diff --git a/spaces/101-5/gpt4free/g4f/.v1/CODE_OF_CONDUCT.md b/spaces/101-5/gpt4free/g4f/.v1/CODE_OF_CONDUCT.md deleted file mode 100644 index c5afe0a46456e33de178e4242232b51fedaf54d9..0000000000000000000000000000000000000000 --- a/spaces/101-5/gpt4free/g4f/.v1/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,128 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -https://t.me/xtekky. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Ativador Do Windows 8.1 Utorrent.md b/spaces/1gistliPinn/ChatGPT4/Examples/Ativador Do Windows 8.1 Utorrent.md deleted file mode 100644 index 9a81e2090986dd89b14f953e6f4bf2a6487df553..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Ativador Do Windows 8.1 Utorrent.md +++ /dev/null @@ -1,6 +0,0 @@ -

Ativador do Windows 8.1 utorrent


DOWNLOAD ->->->-> https://imgfil.com/2uxZSM



- -January 7, 2022 - Windows 8.1 Crack is one of the OS widely used by millions of people besides Windows. This OS is simple and easy to use. If you . NET developer, you will be able to create applications that use most of the technologies available on Windows. But if you are a .NET programmer, then I strongly recommend that you download Windows 8.1. It is a Windows operating system, but with a different architecture, which is an improved version of Windows. All security updates and bug fixes that Windows 8.1 is currently receiving are also available for Windows 8.1. 8a78ff9644
-
-
-

diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/DRAGON BALL LEGENDS APK Actualizado 2022 Join Goku and Friends in Epic 3D Battles.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/DRAGON BALL LEGENDS APK Actualizado 2022 Join Goku and Friends in Epic 3D Battles.md deleted file mode 100644 index ee1589e7ec313db356a74371240e8581d36716b7..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/DRAGON BALL LEGENDS APK Actualizado 2022 Join Goku and Friends in Epic 3D Battles.md +++ /dev/null @@ -1,167 +0,0 @@ -
-

Dragon Ball Legends APK Actualizado 2022: The Ultimate Anime Action RPG for Android

-

If you are a fan of the Dragon Ball anime series, you will love playing Dragon Ball Legends APK, the latest game from Bandai Namco Entertainment. Dragon Ball Legends APK is an action-packed anime RPG that lets you summon your favorite DB characters for battle in stunning 3D graphics. You can enjoy a new original story based on the mysterious Saiyan Shallot, or relive the classic DB sagas with Goku, Vegeta, Frieza, and more. Dragon Ball Legends APK is free to download and play on your Android device, and it is updated regularly with new features and content. In this article, we will tell you everything you need to know about Dragon Ball Legends APK, including its features, how to download and install it, and why you should play it.

-

dragon ball legends apk actualizado 2022


Download > https://urlin.us/2uSX4z



-

What is Dragon Ball Legends APK?

-

Dragon Ball Legends APK is an Android game that is based on the popular Dragon Ball anime series. It is developed by Bandai Namco Entertainment, the same company that created other DB games such as Dragon Ball Z Dokkan Battle and Dragon Ball FighterZ. Dragon Ball Legends APK is an anime action RPG that combines fast-paced fighting with card-based strategy. You can control your favorite DB heroes in 3D battles, using your ability cards to unleash powerful combos and special moves. You can also enjoy a new original story that features a new character designed by Akira Toriyama, the creator of Dragon Ball. You can also join other players from around the world in live PVP matches, or test your skills in casual or ranked matches.

-

Features of Dragon Ball Legends APK

-

Dragon Ball Legends APK has many features that make it one of the best DB games for Android. Here are some of them:

-

Epic 3D visuals and animations

-

Dragon Ball Legends APK brings the anime to life on your mobile device with high-quality 3D characters and stages. You can see your favorite DB heroes and villains in action, with smooth animations and modern takes on their iconic moves. You can also witness the amazing team-based Rising Rush attack, which fills the screen with explosive effects.

-

Intuitive fighting controls and card-based strategy

-

Dragon Ball Legends APK has simple and intuitive fighting controls that let you dodge, counter, and attack your opponent in real time. You can also use your ability cards to build your own strategy, choosing when to use melee, ranged, or special attacks. You can also customize your deck of cards to suit your play style and preferences.

-

dragon ball legends apk mod 2022
-dragon ball legends apk download latest version
-dragon ball legends apk hack 2022
-dragon ball legends apk obb 2022
-dragon ball legends apk unlimited crystals 2022
-dragon ball legends apk offline 2022
-dragon ball legends apk update 2022
-dragon ball legends apk free download 2022
-dragon ball legends apk no verification 2022
-dragon ball legends apk android 2022
-dragon ball legends apk ios 2022
-dragon ball legends apk full 2022
-dragon ball legends apk english 2022
-dragon ball legends apk español 2022
-dragon ball legends apk mega 2022
-dragon ball legends apk mediafire 2022
-dragon ball legends apk uptodown 2022
-dragon ball legends apk revdl 2022
-dragon ball legends apk rexdl 2022
-dragon ball legends apk pure 2022
-dragon ball legends apk mirror 2022
-dragon ball legends apk mob.org 2022
-dragon ball legends apk apkpure 2022
-dragon ball legends apk apkmirror 2022
-dragon ball legends apk apkmody 2022
-dragon ball legends apk andropalace 2022
-dragon ball legends apk android republic 2022
-dragon ball legends apk android oyun club 2022
-dragon ball legends apk android game zone bd 2022
-dragon ball legends apk android gamespot net 2022
-dragon ball legends apk android gamespot com 2022
-dragon ball legends apk android gamespot in 2022
-dragon ball legends apk android gamespot pk 2022
-dragon ball legends apk android gamespot xyz 2022
-dragon ball legends apk android gamespot co uk 2022
-dragon ball legends apk android gamespot ca 2022
-dragon ball legends apk android gamespot au 2022
-dragon ball legends apk android gamespot nz 2022
-dragon ball legends apk android gamespot za 2022
-dragon ball legends apk android gamespot ng 2022
-dragon ball legends apk android gamespot ke 2022
-dragon ball legends apk android gamespot gh 2022
-dragon ball legends apk android gamespot eg 2022
-dragon ball legends apk android gamespot ma 2022
-dragon ball legends apk android gamespot dz 2022
-dragon ball legends apk android gamespot tn 2022
-dragon ball legends apk android gamespot ly 2022
-dragon ball legends apk android gamespot sd 2022
-dragon ball legends apk android gamespot et 2022

-

Original RPG storyline and voice acting

-

Dragon Ball Legends APK has an original RPG storyline that follows the adventures of Shallot, a new Saiyan character designed by Akira Toriyama. You can join Shallot and other DB characters as they try to save the world from a mysterious threat. You can also enjoy voice acting from the original anime cast, which adds more immersion and authenticity to the game.

-

Iconic DB characters and sagas

-

Dragon Ball Legends APK has more than 400 characters to collect and train, from various DB anime series such as DBZ, DBGT, and DBS. You can summon characters such as Goku, Vegeta, Trunks, Piccolo, Frieza, Broly, Majin Buu, and many more. You can also play through classic DB sagas such as the Saiyan Saga, the Frieza Saga, the Cell Saga, and the Tournament of Power Saga. You can also participate in special events and limited-time missions that feature exclusive characters and rewards.

-

How to download and install Dragon Ball Legends APK?

-

Dragon Ball Legends APK is easy to download and install on your Android device. Here are the steps you need to follow:

-

Requirements and compatibility

-

Before you download Dragon Ball Legends APK, you need to make sure that your device meets the following requirements:

- -

You can check the compatibility of your device by visiting the official website of Dragon Ball Legends APK . You can also see the list of supported devices and the minimum specifications for the game.

-

Steps to download and install

-

Once you have confirmed that your device is compatible, you can follow these steps to download and install Dragon Ball Legends APK:

-
    -
  1. Go to the official website of Dragon Ball Legends APK and click on the "Download" button.
  2. -
  3. You will be redirected to a third-party website where you can download the APK file. Click on the "Download APK" button and wait for the file to be downloaded.
  4. -
  5. After the file is downloaded, locate it in your device's file manager and tap on it to install it. You may need to enable "Unknown sources" in your device's settings to allow the installation of apps from sources other than Google Play Store.
  6. -
  7. Follow the on-screen instructions to complete the installation process. You may need to grant some permissions to the app to access your device's features.
  8. -
  9. Once the installation is done, you can launch the app and enjoy playing Dragon Ball Legends APK.
  10. -
-

Tips and tricks to play Dragon Ball Legends APK

-

If you want to improve your skills and performance in Dragon Ball Legends APK, here are some tips and tricks that you can use:

-

Why should you play Dragon Ball Legends APK?

-

Dragon Ball Legends APK is a game that will appeal to any DB fan or anime lover. It has many advantages and benefits that make it worth playing. Here are some of them:

-

Pros and cons of Dragon Ball Legends APK

-

Like any game, Dragon Ball Legends APK has its pros and cons. Here are some of them:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ProsCons
- Free to download and play- Requires internet connection
- Amazing 3D graphics and animations- May drain battery and data
- Simple and fun fighting controls and strategy- May be repetitive and grindy
- Original RPG story and voice acting- May have some bugs and glitches
- Iconic DB characters and sagas- May have some balance issues and power creep
- Online PVP and co-op modes- May have some lag and disconnect issues
- Regular updates and events- May be hard to get rare characters and items
-

Reviews and ratings of Dragon Ball Legends APK

-

Dragon Ball Legends APK has received positive reviews and ratings from players and critics alike. It has a 4.2 out of 5 stars rating on Google Play Store, based on more than 1.5 million reviews. It also has a 4.6 out of 5 stars rating on App Store, based on more than 100 thousand reviews. Some of the comments from the users are:

- -

Comparison with other DB games for Android

-

Dragon Ball Legends APK is not the only DB game for Android. There are other games that you can try, such as:

- -

Conclusion

-

Dragon Ball Legends APK is a great game for anyone who loves DB or anime in general. It is a free-to-play anime action RPG that lets you summon your favorite DB characters for battle in stunning 3D graphics. You can enjoy a new original story based on the mysterious Saiyan Shallot, or relive the classic DB sagas with Goku, Vegeta, Frieza, and more. You can also join other players from around the world in live PVP matches, or test your skills in casual or ranked matches. Dragon Ball Legends APK has many features that make it one of the best DB games for Android, such as epic 3D visuals and animations, intuitive fighting controls and card-based strategy, original RPG storyline and voice acting, and iconic DB characters and sagas. Dragon Ball Legends APK is easy to download and install on your Android device, and it is updated regularly with new features and content. You can also use some tips and tricks to improve your skills and performance in the game. Dragon Ball Legends APK has its pros and cons, as well as reviews and ratings from other players and critics. You can also compare it with other DB games for Android, such as Dragon Ball Z Dokkan Battle, Dragon Ball Z Kakarot, and Dragon Ball FighterZ. We hope that this article has helped you learn more about Dragon Ball Legends APK, and that you will enjoy playing it on your Android device.

-

FAQs

-

Here are some frequently asked questions about Dragon Ball Legends APK:

-

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/232labs/VToonify/vtoonify/model/raft/alt_cuda_corr/correlation.cpp b/spaces/232labs/VToonify/vtoonify/model/raft/alt_cuda_corr/correlation.cpp deleted file mode 100644 index b01584d19edb99e7feec5f2e4c51169a1ed208db..0000000000000000000000000000000000000000 --- a/spaces/232labs/VToonify/vtoonify/model/raft/alt_cuda_corr/correlation.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include -#include - -// CUDA forward declarations -std::vector corr_cuda_forward( - torch::Tensor fmap1, - torch::Tensor fmap2, - torch::Tensor coords, - int radius); - -std::vector corr_cuda_backward( - torch::Tensor fmap1, - torch::Tensor fmap2, - torch::Tensor coords, - torch::Tensor corr_grad, - int radius); - -// C++ interface -#define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor") -#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") -#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) - -std::vector corr_forward( - torch::Tensor fmap1, - torch::Tensor fmap2, - torch::Tensor coords, - int radius) { - CHECK_INPUT(fmap1); - CHECK_INPUT(fmap2); - CHECK_INPUT(coords); - - return corr_cuda_forward(fmap1, fmap2, coords, radius); -} - - -std::vector corr_backward( - torch::Tensor fmap1, - torch::Tensor fmap2, - torch::Tensor coords, - torch::Tensor corr_grad, - int radius) { - CHECK_INPUT(fmap1); - CHECK_INPUT(fmap2); - CHECK_INPUT(coords); - CHECK_INPUT(corr_grad); - - return corr_cuda_backward(fmap1, fmap2, coords, corr_grad, radius); -} - - -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { - m.def("forward", &corr_forward, "CORR forward"); - m.def("backward", &corr_backward, "CORR backward"); -} \ No newline at end of file diff --git a/spaces/2ndelement/voicevox/voicevox_engine/metas/MetasStore.py b/spaces/2ndelement/voicevox/voicevox_engine/metas/MetasStore.py deleted file mode 100644 index 88a7bc37daad4ab70f1e7af07d7beab7eaa06e46..0000000000000000000000000000000000000000 --- a/spaces/2ndelement/voicevox/voicevox_engine/metas/MetasStore.py +++ /dev/null @@ -1,72 +0,0 @@ -import json -from pathlib import Path -from typing import TYPE_CHECKING, Dict, List, Tuple - -from voicevox_engine.metas.Metas import CoreSpeaker, EngineSpeaker, Speaker, StyleInfo - -if TYPE_CHECKING: - from voicevox_engine.synthesis_engine.synthesis_engine_base import ( - SynthesisEngineBase, - ) - - -class MetasStore: - """ - 話者やスタイルのメタ情報を管理する - """ - - def __init__(self, engine_speakers_path: Path) -> None: - self._engine_speakers_path = engine_speakers_path - self._loaded_metas: Dict[str, EngineSpeaker] = { - folder.name: EngineSpeaker( - **json.loads((folder / "metas.json").read_text(encoding="utf-8")) - ) - for folder in engine_speakers_path.iterdir() - } - - def speaker_engine_metas(self, speaker_uuid: str) -> EngineSpeaker: - return self.loaded_metas[speaker_uuid] - - def combine_metas(self, core_metas: List[CoreSpeaker]) -> List[Speaker]: - """ - 与えられたmetaにエンジンのコア情報を付加して返す - core_metas: コアのmetas()が返すJSONのModel - """ - - return [ - Speaker( - **self.speaker_engine_metas(speaker_meta.speaker_uuid).dict(), - **speaker_meta.dict(), - ) - for speaker_meta in core_metas - ] - - # FIXME: engineではなくList[CoreSpeaker]を渡す形にすることで - # SynthesisEngineBaseによる循環importを修正する - def load_combined_metas(self, engine: "SynthesisEngineBase") -> List[Speaker]: - """ - 与えられたエンジンから、コア・エンジン両方の情報を含んだMetasを返す - """ - - core_metas = [CoreSpeaker(**speaker) for speaker in json.loads(engine.speakers)] - return self.combine_metas(core_metas) - - @property - def engine_speakers_path(self) -> Path: - return self._engine_speakers_path - - @property - def loaded_metas(self) -> Dict[str, EngineSpeaker]: - return self._loaded_metas - - -def construct_lookup(speakers: List[Speaker]) -> Dict[int, Tuple[Speaker, StyleInfo]]: - """ - `{style.id: StyleInfo}`の変換テーブル - """ - - lookup_table = dict() - for speaker in speakers: - for style in speaker.styles: - lookup_table[style.id] = (speaker, style) - return lookup_table diff --git a/spaces/7eu7d7/anime-ai-detect-fucker/README.md b/spaces/7eu7d7/anime-ai-detect-fucker/README.md deleted file mode 100644 index fbd7a91df10443b16b5efd2daa5d268237cccff0..0000000000000000000000000000000000000000 --- a/spaces/7eu7d7/anime-ai-detect-fucker/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Anime Ai Detect Attacker -emoji: 🌖 -colorFrom: yellow -colorTo: purple -sdk: gradio -sdk_version: 3.16.2 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/AIFILMS/generate_human_motion/VQ-Trans/utils/eval_trans.py b/spaces/AIFILMS/generate_human_motion/VQ-Trans/utils/eval_trans.py deleted file mode 100644 index 8778bb8cb7e7a320e5f7f2f3b43c7ba0b4c285ab..0000000000000000000000000000000000000000 --- a/spaces/AIFILMS/generate_human_motion/VQ-Trans/utils/eval_trans.py +++ /dev/null @@ -1,580 +0,0 @@ -import os - -import clip -import numpy as np -import torch -from scipy import linalg - -import visualization.plot_3d_global as plot_3d -from utils.motion_process import recover_from_ric - - -def tensorborad_add_video_xyz(writer, xyz, nb_iter, tag, nb_vis=4, title_batch=None, outname=None): - xyz = xyz[:1] - bs, seq = xyz.shape[:2] - xyz = xyz.reshape(bs, seq, -1, 3) - plot_xyz = plot_3d.draw_to_batch(xyz.cpu().numpy(),title_batch, outname) - plot_xyz =np.transpose(plot_xyz, (0, 1, 4, 2, 3)) - writer.add_video(tag, plot_xyz, nb_iter, fps = 20) - -@torch.no_grad() -def evaluation_vqvae(out_dir, val_loader, net, logger, writer, nb_iter, best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, eval_wrapper, draw = True, save = True, savegif=False, savenpy=False) : - net.eval() - nb_sample = 0 - - draw_org = [] - draw_pred = [] - draw_text = [] - - - motion_annotation_list = [] - motion_pred_list = [] - - R_precision_real = 0 - R_precision = 0 - - nb_sample = 0 - matching_score_real = 0 - matching_score_pred = 0 - for batch in val_loader: - word_embeddings, pos_one_hots, caption, sent_len, motion, m_length, token, name = batch - - motion = motion.cuda() - et, em = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, motion, m_length) - bs, seq = motion.shape[0], motion.shape[1] - - num_joints = 21 if motion.shape[-1] == 251 else 22 - - pred_pose_eval = torch.zeros((bs, seq, motion.shape[-1])).cuda() - - for i in range(bs): - pose = val_loader.dataset.inv_transform(motion[i:i+1, :m_length[i], :].detach().cpu().numpy()) - pose_xyz = recover_from_ric(torch.from_numpy(pose).float().cuda(), num_joints) - - - pred_pose, loss_commit, perplexity = net(motion[i:i+1, :m_length[i]]) - pred_denorm = val_loader.dataset.inv_transform(pred_pose.detach().cpu().numpy()) - pred_xyz = recover_from_ric(torch.from_numpy(pred_denorm).float().cuda(), num_joints) - - if savenpy: - np.save(os.path.join(out_dir, name[i]+'_gt.npy'), pose_xyz[:, :m_length[i]].cpu().numpy()) - np.save(os.path.join(out_dir, name[i]+'_pred.npy'), pred_xyz.detach().cpu().numpy()) - - pred_pose_eval[i:i+1,:m_length[i],:] = pred_pose - - if i < min(4, bs): - draw_org.append(pose_xyz) - draw_pred.append(pred_xyz) - draw_text.append(caption[i]) - - et_pred, em_pred = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pred_pose_eval, m_length) - - motion_pred_list.append(em_pred) - motion_annotation_list.append(em) - - temp_R, temp_match = calculate_R_precision(et.cpu().numpy(), em.cpu().numpy(), top_k=3, sum_all=True) - R_precision_real += temp_R - matching_score_real += temp_match - temp_R, temp_match = calculate_R_precision(et_pred.cpu().numpy(), em_pred.cpu().numpy(), top_k=3, sum_all=True) - R_precision += temp_R - matching_score_pred += temp_match - - nb_sample += bs - - motion_annotation_np = torch.cat(motion_annotation_list, dim=0).cpu().numpy() - motion_pred_np = torch.cat(motion_pred_list, dim=0).cpu().numpy() - gt_mu, gt_cov = calculate_activation_statistics(motion_annotation_np) - mu, cov= calculate_activation_statistics(motion_pred_np) - - diversity_real = calculate_diversity(motion_annotation_np, 300 if nb_sample > 300 else 100) - diversity = calculate_diversity(motion_pred_np, 300 if nb_sample > 300 else 100) - - R_precision_real = R_precision_real / nb_sample - R_precision = R_precision / nb_sample - - matching_score_real = matching_score_real / nb_sample - matching_score_pred = matching_score_pred / nb_sample - - fid = calculate_frechet_distance(gt_mu, gt_cov, mu, cov) - - msg = f"--> \t Eva. Iter {nb_iter} :, FID. {fid:.4f}, Diversity Real. {diversity_real:.4f}, Diversity. {diversity:.4f}, R_precision_real. {R_precision_real}, R_precision. {R_precision}, matching_score_real. {matching_score_real}, matching_score_pred. {matching_score_pred}" - logger.info(msg) - - if draw: - writer.add_scalar('./Test/FID', fid, nb_iter) - writer.add_scalar('./Test/Diversity', diversity, nb_iter) - writer.add_scalar('./Test/top1', R_precision[0], nb_iter) - writer.add_scalar('./Test/top2', R_precision[1], nb_iter) - writer.add_scalar('./Test/top3', R_precision[2], nb_iter) - writer.add_scalar('./Test/matching_score', matching_score_pred, nb_iter) - - - if nb_iter % 5000 == 0 : - for ii in range(4): - tensorborad_add_video_xyz(writer, draw_org[ii], nb_iter, tag='./Vis/org_eval'+str(ii), nb_vis=1, title_batch=[draw_text[ii]], outname=[os.path.join(out_dir, 'gt'+str(ii)+'.gif')] if savegif else None) - - if nb_iter % 5000 == 0 : - for ii in range(4): - tensorborad_add_video_xyz(writer, draw_pred[ii], nb_iter, tag='./Vis/pred_eval'+str(ii), nb_vis=1, title_batch=[draw_text[ii]], outname=[os.path.join(out_dir, 'pred'+str(ii)+'.gif')] if savegif else None) - - - if fid < best_fid : - msg = f"--> --> \t FID Improved from {best_fid:.5f} to {fid:.5f} !!!" - logger.info(msg) - best_fid, best_iter = fid, nb_iter - if save: - torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_best_fid.pth')) - - if abs(diversity_real - diversity) < abs(diversity_real - best_div) : - msg = f"--> --> \t Diversity Improved from {best_div:.5f} to {diversity:.5f} !!!" - logger.info(msg) - best_div = diversity - if save: - torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_best_div.pth')) - - if R_precision[0] > best_top1 : - msg = f"--> --> \t Top1 Improved from {best_top1:.4f} to {R_precision[0]:.4f} !!!" - logger.info(msg) - best_top1 = R_precision[0] - if save: - torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_best_top1.pth')) - - if R_precision[1] > best_top2 : - msg = f"--> --> \t Top2 Improved from {best_top2:.4f} to {R_precision[1]:.4f} !!!" - logger.info(msg) - best_top2 = R_precision[1] - - if R_precision[2] > best_top3 : - msg = f"--> --> \t Top3 Improved from {best_top3:.4f} to {R_precision[2]:.4f} !!!" - logger.info(msg) - best_top3 = R_precision[2] - - if matching_score_pred < best_matching : - msg = f"--> --> \t matching_score Improved from {best_matching:.5f} to {matching_score_pred:.5f} !!!" - logger.info(msg) - best_matching = matching_score_pred - if save: - torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_best_matching.pth')) - - if save: - torch.save({'net' : net.state_dict()}, os.path.join(out_dir, 'net_last.pth')) - - net.train() - return best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, writer, logger - - -@torch.no_grad() -def evaluation_transformer(out_dir, val_loader, net, trans, logger, writer, nb_iter, best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, clip_model, eval_wrapper, draw = True, save = True, savegif=False) : - - trans.eval() - nb_sample = 0 - - draw_org = [] - draw_pred = [] - draw_text = [] - draw_text_pred = [] - - motion_annotation_list = [] - motion_pred_list = [] - R_precision_real = 0 - R_precision = 0 - matching_score_real = 0 - matching_score_pred = 0 - - nb_sample = 0 - for i in range(1): - for batch in val_loader: - word_embeddings, pos_one_hots, clip_text, sent_len, pose, m_length, token, name = batch - - bs, seq = pose.shape[:2] - num_joints = 21 if pose.shape[-1] == 251 else 22 - - text = clip.tokenize(clip_text, truncate=True).cuda() - - feat_clip_text = clip_model.encode_text(text).float() - pred_pose_eval = torch.zeros((bs, seq, pose.shape[-1])).cuda() - pred_len = torch.ones(bs).long() - - for k in range(bs): - try: - index_motion = trans.sample(feat_clip_text[k:k+1], False) - except: - index_motion = torch.ones(1,1).cuda().long() - - pred_pose = net.forward_decoder(index_motion) - cur_len = pred_pose.shape[1] - - pred_len[k] = min(cur_len, seq) - pred_pose_eval[k:k+1, :cur_len] = pred_pose[:, :seq] - - if draw: - pred_denorm = val_loader.dataset.inv_transform(pred_pose.detach().cpu().numpy()) - pred_xyz = recover_from_ric(torch.from_numpy(pred_denorm).float().cuda(), num_joints) - - if i == 0 and k < 4: - draw_pred.append(pred_xyz) - draw_text_pred.append(clip_text[k]) - - et_pred, em_pred = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pred_pose_eval, pred_len) - - if i == 0: - pose = pose.cuda().float() - - et, em = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pose, m_length) - motion_annotation_list.append(em) - motion_pred_list.append(em_pred) - - if draw: - pose = val_loader.dataset.inv_transform(pose.detach().cpu().numpy()) - pose_xyz = recover_from_ric(torch.from_numpy(pose).float().cuda(), num_joints) - - - for j in range(min(4, bs)): - draw_org.append(pose_xyz[j][:m_length[j]].unsqueeze(0)) - draw_text.append(clip_text[j]) - - temp_R, temp_match = calculate_R_precision(et.cpu().numpy(), em.cpu().numpy(), top_k=3, sum_all=True) - R_precision_real += temp_R - matching_score_real += temp_match - temp_R, temp_match = calculate_R_precision(et_pred.cpu().numpy(), em_pred.cpu().numpy(), top_k=3, sum_all=True) - R_precision += temp_R - matching_score_pred += temp_match - - nb_sample += bs - - motion_annotation_np = torch.cat(motion_annotation_list, dim=0).cpu().numpy() - motion_pred_np = torch.cat(motion_pred_list, dim=0).cpu().numpy() - gt_mu, gt_cov = calculate_activation_statistics(motion_annotation_np) - mu, cov= calculate_activation_statistics(motion_pred_np) - - diversity_real = calculate_diversity(motion_annotation_np, 300 if nb_sample > 300 else 100) - diversity = calculate_diversity(motion_pred_np, 300 if nb_sample > 300 else 100) - - R_precision_real = R_precision_real / nb_sample - R_precision = R_precision / nb_sample - - matching_score_real = matching_score_real / nb_sample - matching_score_pred = matching_score_pred / nb_sample - - - fid = calculate_frechet_distance(gt_mu, gt_cov, mu, cov) - - msg = f"--> \t Eva. Iter {nb_iter} :, FID. {fid:.4f}, Diversity Real. {diversity_real:.4f}, Diversity. {diversity:.4f}, R_precision_real. {R_precision_real}, R_precision. {R_precision}, matching_score_real. {matching_score_real}, matching_score_pred. {matching_score_pred}" - logger.info(msg) - - - if draw: - writer.add_scalar('./Test/FID', fid, nb_iter) - writer.add_scalar('./Test/Diversity', diversity, nb_iter) - writer.add_scalar('./Test/top1', R_precision[0], nb_iter) - writer.add_scalar('./Test/top2', R_precision[1], nb_iter) - writer.add_scalar('./Test/top3', R_precision[2], nb_iter) - writer.add_scalar('./Test/matching_score', matching_score_pred, nb_iter) - - - if nb_iter % 10000 == 0 : - for ii in range(4): - tensorborad_add_video_xyz(writer, draw_org[ii], nb_iter, tag='./Vis/org_eval'+str(ii), nb_vis=1, title_batch=[draw_text[ii]], outname=[os.path.join(out_dir, 'gt'+str(ii)+'.gif')] if savegif else None) - - if nb_iter % 10000 == 0 : - for ii in range(4): - tensorborad_add_video_xyz(writer, draw_pred[ii], nb_iter, tag='./Vis/pred_eval'+str(ii), nb_vis=1, title_batch=[draw_text_pred[ii]], outname=[os.path.join(out_dir, 'pred'+str(ii)+'.gif')] if savegif else None) - - - if fid < best_fid : - msg = f"--> --> \t FID Improved from {best_fid:.5f} to {fid:.5f} !!!" - logger.info(msg) - best_fid, best_iter = fid, nb_iter - if save: - torch.save({'trans' : trans.state_dict()}, os.path.join(out_dir, 'net_best_fid.pth')) - - if matching_score_pred < best_matching : - msg = f"--> --> \t matching_score Improved from {best_matching:.5f} to {matching_score_pred:.5f} !!!" - logger.info(msg) - best_matching = matching_score_pred - - if abs(diversity_real - diversity) < abs(diversity_real - best_div) : - msg = f"--> --> \t Diversity Improved from {best_div:.5f} to {diversity:.5f} !!!" - logger.info(msg) - best_div = diversity - - if R_precision[0] > best_top1 : - msg = f"--> --> \t Top1 Improved from {best_top1:.4f} to {R_precision[0]:.4f} !!!" - logger.info(msg) - best_top1 = R_precision[0] - - if R_precision[1] > best_top2 : - msg = f"--> --> \t Top2 Improved from {best_top2:.4f} to {R_precision[1]:.4f} !!!" - logger.info(msg) - best_top2 = R_precision[1] - - if R_precision[2] > best_top3 : - msg = f"--> --> \t Top3 Improved from {best_top3:.4f} to {R_precision[2]:.4f} !!!" - logger.info(msg) - best_top3 = R_precision[2] - - if save: - torch.save({'trans' : trans.state_dict()}, os.path.join(out_dir, 'net_last.pth')) - - trans.train() - return best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, writer, logger - - -@torch.no_grad() -def evaluation_transformer_test(out_dir, val_loader, net, trans, logger, writer, nb_iter, best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, best_multi, clip_model, eval_wrapper, draw = True, save = True, savegif=False, savenpy=False) : - - trans.eval() - nb_sample = 0 - - draw_org = [] - draw_pred = [] - draw_text = [] - draw_text_pred = [] - draw_name = [] - - motion_annotation_list = [] - motion_pred_list = [] - motion_multimodality = [] - R_precision_real = 0 - R_precision = 0 - matching_score_real = 0 - matching_score_pred = 0 - - nb_sample = 0 - - for batch in val_loader: - - word_embeddings, pos_one_hots, clip_text, sent_len, pose, m_length, token, name = batch - bs, seq = pose.shape[:2] - num_joints = 21 if pose.shape[-1] == 251 else 22 - - text = clip.tokenize(clip_text, truncate=True).cuda() - - feat_clip_text = clip_model.encode_text(text).float() - motion_multimodality_batch = [] - for i in range(30): - pred_pose_eval = torch.zeros((bs, seq, pose.shape[-1])).cuda() - pred_len = torch.ones(bs).long() - - for k in range(bs): - try: - index_motion = trans.sample(feat_clip_text[k:k+1], True) - except: - index_motion = torch.ones(1,1).cuda().long() - - pred_pose = net.forward_decoder(index_motion) - cur_len = pred_pose.shape[1] - - pred_len[k] = min(cur_len, seq) - pred_pose_eval[k:k+1, :cur_len] = pred_pose[:, :seq] - - if i == 0 and (draw or savenpy): - pred_denorm = val_loader.dataset.inv_transform(pred_pose.detach().cpu().numpy()) - pred_xyz = recover_from_ric(torch.from_numpy(pred_denorm).float().cuda(), num_joints) - - if savenpy: - np.save(os.path.join(out_dir, name[k]+'_pred.npy'), pred_xyz.detach().cpu().numpy()) - - if draw: - if i == 0: - draw_pred.append(pred_xyz) - draw_text_pred.append(clip_text[k]) - draw_name.append(name[k]) - - et_pred, em_pred = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pred_pose_eval, pred_len) - - motion_multimodality_batch.append(em_pred.reshape(bs, 1, -1)) - - if i == 0: - pose = pose.cuda().float() - - et, em = eval_wrapper.get_co_embeddings(word_embeddings, pos_one_hots, sent_len, pose, m_length) - motion_annotation_list.append(em) - motion_pred_list.append(em_pred) - - if draw or savenpy: - pose = val_loader.dataset.inv_transform(pose.detach().cpu().numpy()) - pose_xyz = recover_from_ric(torch.from_numpy(pose).float().cuda(), num_joints) - - if savenpy: - for j in range(bs): - np.save(os.path.join(out_dir, name[j]+'_gt.npy'), pose_xyz[j][:m_length[j]].unsqueeze(0).cpu().numpy()) - - if draw: - for j in range(bs): - draw_org.append(pose_xyz[j][:m_length[j]].unsqueeze(0)) - draw_text.append(clip_text[j]) - - temp_R, temp_match = calculate_R_precision(et.cpu().numpy(), em.cpu().numpy(), top_k=3, sum_all=True) - R_precision_real += temp_R - matching_score_real += temp_match - temp_R, temp_match = calculate_R_precision(et_pred.cpu().numpy(), em_pred.cpu().numpy(), top_k=3, sum_all=True) - R_precision += temp_R - matching_score_pred += temp_match - - nb_sample += bs - - motion_multimodality.append(torch.cat(motion_multimodality_batch, dim=1)) - - motion_annotation_np = torch.cat(motion_annotation_list, dim=0).cpu().numpy() - motion_pred_np = torch.cat(motion_pred_list, dim=0).cpu().numpy() - gt_mu, gt_cov = calculate_activation_statistics(motion_annotation_np) - mu, cov= calculate_activation_statistics(motion_pred_np) - - diversity_real = calculate_diversity(motion_annotation_np, 300 if nb_sample > 300 else 100) - diversity = calculate_diversity(motion_pred_np, 300 if nb_sample > 300 else 100) - - R_precision_real = R_precision_real / nb_sample - R_precision = R_precision / nb_sample - - matching_score_real = matching_score_real / nb_sample - matching_score_pred = matching_score_pred / nb_sample - - multimodality = 0 - motion_multimodality = torch.cat(motion_multimodality, dim=0).cpu().numpy() - multimodality = calculate_multimodality(motion_multimodality, 10) - - fid = calculate_frechet_distance(gt_mu, gt_cov, mu, cov) - - msg = f"--> \t Eva. Iter {nb_iter} :, FID. {fid:.4f}, Diversity Real. {diversity_real:.4f}, Diversity. {diversity:.4f}, R_precision_real. {R_precision_real}, R_precision. {R_precision}, matching_score_real. {matching_score_real}, matching_score_pred. {matching_score_pred}, multimodality. {multimodality:.4f}" - logger.info(msg) - - - if draw: - for ii in range(len(draw_org)): - tensorborad_add_video_xyz(writer, draw_org[ii], nb_iter, tag='./Vis/'+draw_name[ii]+'_org', nb_vis=1, title_batch=[draw_text[ii]], outname=[os.path.join(out_dir, draw_name[ii]+'_skel_gt.gif')] if savegif else None) - - tensorborad_add_video_xyz(writer, draw_pred[ii], nb_iter, tag='./Vis/'+draw_name[ii]+'_pred', nb_vis=1, title_batch=[draw_text_pred[ii]], outname=[os.path.join(out_dir, draw_name[ii]+'_skel_pred.gif')] if savegif else None) - - trans.train() - return fid, best_iter, diversity, R_precision[0], R_precision[1], R_precision[2], matching_score_pred, multimodality, writer, logger - -# (X - X_train)*(X - X_train) = -2X*X_train + X*X + X_train*X_train -def euclidean_distance_matrix(matrix1, matrix2): - """ - Params: - -- matrix1: N1 x D - -- matrix2: N2 x D - Returns: - -- dist: N1 x N2 - dist[i, j] == distance(matrix1[i], matrix2[j]) - """ - assert matrix1.shape[1] == matrix2.shape[1] - d1 = -2 * np.dot(matrix1, matrix2.T) # shape (num_test, num_train) - d2 = np.sum(np.square(matrix1), axis=1, keepdims=True) # shape (num_test, 1) - d3 = np.sum(np.square(matrix2), axis=1) # shape (num_train, ) - dists = np.sqrt(d1 + d2 + d3) # broadcasting - return dists - - - -def calculate_top_k(mat, top_k): - size = mat.shape[0] - gt_mat = np.expand_dims(np.arange(size), 1).repeat(size, 1) - bool_mat = (mat == gt_mat) - correct_vec = False - top_k_list = [] - for i in range(top_k): -# print(correct_vec, bool_mat[:, i]) - correct_vec = (correct_vec | bool_mat[:, i]) - # print(correct_vec) - top_k_list.append(correct_vec[:, None]) - top_k_mat = np.concatenate(top_k_list, axis=1) - return top_k_mat - - -def calculate_R_precision(embedding1, embedding2, top_k, sum_all=False): - dist_mat = euclidean_distance_matrix(embedding1, embedding2) - matching_score = dist_mat.trace() - argmax = np.argsort(dist_mat, axis=1) - top_k_mat = calculate_top_k(argmax, top_k) - if sum_all: - return top_k_mat.sum(axis=0), matching_score - else: - return top_k_mat, matching_score - -def calculate_multimodality(activation, multimodality_times): - assert len(activation.shape) == 3 - assert activation.shape[1] > multimodality_times - num_per_sent = activation.shape[1] - - first_dices = np.random.choice(num_per_sent, multimodality_times, replace=False) - second_dices = np.random.choice(num_per_sent, multimodality_times, replace=False) - dist = linalg.norm(activation[:, first_dices] - activation[:, second_dices], axis=2) - return dist.mean() - - -def calculate_diversity(activation, diversity_times): - assert len(activation.shape) == 2 - assert activation.shape[0] > diversity_times - num_samples = activation.shape[0] - - first_indices = np.random.choice(num_samples, diversity_times, replace=False) - second_indices = np.random.choice(num_samples, diversity_times, replace=False) - dist = linalg.norm(activation[first_indices] - activation[second_indices], axis=1) - return dist.mean() - - - -def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): - - mu1 = np.atleast_1d(mu1) - mu2 = np.atleast_1d(mu2) - - sigma1 = np.atleast_2d(sigma1) - sigma2 = np.atleast_2d(sigma2) - - assert mu1.shape == mu2.shape, \ - 'Training and test mean vectors have different lengths' - assert sigma1.shape == sigma2.shape, \ - 'Training and test covariances have different dimensions' - - diff = mu1 - mu2 - - # Product might be almost singular - covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False) - if not np.isfinite(covmean).all(): - msg = ('fid calculation produces singular product; ' - 'adding %s to diagonal of cov estimates') % eps - print(msg) - offset = np.eye(sigma1.shape[0]) * eps - covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset)) - - # Numerical error might give slight imaginary component - if np.iscomplexobj(covmean): - if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3): - m = np.max(np.abs(covmean.imag)) - raise ValueError('Imaginary component {}'.format(m)) - covmean = covmean.real - - tr_covmean = np.trace(covmean) - - return (diff.dot(diff) + np.trace(sigma1) - + np.trace(sigma2) - 2 * tr_covmean) - - - -def calculate_activation_statistics(activations): - - mu = np.mean(activations, axis=0) - cov = np.cov(activations, rowvar=False) - return mu, cov - - -def calculate_frechet_feature_distance(feature_list1, feature_list2): - feature_list1 = np.stack(feature_list1) - feature_list2 = np.stack(feature_list2) - - # normalize the scale - mean = np.mean(feature_list1, axis=0) - std = np.std(feature_list1, axis=0) + 1e-10 - feature_list1 = (feature_list1 - mean) / std - feature_list2 = (feature_list2 - mean) / std - - dist = calculate_frechet_distance( - mu1=np.mean(feature_list1, axis=0), - sigma1=np.cov(feature_list1, rowvar=False), - mu2=np.mean(feature_list2, axis=0), - sigma2=np.cov(feature_list2, rowvar=False), - ) - return dist \ No newline at end of file diff --git a/spaces/AIGC-Audio/AudioGPT/NeuralSeq/data_gen/tts/wav_processors/__init__.py b/spaces/AIGC-Audio/AudioGPT/NeuralSeq/data_gen/tts/wav_processors/__init__.py deleted file mode 100644 index 4be97b377dcb95a0e6bceb876ac0ce93c8290249..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/NeuralSeq/data_gen/tts/wav_processors/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from . import base_processor -from . import common_processors diff --git a/spaces/AIGC-Audio/AudioGPT/NeuralSeq/tasks/tts/tts.py b/spaces/AIGC-Audio/AudioGPT/NeuralSeq/tasks/tts/tts.py deleted file mode 100644 index f803c1e738137cb1eca19a1943196abd2884c0a5..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/NeuralSeq/tasks/tts/tts.py +++ /dev/null @@ -1,131 +0,0 @@ -from multiprocessing.pool import Pool - -import matplotlib - -from utils.pl_utils import data_loader -from utils.training_utils import RSQRTSchedule -from vocoders.base_vocoder import get_vocoder_cls, BaseVocoder -from modules.fastspeech.pe import PitchExtractor - -matplotlib.use('Agg') -import os -import numpy as np -from tqdm import tqdm -import torch.distributed as dist - -from tasks.base_task import BaseTask -from utils.hparams import hparams -from utils.text_encoder import TokenTextEncoder -import json - -import torch -import torch.optim -import torch.utils.data -import utils - - - -class TtsTask(BaseTask): - def __init__(self, *args, **kwargs): - self.vocoder = None - self.phone_encoder = self.build_phone_encoder(hparams['binary_data_dir']) - self.padding_idx = self.phone_encoder.pad() - self.eos_idx = self.phone_encoder.eos() - self.seg_idx = self.phone_encoder.seg() - self.saving_result_pool = None - self.saving_results_futures = None - self.stats = {} - super().__init__(*args, **kwargs) - - def build_scheduler(self, optimizer): - return RSQRTSchedule(optimizer) - - def build_optimizer(self, model): - self.optimizer = optimizer = torch.optim.AdamW( - model.parameters(), - lr=hparams['lr']) - return optimizer - - def build_dataloader(self, dataset, shuffle, max_tokens=None, max_sentences=None, - required_batch_size_multiple=-1, endless=False, batch_by_size=True): - devices_cnt = torch.cuda.device_count() - if devices_cnt == 0: - devices_cnt = 1 - if required_batch_size_multiple == -1: - required_batch_size_multiple = devices_cnt - - def shuffle_batches(batches): - np.random.shuffle(batches) - return batches - - if max_tokens is not None: - max_tokens *= devices_cnt - if max_sentences is not None: - max_sentences *= devices_cnt - indices = dataset.ordered_indices() - if batch_by_size: - batch_sampler = utils.batch_by_size( - indices, dataset.num_tokens, max_tokens=max_tokens, max_sentences=max_sentences, - required_batch_size_multiple=required_batch_size_multiple, - ) - else: - batch_sampler = [] - for i in range(0, len(indices), max_sentences): - batch_sampler.append(indices[i:i + max_sentences]) - - if shuffle: - batches = shuffle_batches(list(batch_sampler)) - if endless: - batches = [b for _ in range(1000) for b in shuffle_batches(list(batch_sampler))] - else: - batches = batch_sampler - if endless: - batches = [b for _ in range(1000) for b in batches] - num_workers = dataset.num_workers - if self.trainer.use_ddp: - num_replicas = dist.get_world_size() - rank = dist.get_rank() - batches = [x[rank::num_replicas] for x in batches if len(x) % num_replicas == 0] - return torch.utils.data.DataLoader(dataset, - collate_fn=dataset.collater, - batch_sampler=batches, - num_workers=num_workers, - pin_memory=False) - - def build_phone_encoder(self, data_dir): - phone_list_file = os.path.join(data_dir, 'phone_set.json') - - phone_list = json.load(open(phone_list_file)) - return TokenTextEncoder(None, vocab_list=phone_list, replace_oov=',') - - def build_optimizer(self, model): - self.optimizer = optimizer = torch.optim.AdamW( - model.parameters(), - lr=hparams['lr']) - return optimizer - - def test_start(self): - self.saving_result_pool = Pool(8) - self.saving_results_futures = [] - self.vocoder: BaseVocoder = get_vocoder_cls(hparams)() - if hparams.get('pe_enable') is not None and hparams['pe_enable']: - self.pe = PitchExtractor().cuda() - utils.load_ckpt(self.pe, hparams['pe_ckpt'], 'model', strict=True) - self.pe.eval() - def test_end(self, outputs): - self.saving_result_pool.close() - [f.get() for f in tqdm(self.saving_results_futures)] - self.saving_result_pool.join() - return {} - - ########## - # utils - ########## - def weights_nonzero_speech(self, target): - # target : B x T x mel - # Assign weight 1.0 to all labels except for padding (id=0). - dim = target.size(-1) - return target.abs().sum(-1, keepdim=True).ne(0).float().repeat(1, 1, dim) - -if __name__ == '__main__': - TtsTask.start() diff --git a/spaces/ALSv/FSW/roop/__init__.py b/spaces/ALSv/FSW/roop/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_1_ClothesKeyPoint/work_dirs_1-x/td_hm_res50_4xb64-60e_deepfashion2_trousers_256x192/td_hm_res50_4xb64-60e_deepfashion2_trousers_256x192.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_1_ClothesKeyPoint/work_dirs_1-x/td_hm_res50_4xb64-60e_deepfashion2_trousers_256x192/td_hm_res50_4xb64-60e_deepfashion2_trousers_256x192.py deleted file mode 100644 index 892d55b7cedfb1217800eb200e8a47327b500437..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_1_ClothesKeyPoint/work_dirs_1-x/td_hm_res50_4xb64-60e_deepfashion2_trousers_256x192/td_hm_res50_4xb64-60e_deepfashion2_trousers_256x192.py +++ /dev/null @@ -1,2861 +0,0 @@ -default_scope = 'mmpose' -default_hooks = dict( - timer=dict(type='IterTimerHook'), - logger=dict(type='LoggerHook', interval=50), - param_scheduler=dict(type='ParamSchedulerHook'), - checkpoint=dict( - type='CheckpointHook', interval=10, save_best='PCK', rule='greater'), - sampler_seed=dict(type='DistSamplerSeedHook'), - visualization=dict(type='PoseVisualizationHook', enable=False)) -custom_hooks = [dict(type='SyncBuffersHook')] -env_cfg = dict( - cudnn_benchmark=False, - mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), - dist_cfg=dict(backend='nccl')) -vis_backends = [dict(type='LocalVisBackend')] -visualizer = dict( - type='PoseLocalVisualizer', - vis_backends=[dict(type='LocalVisBackend'), - dict(type='WandbVisBackend')], - name='visualizer') -log_processor = dict( - type='LogProcessor', window_size=50, by_epoch=True, num_digits=6) -log_level = 'INFO' -load_from = None -resume = False -backend_args = dict(backend='local') -train_cfg = dict(by_epoch=True, max_epochs=60, val_interval=10) -val_cfg = dict() -test_cfg = dict() -colors = dict( - sss=[255, 128, 0], - lss=[255, 0, 128], - sso=[128, 0, 255], - lso=[0, 128, 255], - vest=[0, 128, 128], - sling=[0, 0, 128], - shorts=[128, 128, 128], - trousers=[128, 0, 128], - skirt=[64, 128, 128], - ssd=[64, 64, 128], - lsd=[128, 64, 0], - vd=[128, 64, 255], - sd=[128, 64, 0]) -dataset_info = dict( - dataset_name='deepfashion2', - paper_info=dict( - author= - 'Yuying Ge and Ruimao Zhang and Lingyun Wu and Xiaogang Wang and Xiaoou Tang and Ping Luo', - title= - 'DeepFashion2: A Versatile Benchmark for Detection, Pose Estimation, Segmentation and Re-Identification of Clothing Images', - container= - 'Proceedings of IEEE Conference on Computer Vision and Pattern Recognition (CVPR)', - year='2019', - homepage='https://github.com/switchablenorms/DeepFashion2'), - keypoint_info=dict({ - 0: - dict(name='sss_kpt1', id=0, color=[255, 128, 0], type='', swap=''), - 1: - dict( - name='sss_kpt2', - id=1, - color=[255, 128, 0], - type='', - swap='sss_kpt6'), - 2: - dict( - name='sss_kpt3', - id=2, - color=[255, 128, 0], - type='', - swap='sss_kpt5'), - 3: - dict(name='sss_kpt4', id=3, color=[255, 128, 0], type='', swap=''), - 4: - dict( - name='sss_kpt5', - id=4, - color=[255, 128, 0], - type='', - swap='sss_kpt3'), - 5: - dict( - name='sss_kpt6', - id=5, - color=[255, 128, 0], - type='', - swap='sss_kpt2'), - 6: - dict( - name='sss_kpt7', - id=6, - color=[255, 128, 0], - type='', - swap='sss_kpt25'), - 7: - dict( - name='sss_kpt8', - id=7, - color=[255, 128, 0], - type='', - swap='sss_kpt24'), - 8: - dict( - name='sss_kpt9', - id=8, - color=[255, 128, 0], - type='', - swap='sss_kpt23'), - 9: - dict( - name='sss_kpt10', - id=9, - color=[255, 128, 0], - type='', - swap='sss_kpt22'), - 10: - dict( - name='sss_kpt11', - id=10, - color=[255, 128, 0], - type='', - swap='sss_kpt21'), - 11: - dict( - name='sss_kpt12', - id=11, - color=[255, 128, 0], - type='', - swap='sss_kpt20'), - 12: - dict( - name='sss_kpt13', - id=12, - color=[255, 128, 0], - type='', - swap='sss_kpt19'), - 13: - dict( - name='sss_kpt14', - id=13, - color=[255, 128, 0], - type='', - swap='sss_kpt18'), - 14: - dict( - name='sss_kpt15', - id=14, - color=[255, 128, 0], - type='', - swap='sss_kpt17'), - 15: - dict(name='sss_kpt16', id=15, color=[255, 128, 0], type='', swap=''), - 16: - dict( - name='sss_kpt17', - id=16, - color=[255, 128, 0], - type='', - swap='sss_kpt15'), - 17: - dict( - name='sss_kpt18', - id=17, - color=[255, 128, 0], - type='', - swap='sss_kpt14'), - 18: - dict( - name='sss_kpt19', - id=18, - color=[255, 128, 0], - type='', - swap='sss_kpt13'), - 19: - dict( - name='sss_kpt20', - id=19, - color=[255, 128, 0], - type='', - swap='sss_kpt12'), - 20: - dict( - name='sss_kpt21', - id=20, - color=[255, 128, 0], - type='', - swap='sss_kpt11'), - 21: - dict( - name='sss_kpt22', - id=21, - color=[255, 128, 0], - type='', - swap='sss_kpt10'), - 22: - dict( - name='sss_kpt23', - id=22, - color=[255, 128, 0], - type='', - swap='sss_kpt9'), - 23: - dict( - name='sss_kpt24', - id=23, - color=[255, 128, 0], - type='', - swap='sss_kpt8'), - 24: - dict( - name='sss_kpt25', - id=24, - color=[255, 128, 0], - type='', - swap='sss_kpt7'), - 25: - dict(name='lss_kpt1', id=25, color=[255, 0, 128], type='', swap=''), - 26: - dict( - name='lss_kpt2', - id=26, - color=[255, 0, 128], - type='', - swap='lss_kpt6'), - 27: - dict( - name='lss_kpt3', - id=27, - color=[255, 0, 128], - type='', - swap='lss_kpt5'), - 28: - dict(name='lss_kpt4', id=28, color=[255, 0, 128], type='', swap=''), - 29: - dict( - name='lss_kpt5', - id=29, - color=[255, 0, 128], - type='', - swap='lss_kpt3'), - 30: - dict( - name='lss_kpt6', - id=30, - color=[255, 0, 128], - type='', - swap='lss_kpt2'), - 31: - dict( - name='lss_kpt7', - id=31, - color=[255, 0, 128], - type='', - swap='lss_kpt33'), - 32: - dict( - name='lss_kpt8', - id=32, - color=[255, 0, 128], - type='', - swap='lss_kpt32'), - 33: - dict( - name='lss_kpt9', - id=33, - color=[255, 0, 128], - type='', - swap='lss_kpt31'), - 34: - dict( - name='lss_kpt10', - id=34, - color=[255, 0, 128], - type='', - swap='lss_kpt30'), - 35: - dict( - name='lss_kpt11', - id=35, - color=[255, 0, 128], - type='', - swap='lss_kpt29'), - 36: - dict( - name='lss_kpt12', - id=36, - color=[255, 0, 128], - type='', - swap='lss_kpt28'), - 37: - dict( - name='lss_kpt13', - id=37, - color=[255, 0, 128], - type='', - swap='lss_kpt27'), - 38: - dict( - name='lss_kpt14', - id=38, - color=[255, 0, 128], - type='', - swap='lss_kpt26'), - 39: - dict( - name='lss_kpt15', - id=39, - color=[255, 0, 128], - type='', - swap='lss_kpt25'), - 40: - dict( - name='lss_kpt16', - id=40, - color=[255, 0, 128], - type='', - swap='lss_kpt24'), - 41: - dict( - name='lss_kpt17', - id=41, - color=[255, 0, 128], - type='', - swap='lss_kpt23'), - 42: - dict( - name='lss_kpt18', - id=42, - color=[255, 0, 128], - type='', - swap='lss_kpt22'), - 43: - dict( - name='lss_kpt19', - id=43, - color=[255, 0, 128], - type='', - swap='lss_kpt21'), - 44: - dict(name='lss_kpt20', id=44, color=[255, 0, 128], type='', swap=''), - 45: - dict( - name='lss_kpt21', - id=45, - color=[255, 0, 128], - type='', - swap='lss_kpt19'), - 46: - dict( - name='lss_kpt22', - id=46, - color=[255, 0, 128], - type='', - swap='lss_kpt18'), - 47: - dict( - name='lss_kpt23', - id=47, - color=[255, 0, 128], - type='', - swap='lss_kpt17'), - 48: - dict( - name='lss_kpt24', - id=48, - color=[255, 0, 128], - type='', - swap='lss_kpt16'), - 49: - dict( - name='lss_kpt25', - id=49, - color=[255, 0, 128], - type='', - swap='lss_kpt15'), - 50: - dict( - name='lss_kpt26', - id=50, - color=[255, 0, 128], - type='', - swap='lss_kpt14'), - 51: - dict( - name='lss_kpt27', - id=51, - color=[255, 0, 128], - type='', - swap='lss_kpt13'), - 52: - dict( - name='lss_kpt28', - id=52, - color=[255, 0, 128], - type='', - swap='lss_kpt12'), - 53: - dict( - name='lss_kpt29', - id=53, - color=[255, 0, 128], - type='', - swap='lss_kpt11'), - 54: - dict( - name='lss_kpt30', - id=54, - color=[255, 0, 128], - type='', - swap='lss_kpt10'), - 55: - dict( - name='lss_kpt31', - id=55, - color=[255, 0, 128], - type='', - swap='lss_kpt9'), - 56: - dict( - name='lss_kpt32', - id=56, - color=[255, 0, 128], - type='', - swap='lss_kpt8'), - 57: - dict( - name='lss_kpt33', - id=57, - color=[255, 0, 128], - type='', - swap='lss_kpt7'), - 58: - dict(name='sso_kpt1', id=58, color=[128, 0, 255], type='', swap=''), - 59: - dict( - name='sso_kpt2', - id=59, - color=[128, 0, 255], - type='', - swap='sso_kpt26'), - 60: - dict( - name='sso_kpt3', - id=60, - color=[128, 0, 255], - type='', - swap='sso_kpt5'), - 61: - dict( - name='sso_kpt4', - id=61, - color=[128, 0, 255], - type='', - swap='sso_kpt6'), - 62: - dict( - name='sso_kpt5', - id=62, - color=[128, 0, 255], - type='', - swap='sso_kpt3'), - 63: - dict( - name='sso_kpt6', - id=63, - color=[128, 0, 255], - type='', - swap='sso_kpt4'), - 64: - dict( - name='sso_kpt7', - id=64, - color=[128, 0, 255], - type='', - swap='sso_kpt25'), - 65: - dict( - name='sso_kpt8', - id=65, - color=[128, 0, 255], - type='', - swap='sso_kpt24'), - 66: - dict( - name='sso_kpt9', - id=66, - color=[128, 0, 255], - type='', - swap='sso_kpt23'), - 67: - dict( - name='sso_kpt10', - id=67, - color=[128, 0, 255], - type='', - swap='sso_kpt22'), - 68: - dict( - name='sso_kpt11', - id=68, - color=[128, 0, 255], - type='', - swap='sso_kpt21'), - 69: - dict( - name='sso_kpt12', - id=69, - color=[128, 0, 255], - type='', - swap='sso_kpt20'), - 70: - dict( - name='sso_kpt13', - id=70, - color=[128, 0, 255], - type='', - swap='sso_kpt19'), - 71: - dict( - name='sso_kpt14', - id=71, - color=[128, 0, 255], - type='', - swap='sso_kpt18'), - 72: - dict( - name='sso_kpt15', - id=72, - color=[128, 0, 255], - type='', - swap='sso_kpt17'), - 73: - dict( - name='sso_kpt16', - id=73, - color=[128, 0, 255], - type='', - swap='sso_kpt29'), - 74: - dict( - name='sso_kpt17', - id=74, - color=[128, 0, 255], - type='', - swap='sso_kpt15'), - 75: - dict( - name='sso_kpt18', - id=75, - color=[128, 0, 255], - type='', - swap='sso_kpt14'), - 76: - dict( - name='sso_kpt19', - id=76, - color=[128, 0, 255], - type='', - swap='sso_kpt13'), - 77: - dict( - name='sso_kpt20', - id=77, - color=[128, 0, 255], - type='', - swap='sso_kpt12'), - 78: - dict( - name='sso_kpt21', - id=78, - color=[128, 0, 255], - type='', - swap='sso_kpt11'), - 79: - dict( - name='sso_kpt22', - id=79, - color=[128, 0, 255], - type='', - swap='sso_kpt10'), - 80: - dict( - name='sso_kpt23', - id=80, - color=[128, 0, 255], - type='', - swap='sso_kpt9'), - 81: - dict( - name='sso_kpt24', - id=81, - color=[128, 0, 255], - type='', - swap='sso_kpt8'), - 82: - dict( - name='sso_kpt25', - id=82, - color=[128, 0, 255], - type='', - swap='sso_kpt7'), - 83: - dict( - name='sso_kpt26', - id=83, - color=[128, 0, 255], - type='', - swap='sso_kpt2'), - 84: - dict( - name='sso_kpt27', - id=84, - color=[128, 0, 255], - type='', - swap='sso_kpt30'), - 85: - dict( - name='sso_kpt28', - id=85, - color=[128, 0, 255], - type='', - swap='sso_kpt31'), - 86: - dict( - name='sso_kpt29', - id=86, - color=[128, 0, 255], - type='', - swap='sso_kpt16'), - 87: - dict( - name='sso_kpt30', - id=87, - color=[128, 0, 255], - type='', - swap='sso_kpt27'), - 88: - dict( - name='sso_kpt31', - id=88, - color=[128, 0, 255], - type='', - swap='sso_kpt28'), - 89: - dict(name='lso_kpt1', id=89, color=[0, 128, 255], type='', swap=''), - 90: - dict( - name='lso_kpt2', - id=90, - color=[0, 128, 255], - type='', - swap='lso_kpt6'), - 91: - dict( - name='lso_kpt3', - id=91, - color=[0, 128, 255], - type='', - swap='lso_kpt5'), - 92: - dict( - name='lso_kpt4', - id=92, - color=[0, 128, 255], - type='', - swap='lso_kpt34'), - 93: - dict( - name='lso_kpt5', - id=93, - color=[0, 128, 255], - type='', - swap='lso_kpt3'), - 94: - dict( - name='lso_kpt6', - id=94, - color=[0, 128, 255], - type='', - swap='lso_kpt2'), - 95: - dict( - name='lso_kpt7', - id=95, - color=[0, 128, 255], - type='', - swap='lso_kpt33'), - 96: - dict( - name='lso_kpt8', - id=96, - color=[0, 128, 255], - type='', - swap='lso_kpt32'), - 97: - dict( - name='lso_kpt9', - id=97, - color=[0, 128, 255], - type='', - swap='lso_kpt31'), - 98: - dict( - name='lso_kpt10', - id=98, - color=[0, 128, 255], - type='', - swap='lso_kpt30'), - 99: - dict( - name='lso_kpt11', - id=99, - color=[0, 128, 255], - type='', - swap='lso_kpt29'), - 100: - dict( - name='lso_kpt12', - id=100, - color=[0, 128, 255], - type='', - swap='lso_kpt28'), - 101: - dict( - name='lso_kpt13', - id=101, - color=[0, 128, 255], - type='', - swap='lso_kpt27'), - 102: - dict( - name='lso_kpt14', - id=102, - color=[0, 128, 255], - type='', - swap='lso_kpt26'), - 103: - dict( - name='lso_kpt15', - id=103, - color=[0, 128, 255], - type='', - swap='lso_kpt25'), - 104: - dict( - name='lso_kpt16', - id=104, - color=[0, 128, 255], - type='', - swap='lso_kpt24'), - 105: - dict( - name='lso_kpt17', - id=105, - color=[0, 128, 255], - type='', - swap='lso_kpt23'), - 106: - dict( - name='lso_kpt18', - id=106, - color=[0, 128, 255], - type='', - swap='lso_kpt22'), - 107: - dict( - name='lso_kpt19', - id=107, - color=[0, 128, 255], - type='', - swap='lso_kpt21'), - 108: - dict( - name='lso_kpt20', - id=108, - color=[0, 128, 255], - type='', - swap='lso_kpt37'), - 109: - dict( - name='lso_kpt21', - id=109, - color=[0, 128, 255], - type='', - swap='lso_kpt19'), - 110: - dict( - name='lso_kpt22', - id=110, - color=[0, 128, 255], - type='', - swap='lso_kpt18'), - 111: - dict( - name='lso_kpt23', - id=111, - color=[0, 128, 255], - type='', - swap='lso_kpt17'), - 112: - dict( - name='lso_kpt24', - id=112, - color=[0, 128, 255], - type='', - swap='lso_kpt16'), - 113: - dict( - name='lso_kpt25', - id=113, - color=[0, 128, 255], - type='', - swap='lso_kpt15'), - 114: - dict( - name='lso_kpt26', - id=114, - color=[0, 128, 255], - type='', - swap='lso_kpt14'), - 115: - dict( - name='lso_kpt27', - id=115, - color=[0, 128, 255], - type='', - swap='lso_kpt13'), - 116: - dict( - name='lso_kpt28', - id=116, - color=[0, 128, 255], - type='', - swap='lso_kpt12'), - 117: - dict( - name='lso_kpt29', - id=117, - color=[0, 128, 255], - type='', - swap='lso_kpt11'), - 118: - dict( - name='lso_kpt30', - id=118, - color=[0, 128, 255], - type='', - swap='lso_kpt10'), - 119: - dict( - name='lso_kpt31', - id=119, - color=[0, 128, 255], - type='', - swap='lso_kpt9'), - 120: - dict( - name='lso_kpt32', - id=120, - color=[0, 128, 255], - type='', - swap='lso_kpt8'), - 121: - dict( - name='lso_kpt33', - id=121, - color=[0, 128, 255], - type='', - swap='lso_kpt7'), - 122: - dict( - name='lso_kpt34', - id=122, - color=[0, 128, 255], - type='', - swap='lso_kpt4'), - 123: - dict( - name='lso_kpt35', - id=123, - color=[0, 128, 255], - type='', - swap='lso_kpt38'), - 124: - dict( - name='lso_kpt36', - id=124, - color=[0, 128, 255], - type='', - swap='lso_kpt39'), - 125: - dict( - name='lso_kpt37', - id=125, - color=[0, 128, 255], - type='', - swap='lso_kpt20'), - 126: - dict( - name='lso_kpt38', - id=126, - color=[0, 128, 255], - type='', - swap='lso_kpt35'), - 127: - dict( - name='lso_kpt39', - id=127, - color=[0, 128, 255], - type='', - swap='lso_kpt36'), - 128: - dict(name='vest_kpt1', id=128, color=[0, 128, 128], type='', swap=''), - 129: - dict( - name='vest_kpt2', - id=129, - color=[0, 128, 128], - type='', - swap='vest_kpt6'), - 130: - dict( - name='vest_kpt3', - id=130, - color=[0, 128, 128], - type='', - swap='vest_kpt5'), - 131: - dict(name='vest_kpt4', id=131, color=[0, 128, 128], type='', swap=''), - 132: - dict( - name='vest_kpt5', - id=132, - color=[0, 128, 128], - type='', - swap='vest_kpt3'), - 133: - dict( - name='vest_kpt6', - id=133, - color=[0, 128, 128], - type='', - swap='vest_kpt2'), - 134: - dict( - name='vest_kpt7', - id=134, - color=[0, 128, 128], - type='', - swap='vest_kpt15'), - 135: - dict( - name='vest_kpt8', - id=135, - color=[0, 128, 128], - type='', - swap='vest_kpt14'), - 136: - dict( - name='vest_kpt9', - id=136, - color=[0, 128, 128], - type='', - swap='vest_kpt13'), - 137: - dict( - name='vest_kpt10', - id=137, - color=[0, 128, 128], - type='', - swap='vest_kpt12'), - 138: - dict(name='vest_kpt11', id=138, color=[0, 128, 128], type='', swap=''), - 139: - dict( - name='vest_kpt12', - id=139, - color=[0, 128, 128], - type='', - swap='vest_kpt10'), - 140: - dict(name='vest_kpt13', id=140, color=[0, 128, 128], type='', swap=''), - 141: - dict( - name='vest_kpt14', - id=141, - color=[0, 128, 128], - type='', - swap='vest_kpt8'), - 142: - dict( - name='vest_kpt15', - id=142, - color=[0, 128, 128], - type='', - swap='vest_kpt7'), - 143: - dict(name='sling_kpt1', id=143, color=[0, 0, 128], type='', swap=''), - 144: - dict( - name='sling_kpt2', - id=144, - color=[0, 0, 128], - type='', - swap='sling_kpt6'), - 145: - dict( - name='sling_kpt3', - id=145, - color=[0, 0, 128], - type='', - swap='sling_kpt5'), - 146: - dict(name='sling_kpt4', id=146, color=[0, 0, 128], type='', swap=''), - 147: - dict( - name='sling_kpt5', - id=147, - color=[0, 0, 128], - type='', - swap='sling_kpt3'), - 148: - dict( - name='sling_kpt6', - id=148, - color=[0, 0, 128], - type='', - swap='sling_kpt2'), - 149: - dict( - name='sling_kpt7', - id=149, - color=[0, 0, 128], - type='', - swap='sling_kpt15'), - 150: - dict( - name='sling_kpt8', - id=150, - color=[0, 0, 128], - type='', - swap='sling_kpt14'), - 151: - dict( - name='sling_kpt9', - id=151, - color=[0, 0, 128], - type='', - swap='sling_kpt13'), - 152: - dict( - name='sling_kpt10', - id=152, - color=[0, 0, 128], - type='', - swap='sling_kpt12'), - 153: - dict(name='sling_kpt11', id=153, color=[0, 0, 128], type='', swap=''), - 154: - dict( - name='sling_kpt12', - id=154, - color=[0, 0, 128], - type='', - swap='sling_kpt10'), - 155: - dict( - name='sling_kpt13', - id=155, - color=[0, 0, 128], - type='', - swap='sling_kpt9'), - 156: - dict( - name='sling_kpt14', - id=156, - color=[0, 0, 128], - type='', - swap='sling_kpt8'), - 157: - dict( - name='sling_kpt15', - id=157, - color=[0, 0, 128], - type='', - swap='sling_kpt7'), - 158: - dict( - name='shorts_kpt1', - id=158, - color=[128, 128, 128], - type='', - swap='shorts_kpt3'), - 159: - dict( - name='shorts_kpt2', - id=159, - color=[128, 128, 128], - type='', - swap=''), - 160: - dict( - name='shorts_kpt3', - id=160, - color=[128, 128, 128], - type='', - swap='shorts_kpt1'), - 161: - dict( - name='shorts_kpt4', - id=161, - color=[128, 128, 128], - type='', - swap='shorts_kpt10'), - 162: - dict( - name='shorts_kpt5', - id=162, - color=[128, 128, 128], - type='', - swap='shorts_kpt9'), - 163: - dict( - name='shorts_kpt6', - id=163, - color=[128, 128, 128], - type='', - swap='shorts_kpt8'), - 164: - dict( - name='shorts_kpt7', - id=164, - color=[128, 128, 128], - type='', - swap=''), - 165: - dict( - name='shorts_kpt8', - id=165, - color=[128, 128, 128], - type='', - swap='shorts_kpt6'), - 166: - dict( - name='shorts_kpt9', - id=166, - color=[128, 128, 128], - type='', - swap='shorts_kpt5'), - 167: - dict( - name='shorts_kpt10', - id=167, - color=[128, 128, 128], - type='', - swap='shorts_kpt4'), - 168: - dict( - name='trousers_kpt1', - id=168, - color=[128, 0, 128], - type='', - swap='trousers_kpt3'), - 169: - dict( - name='trousers_kpt2', - id=169, - color=[128, 0, 128], - type='', - swap=''), - 170: - dict( - name='trousers_kpt3', - id=170, - color=[128, 0, 128], - type='', - swap='trousers_kpt1'), - 171: - dict( - name='trousers_kpt4', - id=171, - color=[128, 0, 128], - type='', - swap='trousers_kpt14'), - 172: - dict( - name='trousers_kpt5', - id=172, - color=[128, 0, 128], - type='', - swap='trousers_kpt13'), - 173: - dict( - name='trousers_kpt6', - id=173, - color=[128, 0, 128], - type='', - swap='trousers_kpt12'), - 174: - dict( - name='trousers_kpt7', - id=174, - color=[128, 0, 128], - type='', - swap='trousers_kpt11'), - 175: - dict( - name='trousers_kpt8', - id=175, - color=[128, 0, 128], - type='', - swap='trousers_kpt10'), - 176: - dict( - name='trousers_kpt9', - id=176, - color=[128, 0, 128], - type='', - swap=''), - 177: - dict( - name='trousers_kpt10', - id=177, - color=[128, 0, 128], - type='', - swap='trousers_kpt8'), - 178: - dict( - name='trousers_kpt11', - id=178, - color=[128, 0, 128], - type='', - swap='trousers_kpt7'), - 179: - dict( - name='trousers_kpt12', - id=179, - color=[128, 0, 128], - type='', - swap='trousers_kpt6'), - 180: - dict( - name='trousers_kpt13', - id=180, - color=[128, 0, 128], - type='', - swap='trousers_kpt5'), - 181: - dict( - name='trousers_kpt14', - id=181, - color=[128, 0, 128], - type='', - swap='trousers_kpt4'), - 182: - dict( - name='skirt_kpt1', - id=182, - color=[64, 128, 128], - type='', - swap='skirt_kpt3'), - 183: - dict( - name='skirt_kpt2', id=183, color=[64, 128, 128], type='', swap=''), - 184: - dict( - name='skirt_kpt3', - id=184, - color=[64, 128, 128], - type='', - swap='skirt_kpt1'), - 185: - dict( - name='skirt_kpt4', - id=185, - color=[64, 128, 128], - type='', - swap='skirt_kpt8'), - 186: - dict( - name='skirt_kpt5', - id=186, - color=[64, 128, 128], - type='', - swap='skirt_kpt7'), - 187: - dict( - name='skirt_kpt6', id=187, color=[64, 128, 128], type='', swap=''), - 188: - dict( - name='skirt_kpt7', - id=188, - color=[64, 128, 128], - type='', - swap='skirt_kpt5'), - 189: - dict( - name='skirt_kpt8', - id=189, - color=[64, 128, 128], - type='', - swap='skirt_kpt4'), - 190: - dict(name='ssd_kpt1', id=190, color=[64, 64, 128], type='', swap=''), - 191: - dict( - name='ssd_kpt2', - id=191, - color=[64, 64, 128], - type='', - swap='ssd_kpt6'), - 192: - dict( - name='ssd_kpt3', - id=192, - color=[64, 64, 128], - type='', - swap='ssd_kpt5'), - 193: - dict(name='ssd_kpt4', id=193, color=[64, 64, 128], type='', swap=''), - 194: - dict( - name='ssd_kpt5', - id=194, - color=[64, 64, 128], - type='', - swap='ssd_kpt3'), - 195: - dict( - name='ssd_kpt6', - id=195, - color=[64, 64, 128], - type='', - swap='ssd_kpt2'), - 196: - dict( - name='ssd_kpt7', - id=196, - color=[64, 64, 128], - type='', - swap='ssd_kpt29'), - 197: - dict( - name='ssd_kpt8', - id=197, - color=[64, 64, 128], - type='', - swap='ssd_kpt28'), - 198: - dict( - name='ssd_kpt9', - id=198, - color=[64, 64, 128], - type='', - swap='ssd_kpt27'), - 199: - dict( - name='ssd_kpt10', - id=199, - color=[64, 64, 128], - type='', - swap='ssd_kpt26'), - 200: - dict( - name='ssd_kpt11', - id=200, - color=[64, 64, 128], - type='', - swap='ssd_kpt25'), - 201: - dict( - name='ssd_kpt12', - id=201, - color=[64, 64, 128], - type='', - swap='ssd_kpt24'), - 202: - dict( - name='ssd_kpt13', - id=202, - color=[64, 64, 128], - type='', - swap='ssd_kpt23'), - 203: - dict( - name='ssd_kpt14', - id=203, - color=[64, 64, 128], - type='', - swap='ssd_kpt22'), - 204: - dict( - name='ssd_kpt15', - id=204, - color=[64, 64, 128], - type='', - swap='ssd_kpt21'), - 205: - dict( - name='ssd_kpt16', - id=205, - color=[64, 64, 128], - type='', - swap='ssd_kpt20'), - 206: - dict( - name='ssd_kpt17', - id=206, - color=[64, 64, 128], - type='', - swap='ssd_kpt19'), - 207: - dict(name='ssd_kpt18', id=207, color=[64, 64, 128], type='', swap=''), - 208: - dict( - name='ssd_kpt19', - id=208, - color=[64, 64, 128], - type='', - swap='ssd_kpt17'), - 209: - dict( - name='ssd_kpt20', - id=209, - color=[64, 64, 128], - type='', - swap='ssd_kpt16'), - 210: - dict( - name='ssd_kpt21', - id=210, - color=[64, 64, 128], - type='', - swap='ssd_kpt15'), - 211: - dict( - name='ssd_kpt22', - id=211, - color=[64, 64, 128], - type='', - swap='ssd_kpt14'), - 212: - dict( - name='ssd_kpt23', - id=212, - color=[64, 64, 128], - type='', - swap='ssd_kpt13'), - 213: - dict( - name='ssd_kpt24', - id=213, - color=[64, 64, 128], - type='', - swap='ssd_kpt12'), - 214: - dict( - name='ssd_kpt25', - id=214, - color=[64, 64, 128], - type='', - swap='ssd_kpt11'), - 215: - dict( - name='ssd_kpt26', - id=215, - color=[64, 64, 128], - type='', - swap='ssd_kpt10'), - 216: - dict( - name='ssd_kpt27', - id=216, - color=[64, 64, 128], - type='', - swap='ssd_kpt9'), - 217: - dict( - name='ssd_kpt28', - id=217, - color=[64, 64, 128], - type='', - swap='ssd_kpt8'), - 218: - dict( - name='ssd_kpt29', - id=218, - color=[64, 64, 128], - type='', - swap='ssd_kpt7'), - 219: - dict(name='lsd_kpt1', id=219, color=[128, 64, 0], type='', swap=''), - 220: - dict( - name='lsd_kpt2', - id=220, - color=[128, 64, 0], - type='', - swap='lsd_kpt6'), - 221: - dict( - name='lsd_kpt3', - id=221, - color=[128, 64, 0], - type='', - swap='lsd_kpt5'), - 222: - dict(name='lsd_kpt4', id=222, color=[128, 64, 0], type='', swap=''), - 223: - dict( - name='lsd_kpt5', - id=223, - color=[128, 64, 0], - type='', - swap='lsd_kpt3'), - 224: - dict( - name='lsd_kpt6', - id=224, - color=[128, 64, 0], - type='', - swap='lsd_kpt2'), - 225: - dict( - name='lsd_kpt7', - id=225, - color=[128, 64, 0], - type='', - swap='lsd_kpt37'), - 226: - dict( - name='lsd_kpt8', - id=226, - color=[128, 64, 0], - type='', - swap='lsd_kpt36'), - 227: - dict( - name='lsd_kpt9', - id=227, - color=[128, 64, 0], - type='', - swap='lsd_kpt35'), - 228: - dict( - name='lsd_kpt10', - id=228, - color=[128, 64, 0], - type='', - swap='lsd_kpt34'), - 229: - dict( - name='lsd_kpt11', - id=229, - color=[128, 64, 0], - type='', - swap='lsd_kpt33'), - 230: - dict( - name='lsd_kpt12', - id=230, - color=[128, 64, 0], - type='', - swap='lsd_kpt32'), - 231: - dict( - name='lsd_kpt13', - id=231, - color=[128, 64, 0], - type='', - swap='lsd_kpt31'), - 232: - dict( - name='lsd_kpt14', - id=232, - color=[128, 64, 0], - type='', - swap='lsd_kpt30'), - 233: - dict( - name='lsd_kpt15', - id=233, - color=[128, 64, 0], - type='', - swap='lsd_kpt29'), - 234: - dict( - name='lsd_kpt16', - id=234, - color=[128, 64, 0], - type='', - swap='lsd_kpt28'), - 235: - dict( - name='lsd_kpt17', - id=235, - color=[128, 64, 0], - type='', - swap='lsd_kpt27'), - 236: - dict( - name='lsd_kpt18', - id=236, - color=[128, 64, 0], - type='', - swap='lsd_kpt26'), - 237: - dict( - name='lsd_kpt19', - id=237, - color=[128, 64, 0], - type='', - swap='lsd_kpt25'), - 238: - dict( - name='lsd_kpt20', - id=238, - color=[128, 64, 0], - type='', - swap='lsd_kpt24'), - 239: - dict( - name='lsd_kpt21', - id=239, - color=[128, 64, 0], - type='', - swap='lsd_kpt23'), - 240: - dict(name='lsd_kpt22', id=240, color=[128, 64, 0], type='', swap=''), - 241: - dict( - name='lsd_kpt23', - id=241, - color=[128, 64, 0], - type='', - swap='lsd_kpt21'), - 242: - dict( - name='lsd_kpt24', - id=242, - color=[128, 64, 0], - type='', - swap='lsd_kpt20'), - 243: - dict( - name='lsd_kpt25', - id=243, - color=[128, 64, 0], - type='', - swap='lsd_kpt19'), - 244: - dict( - name='lsd_kpt26', - id=244, - color=[128, 64, 0], - type='', - swap='lsd_kpt18'), - 245: - dict( - name='lsd_kpt27', - id=245, - color=[128, 64, 0], - type='', - swap='lsd_kpt17'), - 246: - dict( - name='lsd_kpt28', - id=246, - color=[128, 64, 0], - type='', - swap='lsd_kpt16'), - 247: - dict( - name='lsd_kpt29', - id=247, - color=[128, 64, 0], - type='', - swap='lsd_kpt15'), - 248: - dict( - name='lsd_kpt30', - id=248, - color=[128, 64, 0], - type='', - swap='lsd_kpt14'), - 249: - dict( - name='lsd_kpt31', - id=249, - color=[128, 64, 0], - type='', - swap='lsd_kpt13'), - 250: - dict( - name='lsd_kpt32', - id=250, - color=[128, 64, 0], - type='', - swap='lsd_kpt12'), - 251: - dict( - name='lsd_kpt33', - id=251, - color=[128, 64, 0], - type='', - swap='lsd_kpt11'), - 252: - dict( - name='lsd_kpt34', - id=252, - color=[128, 64, 0], - type='', - swap='lsd_kpt10'), - 253: - dict( - name='lsd_kpt35', - id=253, - color=[128, 64, 0], - type='', - swap='lsd_kpt9'), - 254: - dict( - name='lsd_kpt36', - id=254, - color=[128, 64, 0], - type='', - swap='lsd_kpt8'), - 255: - dict( - name='lsd_kpt37', - id=255, - color=[128, 64, 0], - type='', - swap='lsd_kpt7'), - 256: - dict(name='vd_kpt1', id=256, color=[128, 64, 255], type='', swap=''), - 257: - dict( - name='vd_kpt2', - id=257, - color=[128, 64, 255], - type='', - swap='vd_kpt6'), - 258: - dict( - name='vd_kpt3', - id=258, - color=[128, 64, 255], - type='', - swap='vd_kpt5'), - 259: - dict(name='vd_kpt4', id=259, color=[128, 64, 255], type='', swap=''), - 260: - dict( - name='vd_kpt5', - id=260, - color=[128, 64, 255], - type='', - swap='vd_kpt3'), - 261: - dict( - name='vd_kpt6', - id=261, - color=[128, 64, 255], - type='', - swap='vd_kpt2'), - 262: - dict( - name='vd_kpt7', - id=262, - color=[128, 64, 255], - type='', - swap='vd_kpt19'), - 263: - dict( - name='vd_kpt8', - id=263, - color=[128, 64, 255], - type='', - swap='vd_kpt18'), - 264: - dict( - name='vd_kpt9', - id=264, - color=[128, 64, 255], - type='', - swap='vd_kpt17'), - 265: - dict( - name='vd_kpt10', - id=265, - color=[128, 64, 255], - type='', - swap='vd_kpt16'), - 266: - dict( - name='vd_kpt11', - id=266, - color=[128, 64, 255], - type='', - swap='vd_kpt15'), - 267: - dict( - name='vd_kpt12', - id=267, - color=[128, 64, 255], - type='', - swap='vd_kpt14'), - 268: - dict(name='vd_kpt13', id=268, color=[128, 64, 255], type='', swap=''), - 269: - dict( - name='vd_kpt14', - id=269, - color=[128, 64, 255], - type='', - swap='vd_kpt12'), - 270: - dict( - name='vd_kpt15', - id=270, - color=[128, 64, 255], - type='', - swap='vd_kpt11'), - 271: - dict( - name='vd_kpt16', - id=271, - color=[128, 64, 255], - type='', - swap='vd_kpt10'), - 272: - dict( - name='vd_kpt17', - id=272, - color=[128, 64, 255], - type='', - swap='vd_kpt9'), - 273: - dict( - name='vd_kpt18', - id=273, - color=[128, 64, 255], - type='', - swap='vd_kpt8'), - 274: - dict( - name='vd_kpt19', - id=274, - color=[128, 64, 255], - type='', - swap='vd_kpt7'), - 275: - dict(name='sd_kpt1', id=275, color=[128, 64, 0], type='', swap=''), - 276: - dict( - name='sd_kpt2', - id=276, - color=[128, 64, 0], - type='', - swap='sd_kpt6'), - 277: - dict( - name='sd_kpt3', - id=277, - color=[128, 64, 0], - type='', - swap='sd_kpt5'), - 278: - dict(name='sd_kpt4', id=278, color=[128, 64, 0], type='', swap=''), - 279: - dict( - name='sd_kpt5', - id=279, - color=[128, 64, 0], - type='', - swap='sd_kpt3'), - 280: - dict( - name='sd_kpt6', - id=280, - color=[128, 64, 0], - type='', - swap='sd_kpt2'), - 281: - dict( - name='sd_kpt7', - id=281, - color=[128, 64, 0], - type='', - swap='sd_kpt19'), - 282: - dict( - name='sd_kpt8', - id=282, - color=[128, 64, 0], - type='', - swap='sd_kpt18'), - 283: - dict( - name='sd_kpt9', - id=283, - color=[128, 64, 0], - type='', - swap='sd_kpt17'), - 284: - dict( - name='sd_kpt10', - id=284, - color=[128, 64, 0], - type='', - swap='sd_kpt16'), - 285: - dict( - name='sd_kpt11', - id=285, - color=[128, 64, 0], - type='', - swap='sd_kpt15'), - 286: - dict( - name='sd_kpt12', - id=286, - color=[128, 64, 0], - type='', - swap='sd_kpt14'), - 287: - dict(name='sd_kpt13', id=287, color=[128, 64, 0], type='', swap=''), - 288: - dict( - name='sd_kpt14', - id=288, - color=[128, 64, 0], - type='', - swap='sd_kpt12'), - 289: - dict( - name='sd_kpt15', - id=289, - color=[128, 64, 0], - type='', - swap='sd_kpt11'), - 290: - dict( - name='sd_kpt16', - id=290, - color=[128, 64, 0], - type='', - swap='sd_kpt10'), - 291: - dict( - name='sd_kpt17', - id=291, - color=[128, 64, 0], - type='', - swap='sd_kpt9'), - 292: - dict( - name='sd_kpt18', - id=292, - color=[128, 64, 0], - type='', - swap='sd_kpt8'), - 293: - dict( - name='sd_kpt19', - id=293, - color=[128, 64, 0], - type='', - swap='sd_kpt7') - }), - skeleton_info=dict({ - 0: - dict(link=('sss_kpt1', 'sss_kpt2'), id=0, color=[255, 128, 0]), - 1: - dict(link=('sss_kpt2', 'sss_kpt7'), id=1, color=[255, 128, 0]), - 2: - dict(link=('sss_kpt7', 'sss_kpt8'), id=2, color=[255, 128, 0]), - 3: - dict(link=('sss_kpt8', 'sss_kpt9'), id=3, color=[255, 128, 0]), - 4: - dict(link=('sss_kpt9', 'sss_kpt10'), id=4, color=[255, 128, 0]), - 5: - dict(link=('sss_kpt10', 'sss_kpt11'), id=5, color=[255, 128, 0]), - 6: - dict(link=('sss_kpt11', 'sss_kpt12'), id=6, color=[255, 128, 0]), - 7: - dict(link=('sss_kpt12', 'sss_kpt13'), id=7, color=[255, 128, 0]), - 8: - dict(link=('sss_kpt13', 'sss_kpt14'), id=8, color=[255, 128, 0]), - 9: - dict(link=('sss_kpt14', 'sss_kpt15'), id=9, color=[255, 128, 0]), - 10: - dict(link=('sss_kpt15', 'sss_kpt16'), id=10, color=[255, 128, 0]), - 11: - dict(link=('sss_kpt16', 'sss_kpt17'), id=11, color=[255, 128, 0]), - 12: - dict(link=('sss_kpt17', 'sss_kpt18'), id=12, color=[255, 128, 0]), - 13: - dict(link=('sss_kpt18', 'sss_kpt19'), id=13, color=[255, 128, 0]), - 14: - dict(link=('sss_kpt19', 'sss_kpt20'), id=14, color=[255, 128, 0]), - 15: - dict(link=('sss_kpt20', 'sss_kpt21'), id=15, color=[255, 128, 0]), - 16: - dict(link=('sss_kpt21', 'sss_kpt22'), id=16, color=[255, 128, 0]), - 17: - dict(link=('sss_kpt22', 'sss_kpt23'), id=17, color=[255, 128, 0]), - 18: - dict(link=('sss_kpt23', 'sss_kpt24'), id=18, color=[255, 128, 0]), - 19: - dict(link=('sss_kpt24', 'sss_kpt25'), id=19, color=[255, 128, 0]), - 20: - dict(link=('sss_kpt25', 'sss_kpt6'), id=20, color=[255, 128, 0]), - 21: - dict(link=('sss_kpt6', 'sss_kpt1'), id=21, color=[255, 128, 0]), - 22: - dict(link=('sss_kpt2', 'sss_kpt3'), id=22, color=[255, 128, 0]), - 23: - dict(link=('sss_kpt3', 'sss_kpt4'), id=23, color=[255, 128, 0]), - 24: - dict(link=('sss_kpt4', 'sss_kpt5'), id=24, color=[255, 128, 0]), - 25: - dict(link=('sss_kpt5', 'sss_kpt6'), id=25, color=[255, 128, 0]), - 26: - dict(link=('lss_kpt1', 'lss_kpt2'), id=26, color=[255, 0, 128]), - 27: - dict(link=('lss_kpt2', 'lss_kpt7'), id=27, color=[255, 0, 128]), - 28: - dict(link=('lss_kpt7', 'lss_kpt8'), id=28, color=[255, 0, 128]), - 29: - dict(link=('lss_kpt8', 'lss_kpt9'), id=29, color=[255, 0, 128]), - 30: - dict(link=('lss_kpt9', 'lss_kpt10'), id=30, color=[255, 0, 128]), - 31: - dict(link=('lss_kpt10', 'lss_kpt11'), id=31, color=[255, 0, 128]), - 32: - dict(link=('lss_kpt11', 'lss_kpt12'), id=32, color=[255, 0, 128]), - 33: - dict(link=('lss_kpt12', 'lss_kpt13'), id=33, color=[255, 0, 128]), - 34: - dict(link=('lss_kpt13', 'lss_kpt14'), id=34, color=[255, 0, 128]), - 35: - dict(link=('lss_kpt14', 'lss_kpt15'), id=35, color=[255, 0, 128]), - 36: - dict(link=('lss_kpt15', 'lss_kpt16'), id=36, color=[255, 0, 128]), - 37: - dict(link=('lss_kpt16', 'lss_kpt17'), id=37, color=[255, 0, 128]), - 38: - dict(link=('lss_kpt17', 'lss_kpt18'), id=38, color=[255, 0, 128]), - 39: - dict(link=('lss_kpt18', 'lss_kpt19'), id=39, color=[255, 0, 128]), - 40: - dict(link=('lss_kpt19', 'lss_kpt20'), id=40, color=[255, 0, 128]), - 41: - dict(link=('lss_kpt20', 'lss_kpt21'), id=41, color=[255, 0, 128]), - 42: - dict(link=('lss_kpt21', 'lss_kpt22'), id=42, color=[255, 0, 128]), - 43: - dict(link=('lss_kpt22', 'lss_kpt23'), id=43, color=[255, 0, 128]), - 44: - dict(link=('lss_kpt23', 'lss_kpt24'), id=44, color=[255, 0, 128]), - 45: - dict(link=('lss_kpt24', 'lss_kpt25'), id=45, color=[255, 0, 128]), - 46: - dict(link=('lss_kpt25', 'lss_kpt26'), id=46, color=[255, 0, 128]), - 47: - dict(link=('lss_kpt26', 'lss_kpt27'), id=47, color=[255, 0, 128]), - 48: - dict(link=('lss_kpt27', 'lss_kpt28'), id=48, color=[255, 0, 128]), - 49: - dict(link=('lss_kpt28', 'lss_kpt29'), id=49, color=[255, 0, 128]), - 50: - dict(link=('lss_kpt29', 'lss_kpt30'), id=50, color=[255, 0, 128]), - 51: - dict(link=('lss_kpt30', 'lss_kpt31'), id=51, color=[255, 0, 128]), - 52: - dict(link=('lss_kpt31', 'lss_kpt32'), id=52, color=[255, 0, 128]), - 53: - dict(link=('lss_kpt32', 'lss_kpt33'), id=53, color=[255, 0, 128]), - 54: - dict(link=('lss_kpt33', 'lss_kpt6'), id=54, color=[255, 0, 128]), - 55: - dict(link=('lss_kpt6', 'lss_kpt5'), id=55, color=[255, 0, 128]), - 56: - dict(link=('lss_kpt5', 'lss_kpt4'), id=56, color=[255, 0, 128]), - 57: - dict(link=('lss_kpt4', 'lss_kpt3'), id=57, color=[255, 0, 128]), - 58: - dict(link=('lss_kpt3', 'lss_kpt2'), id=58, color=[255, 0, 128]), - 59: - dict(link=('lss_kpt6', 'lss_kpt1'), id=59, color=[255, 0, 128]), - 60: - dict(link=('sso_kpt1', 'sso_kpt4'), id=60, color=[128, 0, 255]), - 61: - dict(link=('sso_kpt4', 'sso_kpt7'), id=61, color=[128, 0, 255]), - 62: - dict(link=('sso_kpt7', 'sso_kpt8'), id=62, color=[128, 0, 255]), - 63: - dict(link=('sso_kpt8', 'sso_kpt9'), id=63, color=[128, 0, 255]), - 64: - dict(link=('sso_kpt9', 'sso_kpt10'), id=64, color=[128, 0, 255]), - 65: - dict(link=('sso_kpt10', 'sso_kpt11'), id=65, color=[128, 0, 255]), - 66: - dict(link=('sso_kpt11', 'sso_kpt12'), id=66, color=[128, 0, 255]), - 67: - dict(link=('sso_kpt12', 'sso_kpt13'), id=67, color=[128, 0, 255]), - 68: - dict(link=('sso_kpt13', 'sso_kpt14'), id=68, color=[128, 0, 255]), - 69: - dict(link=('sso_kpt14', 'sso_kpt15'), id=69, color=[128, 0, 255]), - 70: - dict(link=('sso_kpt15', 'sso_kpt16'), id=70, color=[128, 0, 255]), - 71: - dict(link=('sso_kpt16', 'sso_kpt31'), id=71, color=[128, 0, 255]), - 72: - dict(link=('sso_kpt31', 'sso_kpt30'), id=72, color=[128, 0, 255]), - 73: - dict(link=('sso_kpt30', 'sso_kpt2'), id=73, color=[128, 0, 255]), - 74: - dict(link=('sso_kpt2', 'sso_kpt3'), id=74, color=[128, 0, 255]), - 75: - dict(link=('sso_kpt3', 'sso_kpt4'), id=75, color=[128, 0, 255]), - 76: - dict(link=('sso_kpt1', 'sso_kpt6'), id=76, color=[128, 0, 255]), - 77: - dict(link=('sso_kpt6', 'sso_kpt25'), id=77, color=[128, 0, 255]), - 78: - dict(link=('sso_kpt25', 'sso_kpt24'), id=78, color=[128, 0, 255]), - 79: - dict(link=('sso_kpt24', 'sso_kpt23'), id=79, color=[128, 0, 255]), - 80: - dict(link=('sso_kpt23', 'sso_kpt22'), id=80, color=[128, 0, 255]), - 81: - dict(link=('sso_kpt22', 'sso_kpt21'), id=81, color=[128, 0, 255]), - 82: - dict(link=('sso_kpt21', 'sso_kpt20'), id=82, color=[128, 0, 255]), - 83: - dict(link=('sso_kpt20', 'sso_kpt19'), id=83, color=[128, 0, 255]), - 84: - dict(link=('sso_kpt19', 'sso_kpt18'), id=84, color=[128, 0, 255]), - 85: - dict(link=('sso_kpt18', 'sso_kpt17'), id=85, color=[128, 0, 255]), - 86: - dict(link=('sso_kpt17', 'sso_kpt29'), id=86, color=[128, 0, 255]), - 87: - dict(link=('sso_kpt29', 'sso_kpt28'), id=87, color=[128, 0, 255]), - 88: - dict(link=('sso_kpt28', 'sso_kpt27'), id=88, color=[128, 0, 255]), - 89: - dict(link=('sso_kpt27', 'sso_kpt26'), id=89, color=[128, 0, 255]), - 90: - dict(link=('sso_kpt26', 'sso_kpt5'), id=90, color=[128, 0, 255]), - 91: - dict(link=('sso_kpt5', 'sso_kpt6'), id=91, color=[128, 0, 255]), - 92: - dict(link=('lso_kpt1', 'lso_kpt2'), id=92, color=[0, 128, 255]), - 93: - dict(link=('lso_kpt2', 'lso_kpt7'), id=93, color=[0, 128, 255]), - 94: - dict(link=('lso_kpt7', 'lso_kpt8'), id=94, color=[0, 128, 255]), - 95: - dict(link=('lso_kpt8', 'lso_kpt9'), id=95, color=[0, 128, 255]), - 96: - dict(link=('lso_kpt9', 'lso_kpt10'), id=96, color=[0, 128, 255]), - 97: - dict(link=('lso_kpt10', 'lso_kpt11'), id=97, color=[0, 128, 255]), - 98: - dict(link=('lso_kpt11', 'lso_kpt12'), id=98, color=[0, 128, 255]), - 99: - dict(link=('lso_kpt12', 'lso_kpt13'), id=99, color=[0, 128, 255]), - 100: - dict(link=('lso_kpt13', 'lso_kpt14'), id=100, color=[0, 128, 255]), - 101: - dict(link=('lso_kpt14', 'lso_kpt15'), id=101, color=[0, 128, 255]), - 102: - dict(link=('lso_kpt15', 'lso_kpt16'), id=102, color=[0, 128, 255]), - 103: - dict(link=('lso_kpt16', 'lso_kpt17'), id=103, color=[0, 128, 255]), - 104: - dict(link=('lso_kpt17', 'lso_kpt18'), id=104, color=[0, 128, 255]), - 105: - dict(link=('lso_kpt18', 'lso_kpt19'), id=105, color=[0, 128, 255]), - 106: - dict(link=('lso_kpt19', 'lso_kpt20'), id=106, color=[0, 128, 255]), - 107: - dict(link=('lso_kpt20', 'lso_kpt39'), id=107, color=[0, 128, 255]), - 108: - dict(link=('lso_kpt39', 'lso_kpt38'), id=108, color=[0, 128, 255]), - 109: - dict(link=('lso_kpt38', 'lso_kpt4'), id=109, color=[0, 128, 255]), - 110: - dict(link=('lso_kpt4', 'lso_kpt3'), id=110, color=[0, 128, 255]), - 111: - dict(link=('lso_kpt3', 'lso_kpt2'), id=111, color=[0, 128, 255]), - 112: - dict(link=('lso_kpt1', 'lso_kpt6'), id=112, color=[0, 128, 255]), - 113: - dict(link=('lso_kpt6', 'lso_kpt33'), id=113, color=[0, 128, 255]), - 114: - dict(link=('lso_kpt33', 'lso_kpt32'), id=114, color=[0, 128, 255]), - 115: - dict(link=('lso_kpt32', 'lso_kpt31'), id=115, color=[0, 128, 255]), - 116: - dict(link=('lso_kpt31', 'lso_kpt30'), id=116, color=[0, 128, 255]), - 117: - dict(link=('lso_kpt30', 'lso_kpt29'), id=117, color=[0, 128, 255]), - 118: - dict(link=('lso_kpt29', 'lso_kpt28'), id=118, color=[0, 128, 255]), - 119: - dict(link=('lso_kpt28', 'lso_kpt27'), id=119, color=[0, 128, 255]), - 120: - dict(link=('lso_kpt27', 'lso_kpt26'), id=120, color=[0, 128, 255]), - 121: - dict(link=('lso_kpt26', 'lso_kpt25'), id=121, color=[0, 128, 255]), - 122: - dict(link=('lso_kpt25', 'lso_kpt24'), id=122, color=[0, 128, 255]), - 123: - dict(link=('lso_kpt24', 'lso_kpt23'), id=123, color=[0, 128, 255]), - 124: - dict(link=('lso_kpt23', 'lso_kpt22'), id=124, color=[0, 128, 255]), - 125: - dict(link=('lso_kpt22', 'lso_kpt21'), id=125, color=[0, 128, 255]), - 126: - dict(link=('lso_kpt21', 'lso_kpt37'), id=126, color=[0, 128, 255]), - 127: - dict(link=('lso_kpt37', 'lso_kpt36'), id=127, color=[0, 128, 255]), - 128: - dict(link=('lso_kpt36', 'lso_kpt35'), id=128, color=[0, 128, 255]), - 129: - dict(link=('lso_kpt35', 'lso_kpt34'), id=129, color=[0, 128, 255]), - 130: - dict(link=('lso_kpt34', 'lso_kpt5'), id=130, color=[0, 128, 255]), - 131: - dict(link=('lso_kpt5', 'lso_kpt6'), id=131, color=[0, 128, 255]), - 132: - dict(link=('vest_kpt1', 'vest_kpt2'), id=132, color=[0, 128, 128]), - 133: - dict(link=('vest_kpt2', 'vest_kpt7'), id=133, color=[0, 128, 128]), - 134: - dict(link=('vest_kpt7', 'vest_kpt8'), id=134, color=[0, 128, 128]), - 135: - dict(link=('vest_kpt8', 'vest_kpt9'), id=135, color=[0, 128, 128]), - 136: - dict(link=('vest_kpt9', 'vest_kpt10'), id=136, color=[0, 128, 128]), - 137: - dict(link=('vest_kpt10', 'vest_kpt11'), id=137, color=[0, 128, 128]), - 138: - dict(link=('vest_kpt11', 'vest_kpt12'), id=138, color=[0, 128, 128]), - 139: - dict(link=('vest_kpt12', 'vest_kpt13'), id=139, color=[0, 128, 128]), - 140: - dict(link=('vest_kpt13', 'vest_kpt14'), id=140, color=[0, 128, 128]), - 141: - dict(link=('vest_kpt14', 'vest_kpt15'), id=141, color=[0, 128, 128]), - 142: - dict(link=('vest_kpt15', 'vest_kpt6'), id=142, color=[0, 128, 128]), - 143: - dict(link=('vest_kpt6', 'vest_kpt1'), id=143, color=[0, 128, 128]), - 144: - dict(link=('vest_kpt2', 'vest_kpt3'), id=144, color=[0, 128, 128]), - 145: - dict(link=('vest_kpt3', 'vest_kpt4'), id=145, color=[0, 128, 128]), - 146: - dict(link=('vest_kpt4', 'vest_kpt5'), id=146, color=[0, 128, 128]), - 147: - dict(link=('vest_kpt5', 'vest_kpt6'), id=147, color=[0, 128, 128]), - 148: - dict(link=('sling_kpt1', 'sling_kpt2'), id=148, color=[0, 0, 128]), - 149: - dict(link=('sling_kpt2', 'sling_kpt8'), id=149, color=[0, 0, 128]), - 150: - dict(link=('sling_kpt8', 'sling_kpt9'), id=150, color=[0, 0, 128]), - 151: - dict(link=('sling_kpt9', 'sling_kpt10'), id=151, color=[0, 0, 128]), - 152: - dict(link=('sling_kpt10', 'sling_kpt11'), id=152, color=[0, 0, 128]), - 153: - dict(link=('sling_kpt11', 'sling_kpt12'), id=153, color=[0, 0, 128]), - 154: - dict(link=('sling_kpt12', 'sling_kpt13'), id=154, color=[0, 0, 128]), - 155: - dict(link=('sling_kpt13', 'sling_kpt14'), id=155, color=[0, 0, 128]), - 156: - dict(link=('sling_kpt14', 'sling_kpt6'), id=156, color=[0, 0, 128]), - 157: - dict(link=('sling_kpt2', 'sling_kpt7'), id=157, color=[0, 0, 128]), - 158: - dict(link=('sling_kpt6', 'sling_kpt15'), id=158, color=[0, 0, 128]), - 159: - dict(link=('sling_kpt2', 'sling_kpt3'), id=159, color=[0, 0, 128]), - 160: - dict(link=('sling_kpt3', 'sling_kpt4'), id=160, color=[0, 0, 128]), - 161: - dict(link=('sling_kpt4', 'sling_kpt5'), id=161, color=[0, 0, 128]), - 162: - dict(link=('sling_kpt5', 'sling_kpt6'), id=162, color=[0, 0, 128]), - 163: - dict(link=('sling_kpt1', 'sling_kpt6'), id=163, color=[0, 0, 128]), - 164: - dict( - link=('shorts_kpt1', 'shorts_kpt4'), id=164, color=[128, 128, - 128]), - 165: - dict( - link=('shorts_kpt4', 'shorts_kpt5'), id=165, color=[128, 128, - 128]), - 166: - dict( - link=('shorts_kpt5', 'shorts_kpt6'), id=166, color=[128, 128, - 128]), - 167: - dict( - link=('shorts_kpt6', 'shorts_kpt7'), id=167, color=[128, 128, - 128]), - 168: - dict( - link=('shorts_kpt7', 'shorts_kpt8'), id=168, color=[128, 128, - 128]), - 169: - dict( - link=('shorts_kpt8', 'shorts_kpt9'), id=169, color=[128, 128, - 128]), - 170: - dict( - link=('shorts_kpt9', 'shorts_kpt10'), - id=170, - color=[128, 128, 128]), - 171: - dict( - link=('shorts_kpt10', 'shorts_kpt3'), - id=171, - color=[128, 128, 128]), - 172: - dict( - link=('shorts_kpt3', 'shorts_kpt2'), id=172, color=[128, 128, - 128]), - 173: - dict( - link=('shorts_kpt2', 'shorts_kpt1'), id=173, color=[128, 128, - 128]), - 174: - dict( - link=('trousers_kpt1', 'trousers_kpt4'), - id=174, - color=[128, 0, 128]), - 175: - dict( - link=('trousers_kpt4', 'trousers_kpt5'), - id=175, - color=[128, 0, 128]), - 176: - dict( - link=('trousers_kpt5', 'trousers_kpt6'), - id=176, - color=[128, 0, 128]), - 177: - dict( - link=('trousers_kpt6', 'trousers_kpt7'), - id=177, - color=[128, 0, 128]), - 178: - dict( - link=('trousers_kpt7', 'trousers_kpt8'), - id=178, - color=[128, 0, 128]), - 179: - dict( - link=('trousers_kpt8', 'trousers_kpt9'), - id=179, - color=[128, 0, 128]), - 180: - dict( - link=('trousers_kpt9', 'trousers_kpt10'), - id=180, - color=[128, 0, 128]), - 181: - dict( - link=('trousers_kpt10', 'trousers_kpt11'), - id=181, - color=[128, 0, 128]), - 182: - dict( - link=('trousers_kpt11', 'trousers_kpt12'), - id=182, - color=[128, 0, 128]), - 183: - dict( - link=('trousers_kpt12', 'trousers_kpt13'), - id=183, - color=[128, 0, 128]), - 184: - dict( - link=('trousers_kpt13', 'trousers_kpt14'), - id=184, - color=[128, 0, 128]), - 185: - dict( - link=('trousers_kpt14', 'trousers_kpt3'), - id=185, - color=[128, 0, 128]), - 186: - dict( - link=('trousers_kpt3', 'trousers_kpt2'), - id=186, - color=[128, 0, 128]), - 187: - dict( - link=('trousers_kpt2', 'trousers_kpt1'), - id=187, - color=[128, 0, 128]), - 188: - dict(link=('skirt_kpt1', 'skirt_kpt4'), id=188, color=[64, 128, 128]), - 189: - dict(link=('skirt_kpt4', 'skirt_kpt5'), id=189, color=[64, 128, 128]), - 190: - dict(link=('skirt_kpt5', 'skirt_kpt6'), id=190, color=[64, 128, 128]), - 191: - dict(link=('skirt_kpt6', 'skirt_kpt7'), id=191, color=[64, 128, 128]), - 192: - dict(link=('skirt_kpt7', 'skirt_kpt8'), id=192, color=[64, 128, 128]), - 193: - dict(link=('skirt_kpt8', 'skirt_kpt3'), id=193, color=[64, 128, 128]), - 194: - dict(link=('skirt_kpt3', 'skirt_kpt2'), id=194, color=[64, 128, 128]), - 195: - dict(link=('skirt_kpt2', 'skirt_kpt1'), id=195, color=[64, 128, 128]), - 196: - dict(link=('ssd_kpt1', 'ssd_kpt2'), id=196, color=[64, 64, 128]), - 197: - dict(link=('ssd_kpt2', 'ssd_kpt7'), id=197, color=[64, 64, 128]), - 198: - dict(link=('ssd_kpt7', 'ssd_kpt8'), id=198, color=[64, 64, 128]), - 199: - dict(link=('ssd_kpt8', 'ssd_kpt9'), id=199, color=[64, 64, 128]), - 200: - dict(link=('ssd_kpt9', 'ssd_kpt10'), id=200, color=[64, 64, 128]), - 201: - dict(link=('ssd_kpt10', 'ssd_kpt11'), id=201, color=[64, 64, 128]), - 202: - dict(link=('ssd_kpt11', 'ssd_kpt12'), id=202, color=[64, 64, 128]), - 203: - dict(link=('ssd_kpt12', 'ssd_kpt13'), id=203, color=[64, 64, 128]), - 204: - dict(link=('ssd_kpt13', 'ssd_kpt14'), id=204, color=[64, 64, 128]), - 205: - dict(link=('ssd_kpt14', 'ssd_kpt15'), id=205, color=[64, 64, 128]), - 206: - dict(link=('ssd_kpt15', 'ssd_kpt16'), id=206, color=[64, 64, 128]), - 207: - dict(link=('ssd_kpt16', 'ssd_kpt17'), id=207, color=[64, 64, 128]), - 208: - dict(link=('ssd_kpt17', 'ssd_kpt18'), id=208, color=[64, 64, 128]), - 209: - dict(link=('ssd_kpt18', 'ssd_kpt19'), id=209, color=[64, 64, 128]), - 210: - dict(link=('ssd_kpt19', 'ssd_kpt20'), id=210, color=[64, 64, 128]), - 211: - dict(link=('ssd_kpt20', 'ssd_kpt21'), id=211, color=[64, 64, 128]), - 212: - dict(link=('ssd_kpt21', 'ssd_kpt22'), id=212, color=[64, 64, 128]), - 213: - dict(link=('ssd_kpt22', 'ssd_kpt23'), id=213, color=[64, 64, 128]), - 214: - dict(link=('ssd_kpt23', 'ssd_kpt24'), id=214, color=[64, 64, 128]), - 215: - dict(link=('ssd_kpt24', 'ssd_kpt25'), id=215, color=[64, 64, 128]), - 216: - dict(link=('ssd_kpt25', 'ssd_kpt26'), id=216, color=[64, 64, 128]), - 217: - dict(link=('ssd_kpt26', 'ssd_kpt27'), id=217, color=[64, 64, 128]), - 218: - dict(link=('ssd_kpt27', 'ssd_kpt28'), id=218, color=[64, 64, 128]), - 219: - dict(link=('ssd_kpt28', 'ssd_kpt29'), id=219, color=[64, 64, 128]), - 220: - dict(link=('ssd_kpt29', 'ssd_kpt6'), id=220, color=[64, 64, 128]), - 221: - dict(link=('ssd_kpt6', 'ssd_kpt5'), id=221, color=[64, 64, 128]), - 222: - dict(link=('ssd_kpt5', 'ssd_kpt4'), id=222, color=[64, 64, 128]), - 223: - dict(link=('ssd_kpt4', 'ssd_kpt3'), id=223, color=[64, 64, 128]), - 224: - dict(link=('ssd_kpt3', 'ssd_kpt2'), id=224, color=[64, 64, 128]), - 225: - dict(link=('ssd_kpt6', 'ssd_kpt1'), id=225, color=[64, 64, 128]), - 226: - dict(link=('lsd_kpt1', 'lsd_kpt2'), id=226, color=[128, 64, 0]), - 227: - dict(link=('lsd_kpt2', 'lsd_kpt7'), id=228, color=[128, 64, 0]), - 228: - dict(link=('lsd_kpt7', 'lsd_kpt8'), id=228, color=[128, 64, 0]), - 229: - dict(link=('lsd_kpt8', 'lsd_kpt9'), id=229, color=[128, 64, 0]), - 230: - dict(link=('lsd_kpt9', 'lsd_kpt10'), id=230, color=[128, 64, 0]), - 231: - dict(link=('lsd_kpt10', 'lsd_kpt11'), id=231, color=[128, 64, 0]), - 232: - dict(link=('lsd_kpt11', 'lsd_kpt12'), id=232, color=[128, 64, 0]), - 233: - dict(link=('lsd_kpt12', 'lsd_kpt13'), id=233, color=[128, 64, 0]), - 234: - dict(link=('lsd_kpt13', 'lsd_kpt14'), id=234, color=[128, 64, 0]), - 235: - dict(link=('lsd_kpt14', 'lsd_kpt15'), id=235, color=[128, 64, 0]), - 236: - dict(link=('lsd_kpt15', 'lsd_kpt16'), id=236, color=[128, 64, 0]), - 237: - dict(link=('lsd_kpt16', 'lsd_kpt17'), id=237, color=[128, 64, 0]), - 238: - dict(link=('lsd_kpt17', 'lsd_kpt18'), id=238, color=[128, 64, 0]), - 239: - dict(link=('lsd_kpt18', 'lsd_kpt19'), id=239, color=[128, 64, 0]), - 240: - dict(link=('lsd_kpt19', 'lsd_kpt20'), id=240, color=[128, 64, 0]), - 241: - dict(link=('lsd_kpt20', 'lsd_kpt21'), id=241, color=[128, 64, 0]), - 242: - dict(link=('lsd_kpt21', 'lsd_kpt22'), id=242, color=[128, 64, 0]), - 243: - dict(link=('lsd_kpt22', 'lsd_kpt23'), id=243, color=[128, 64, 0]), - 244: - dict(link=('lsd_kpt23', 'lsd_kpt24'), id=244, color=[128, 64, 0]), - 245: - dict(link=('lsd_kpt24', 'lsd_kpt25'), id=245, color=[128, 64, 0]), - 246: - dict(link=('lsd_kpt25', 'lsd_kpt26'), id=246, color=[128, 64, 0]), - 247: - dict(link=('lsd_kpt26', 'lsd_kpt27'), id=247, color=[128, 64, 0]), - 248: - dict(link=('lsd_kpt27', 'lsd_kpt28'), id=248, color=[128, 64, 0]), - 249: - dict(link=('lsd_kpt28', 'lsd_kpt29'), id=249, color=[128, 64, 0]), - 250: - dict(link=('lsd_kpt29', 'lsd_kpt30'), id=250, color=[128, 64, 0]), - 251: - dict(link=('lsd_kpt30', 'lsd_kpt31'), id=251, color=[128, 64, 0]), - 252: - dict(link=('lsd_kpt31', 'lsd_kpt32'), id=252, color=[128, 64, 0]), - 253: - dict(link=('lsd_kpt32', 'lsd_kpt33'), id=253, color=[128, 64, 0]), - 254: - dict(link=('lsd_kpt33', 'lsd_kpt34'), id=254, color=[128, 64, 0]), - 255: - dict(link=('lsd_kpt34', 'lsd_kpt35'), id=255, color=[128, 64, 0]), - 256: - dict(link=('lsd_kpt35', 'lsd_kpt36'), id=256, color=[128, 64, 0]), - 257: - dict(link=('lsd_kpt36', 'lsd_kpt37'), id=257, color=[128, 64, 0]), - 258: - dict(link=('lsd_kpt37', 'lsd_kpt6'), id=258, color=[128, 64, 0]), - 259: - dict(link=('lsd_kpt6', 'lsd_kpt5'), id=259, color=[128, 64, 0]), - 260: - dict(link=('lsd_kpt5', 'lsd_kpt4'), id=260, color=[128, 64, 0]), - 261: - dict(link=('lsd_kpt4', 'lsd_kpt3'), id=261, color=[128, 64, 0]), - 262: - dict(link=('lsd_kpt3', 'lsd_kpt2'), id=262, color=[128, 64, 0]), - 263: - dict(link=('lsd_kpt6', 'lsd_kpt1'), id=263, color=[128, 64, 0]), - 264: - dict(link=('vd_kpt1', 'vd_kpt2'), id=264, color=[128, 64, 255]), - 265: - dict(link=('vd_kpt2', 'vd_kpt7'), id=265, color=[128, 64, 255]), - 266: - dict(link=('vd_kpt7', 'vd_kpt8'), id=266, color=[128, 64, 255]), - 267: - dict(link=('vd_kpt8', 'vd_kpt9'), id=267, color=[128, 64, 255]), - 268: - dict(link=('vd_kpt9', 'vd_kpt10'), id=268, color=[128, 64, 255]), - 269: - dict(link=('vd_kpt10', 'vd_kpt11'), id=269, color=[128, 64, 255]), - 270: - dict(link=('vd_kpt11', 'vd_kpt12'), id=270, color=[128, 64, 255]), - 271: - dict(link=('vd_kpt12', 'vd_kpt13'), id=271, color=[128, 64, 255]), - 272: - dict(link=('vd_kpt13', 'vd_kpt14'), id=272, color=[128, 64, 255]), - 273: - dict(link=('vd_kpt14', 'vd_kpt15'), id=273, color=[128, 64, 255]), - 274: - dict(link=('vd_kpt15', 'vd_kpt16'), id=274, color=[128, 64, 255]), - 275: - dict(link=('vd_kpt16', 'vd_kpt17'), id=275, color=[128, 64, 255]), - 276: - dict(link=('vd_kpt17', 'vd_kpt18'), id=276, color=[128, 64, 255]), - 277: - dict(link=('vd_kpt18', 'vd_kpt19'), id=277, color=[128, 64, 255]), - 278: - dict(link=('vd_kpt19', 'vd_kpt6'), id=278, color=[128, 64, 255]), - 279: - dict(link=('vd_kpt6', 'vd_kpt5'), id=279, color=[128, 64, 255]), - 280: - dict(link=('vd_kpt5', 'vd_kpt4'), id=280, color=[128, 64, 255]), - 281: - dict(link=('vd_kpt4', 'vd_kpt3'), id=281, color=[128, 64, 255]), - 282: - dict(link=('vd_kpt3', 'vd_kpt2'), id=282, color=[128, 64, 255]), - 283: - dict(link=('vd_kpt6', 'vd_kpt1'), id=283, color=[128, 64, 255]), - 284: - dict(link=('sd_kpt1', 'sd_kpt2'), id=284, color=[128, 64, 0]), - 285: - dict(link=('sd_kpt2', 'sd_kpt8'), id=285, color=[128, 64, 0]), - 286: - dict(link=('sd_kpt8', 'sd_kpt9'), id=286, color=[128, 64, 0]), - 287: - dict(link=('sd_kpt9', 'sd_kpt10'), id=287, color=[128, 64, 0]), - 288: - dict(link=('sd_kpt10', 'sd_kpt11'), id=288, color=[128, 64, 0]), - 289: - dict(link=('sd_kpt11', 'sd_kpt12'), id=289, color=[128, 64, 0]), - 290: - dict(link=('sd_kpt12', 'sd_kpt13'), id=290, color=[128, 64, 0]), - 291: - dict(link=('sd_kpt13', 'sd_kpt14'), id=291, color=[128, 64, 0]), - 292: - dict(link=('sd_kpt14', 'sd_kpt15'), id=292, color=[128, 64, 0]), - 293: - dict(link=('sd_kpt15', 'sd_kpt16'), id=293, color=[128, 64, 0]), - 294: - dict(link=('sd_kpt16', 'sd_kpt17'), id=294, color=[128, 64, 0]), - 295: - dict(link=('sd_kpt17', 'sd_kpt18'), id=295, color=[128, 64, 0]), - 296: - dict(link=('sd_kpt18', 'sd_kpt6'), id=296, color=[128, 64, 0]), - 297: - dict(link=('sd_kpt6', 'sd_kpt5'), id=297, color=[128, 64, 0]), - 298: - dict(link=('sd_kpt5', 'sd_kpt4'), id=298, color=[128, 64, 0]), - 299: - dict(link=('sd_kpt4', 'sd_kpt3'), id=299, color=[128, 64, 0]), - 300: - dict(link=('sd_kpt3', 'sd_kpt2'), id=300, color=[128, 64, 0]), - 301: - dict(link=('sd_kpt2', 'sd_kpt7'), id=301, color=[128, 64, 0]), - 302: - dict(link=('sd_kpt6', 'sd_kpt19'), id=302, color=[128, 64, 0]), - 303: - dict(link=('sd_kpt6', 'sd_kpt1'), id=303, color=[128, 64, 0]) - }), - joint_weights=[ - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 - ], - sigmas=[]) -param_scheduler = [ - dict( - type='LinearLR', begin=0, end=500, start_factor=0.001, by_epoch=False), - dict( - type='MultiStepLR', - begin=0, - end=60, - milestones=[20, 40], - gamma=0.1, - by_epoch=True) -] -optim_wrapper = dict(optimizer=dict(type='Adam', lr=0.0005)) -auto_scale_lr = dict(base_batch_size=512) -dataset_type = 'DeepFashion2Dataset' -data_mode = 'topdown' -data_root = 'data/deepfashion2/' -codec = dict( - type='MSRAHeatmap', input_size=(192, 256), heatmap_size=(48, 64), sigma=2) -train_pipeline = [ - dict(type='LoadImage'), - dict(type='GetBBoxCenterScale'), - dict(type='RandomFlip', direction='horizontal'), - dict( - type='RandomBBoxTransform', - shift_prob=0, - rotate_factor=60, - scale_factor=(0.75, 1.25)), - dict(type='TopdownAffine', input_size=(192, 256)), - dict( - type='GenerateTarget', - encoder=dict( - type='MSRAHeatmap', - input_size=(192, 256), - heatmap_size=(48, 64), - sigma=2)), - dict(type='PackPoseInputs') -] -val_pipeline = [ - dict(type='LoadImage', backend_args=dict(backend='local')), - dict(type='GetBBoxCenterScale'), - dict(type='TopdownAffine', input_size=(192, 256)), - dict(type='PackPoseInputs') -] -train_dataloader = dict( - batch_size=64, - num_workers=6, - persistent_workers=True, - sampler=dict(type='DefaultSampler', shuffle=True), - dataset=dict( - type='DeepFashion2Dataset', - data_root='data/deepfashion2/', - data_mode='topdown', - ann_file='train/deepfashion2_trousers.json', - data_prefix=dict(img='train/image/'), - pipeline=[ - dict(type='LoadImage'), - dict(type='GetBBoxCenterScale'), - dict(type='RandomFlip', direction='horizontal'), - dict( - type='RandomBBoxTransform', - shift_prob=0, - rotate_factor=60, - scale_factor=(0.75, 1.25)), - dict(type='TopdownAffine', input_size=(192, 256)), - dict( - type='GenerateTarget', - encoder=dict( - type='MSRAHeatmap', - input_size=(192, 256), - heatmap_size=(48, 64), - sigma=2)), - dict(type='PackPoseInputs') - ])) -val_dataloader = dict( - batch_size=32, - num_workers=4, - persistent_workers=True, - drop_last=False, - sampler=dict(type='DefaultSampler', shuffle=False), - dataset=dict( - type='DeepFashion2Dataset', - data_root='data/deepfashion2/', - data_mode='topdown', - ann_file='validation/deepfashion2_trousers.json', - data_prefix=dict(img='validation/image/'), - test_mode=True, - pipeline=[ - dict(type='LoadImage', backend_args=dict(backend='local')), - dict(type='GetBBoxCenterScale'), - dict(type='TopdownAffine', input_size=(192, 256)), - dict(type='PackPoseInputs') - ])) -test_dataloader = dict( - batch_size=32, - num_workers=4, - persistent_workers=True, - drop_last=False, - sampler=dict(type='DefaultSampler', shuffle=False), - dataset=dict( - type='DeepFashion2Dataset', - data_root='data/deepfashion2/', - data_mode='topdown', - ann_file='validation/deepfashion2_trousers.json', - data_prefix=dict(img='validation/image/'), - test_mode=True, - pipeline=[ - dict(type='LoadImage', backend_args=dict(backend='local')), - dict(type='GetBBoxCenterScale'), - dict(type='TopdownAffine', input_size=(192, 256)), - dict(type='PackPoseInputs') - ])) -channel_cfg = dict( - num_output_channels=294, - dataset_joints=294, - dataset_channel=[[ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, - 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, - 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, - 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, - 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, - 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, - 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, - 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, - 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, - 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, - 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, - 290, 291, 292, 293 - ]], - inference_channel=[ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, - 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, - 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, - 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, - 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, - 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, - 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, - 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, - 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, - 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, - 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, - 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, - 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, - 290, 291, 292, 293 - ]) -model = dict( - type='TopdownPoseEstimator', - data_preprocessor=dict( - type='PoseDataPreprocessor', - mean=[123.675, 116.28, 103.53], - std=[58.395, 57.12, 57.375], - bgr_to_rgb=True), - backbone=dict( - type='ResNet', - depth=50, - init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), - head=dict( - type='HeatmapHead', - in_channels=2048, - out_channels=294, - loss=dict(type='KeypointMSELoss', use_target_weight=True), - decoder=dict( - type='MSRAHeatmap', - input_size=(192, 256), - heatmap_size=(48, 64), - sigma=2)), - test_cfg=dict(flip_test=True, flip_mode='heatmap', shift_heatmap=True)) -val_evaluator = [ - dict(type='PCKAccuracy', thr=0.2), - dict(type='AUC'), - dict(type='EPE') -] -test_evaluator = [ - dict(type='PCKAccuracy', thr=0.2), - dict(type='AUC'), - dict(type='EPE') -] -launcher = 'pytorch' -work_dir = './work_dirs/td_hm_res50_4xb64-60e_deepfashion2_trousers_256x192' diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/canvasframemanager-plugin.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/canvasframemanager-plugin.js deleted file mode 100644 index b540b03c2550b81ed5a971fe71f05c9b784fc83f..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/canvasframemanager-plugin.js +++ /dev/null @@ -1,19 +0,0 @@ -import CanvasFrameManager from './canvasframemanager.js'; - -class CanvasFrameManagerPlugin extends Phaser.Plugins.BasePlugin { - - constructor(pluginManager) { - super(pluginManager); - } - - start() { - var eventEmitter = this.game.events; - eventEmitter.on('destroy', this.destroy, this); - } - - add(scene, key, width, height, cellWidth, cellHeight, fillColor) { - return new CanvasFrameManager(scene, key, width, height, cellWidth, cellHeight, fillColor); - } -} - -export default CanvasFrameManagerPlugin; \ No newline at end of file diff --git a/spaces/Aki004/herta-so-vits/cluster/train_cluster.py b/spaces/Aki004/herta-so-vits/cluster/train_cluster.py deleted file mode 100644 index 4ac025d400414226e66849407f477ae786c3d5d3..0000000000000000000000000000000000000000 --- a/spaces/Aki004/herta-so-vits/cluster/train_cluster.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -from glob import glob -from pathlib import Path -import torch -import logging -import argparse -import torch -import numpy as np -from sklearn.cluster import KMeans, MiniBatchKMeans -import tqdm -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) -import time -import random - -def train_cluster(in_dir, n_clusters, use_minibatch=True, verbose=False): - - logger.info(f"Loading features from {in_dir}") - features = [] - nums = 0 - for path in tqdm.tqdm(in_dir.glob("*.soft.pt")): - features.append(torch.load(path).squeeze(0).numpy().T) - # print(features[-1].shape) - features = np.concatenate(features, axis=0) - print(nums, features.nbytes/ 1024**2, "MB , shape:",features.shape, features.dtype) - features = features.astype(np.float32) - logger.info(f"Clustering features of shape: {features.shape}") - t = time.time() - if use_minibatch: - kmeans = MiniBatchKMeans(n_clusters=n_clusters,verbose=verbose, batch_size=4096, max_iter=80).fit(features) - else: - kmeans = KMeans(n_clusters=n_clusters,verbose=verbose).fit(features) - print(time.time()-t, "s") - - x = { - "n_features_in_": kmeans.n_features_in_, - "_n_threads": kmeans._n_threads, - "cluster_centers_": kmeans.cluster_centers_, - } - print("end") - - return x - - -if __name__ == "__main__": - - parser = argparse.ArgumentParser() - parser.add_argument('--dataset', type=Path, default="./dataset/44k", - help='path of training data directory') - parser.add_argument('--output', type=Path, default="logs/44k", - help='path of model output directory') - - args = parser.parse_args() - - checkpoint_dir = args.output - dataset = args.dataset - n_clusters = 10000 - - ckpt = {} - for spk in os.listdir(dataset): - if os.path.isdir(dataset/spk): - print(f"train kmeans for {spk}...") - in_dir = dataset/spk - x = train_cluster(in_dir, n_clusters, verbose=False) - ckpt[spk] = x - - checkpoint_path = checkpoint_dir / f"kmeans_{n_clusters}.pt" - checkpoint_path.parent.mkdir(exist_ok=True, parents=True) - torch.save( - ckpt, - checkpoint_path, - ) - - - # import cluster - # for spk in tqdm.tqdm(os.listdir("dataset")): - # if os.path.isdir(f"dataset/{spk}"): - # print(f"start kmeans inference for {spk}...") - # for feature_path in tqdm.tqdm(glob(f"dataset/{spk}/*.discrete.npy", recursive=True)): - # mel_path = feature_path.replace(".discrete.npy",".mel.npy") - # mel_spectrogram = np.load(mel_path) - # feature_len = mel_spectrogram.shape[-1] - # c = np.load(feature_path) - # c = utils.tools.repeat_expand_2d(torch.FloatTensor(c), feature_len).numpy() - # feature = c.T - # feature_class = cluster.get_cluster_result(feature, spk) - # np.save(feature_path.replace(".discrete.npy", ".discrete_class.npy"), feature_class) - - diff --git a/spaces/Alpaca233/SadTalker/src/facerender/modules/keypoint_detector.py b/spaces/Alpaca233/SadTalker/src/facerender/modules/keypoint_detector.py deleted file mode 100644 index 62a38a962b2f1a4326aac771aced353ec5e22a96..0000000000000000000000000000000000000000 --- a/spaces/Alpaca233/SadTalker/src/facerender/modules/keypoint_detector.py +++ /dev/null @@ -1,179 +0,0 @@ -from torch import nn -import torch -import torch.nn.functional as F - -from src.facerender.sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d -from src.facerender.modules.util import KPHourglass, make_coordinate_grid, AntiAliasInterpolation2d, ResBottleneck - - -class KPDetector(nn.Module): - """ - Detecting canonical keypoints. Return keypoint position and jacobian near each keypoint. - """ - - def __init__(self, block_expansion, feature_channel, num_kp, image_channel, max_features, reshape_channel, reshape_depth, - num_blocks, temperature, estimate_jacobian=False, scale_factor=1, single_jacobian_map=False): - super(KPDetector, self).__init__() - - self.predictor = KPHourglass(block_expansion, in_features=image_channel, - max_features=max_features, reshape_features=reshape_channel, reshape_depth=reshape_depth, num_blocks=num_blocks) - - # self.kp = nn.Conv3d(in_channels=self.predictor.out_filters, out_channels=num_kp, kernel_size=7, padding=3) - self.kp = nn.Conv3d(in_channels=self.predictor.out_filters, out_channels=num_kp, kernel_size=3, padding=1) - - if estimate_jacobian: - self.num_jacobian_maps = 1 if single_jacobian_map else num_kp - # self.jacobian = nn.Conv3d(in_channels=self.predictor.out_filters, out_channels=9 * self.num_jacobian_maps, kernel_size=7, padding=3) - self.jacobian = nn.Conv3d(in_channels=self.predictor.out_filters, out_channels=9 * self.num_jacobian_maps, kernel_size=3, padding=1) - ''' - initial as: - [[1 0 0] - [0 1 0] - [0 0 1]] - ''' - self.jacobian.weight.data.zero_() - self.jacobian.bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0, 0, 0, 1] * self.num_jacobian_maps, dtype=torch.float)) - else: - self.jacobian = None - - self.temperature = temperature - self.scale_factor = scale_factor - if self.scale_factor != 1: - self.down = AntiAliasInterpolation2d(image_channel, self.scale_factor) - - def gaussian2kp(self, heatmap): - """ - Extract the mean from a heatmap - """ - shape = heatmap.shape - heatmap = heatmap.unsqueeze(-1) - grid = make_coordinate_grid(shape[2:], heatmap.type()).unsqueeze_(0).unsqueeze_(0) - value = (heatmap * grid).sum(dim=(2, 3, 4)) - kp = {'value': value} - - return kp - - def forward(self, x): - if self.scale_factor != 1: - x = self.down(x) - - feature_map = self.predictor(x) - prediction = self.kp(feature_map) - - final_shape = prediction.shape - heatmap = prediction.view(final_shape[0], final_shape[1], -1) - heatmap = F.softmax(heatmap / self.temperature, dim=2) - heatmap = heatmap.view(*final_shape) - - out = self.gaussian2kp(heatmap) - - if self.jacobian is not None: - jacobian_map = self.jacobian(feature_map) - jacobian_map = jacobian_map.reshape(final_shape[0], self.num_jacobian_maps, 9, final_shape[2], - final_shape[3], final_shape[4]) - heatmap = heatmap.unsqueeze(2) - - jacobian = heatmap * jacobian_map - jacobian = jacobian.view(final_shape[0], final_shape[1], 9, -1) - jacobian = jacobian.sum(dim=-1) - jacobian = jacobian.view(jacobian.shape[0], jacobian.shape[1], 3, 3) - out['jacobian'] = jacobian - - return out - - -class HEEstimator(nn.Module): - """ - Estimating head pose and expression. - """ - - def __init__(self, block_expansion, feature_channel, num_kp, image_channel, max_features, num_bins=66, estimate_jacobian=True): - super(HEEstimator, self).__init__() - - self.conv1 = nn.Conv2d(in_channels=image_channel, out_channels=block_expansion, kernel_size=7, padding=3, stride=2) - self.norm1 = BatchNorm2d(block_expansion, affine=True) - self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) - - self.conv2 = nn.Conv2d(in_channels=block_expansion, out_channels=256, kernel_size=1) - self.norm2 = BatchNorm2d(256, affine=True) - - self.block1 = nn.Sequential() - for i in range(3): - self.block1.add_module('b1_'+ str(i), ResBottleneck(in_features=256, stride=1)) - - self.conv3 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=1) - self.norm3 = BatchNorm2d(512, affine=True) - self.block2 = ResBottleneck(in_features=512, stride=2) - - self.block3 = nn.Sequential() - for i in range(3): - self.block3.add_module('b3_'+ str(i), ResBottleneck(in_features=512, stride=1)) - - self.conv4 = nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=1) - self.norm4 = BatchNorm2d(1024, affine=True) - self.block4 = ResBottleneck(in_features=1024, stride=2) - - self.block5 = nn.Sequential() - for i in range(5): - self.block5.add_module('b5_'+ str(i), ResBottleneck(in_features=1024, stride=1)) - - self.conv5 = nn.Conv2d(in_channels=1024, out_channels=2048, kernel_size=1) - self.norm5 = BatchNorm2d(2048, affine=True) - self.block6 = ResBottleneck(in_features=2048, stride=2) - - self.block7 = nn.Sequential() - for i in range(2): - self.block7.add_module('b7_'+ str(i), ResBottleneck(in_features=2048, stride=1)) - - self.fc_roll = nn.Linear(2048, num_bins) - self.fc_pitch = nn.Linear(2048, num_bins) - self.fc_yaw = nn.Linear(2048, num_bins) - - self.fc_t = nn.Linear(2048, 3) - - self.fc_exp = nn.Linear(2048, 3*num_kp) - - def forward(self, x): - out = self.conv1(x) - out = self.norm1(out) - out = F.relu(out) - out = self.maxpool(out) - - out = self.conv2(out) - out = self.norm2(out) - out = F.relu(out) - - out = self.block1(out) - - out = self.conv3(out) - out = self.norm3(out) - out = F.relu(out) - out = self.block2(out) - - out = self.block3(out) - - out = self.conv4(out) - out = self.norm4(out) - out = F.relu(out) - out = self.block4(out) - - out = self.block5(out) - - out = self.conv5(out) - out = self.norm5(out) - out = F.relu(out) - out = self.block6(out) - - out = self.block7(out) - - out = F.adaptive_avg_pool2d(out, 1) - out = out.view(out.shape[0], -1) - - yaw = self.fc_roll(out) - pitch = self.fc_pitch(out) - roll = self.fc_yaw(out) - t = self.fc_t(out) - exp = self.fc_exp(out) - - return {'yaw': yaw, 'pitch': pitch, 'roll': roll, 't': t, 'exp': exp} - diff --git a/spaces/Andres99/Tune-A-Video-Training-UI/inference.py b/spaces/Andres99/Tune-A-Video-Training-UI/inference.py deleted file mode 100644 index 65ea5c55ce0fdacb37cf6945699824368bb5ff70..0000000000000000000000000000000000000000 --- a/spaces/Andres99/Tune-A-Video-Training-UI/inference.py +++ /dev/null @@ -1,109 +0,0 @@ -from __future__ import annotations - -import gc -import pathlib -import sys -import tempfile - -import gradio as gr -import imageio -import PIL.Image -import torch -from diffusers.utils.import_utils import is_xformers_available -from einops import rearrange -from huggingface_hub import ModelCard - -sys.path.append('Tune-A-Video') - -from tuneavideo.models.unet import UNet3DConditionModel -from tuneavideo.pipelines.pipeline_tuneavideo import TuneAVideoPipeline - - -class InferencePipeline: - def __init__(self, hf_token: str | None = None): - self.hf_token = hf_token - self.pipe = None - self.device = torch.device( - 'cuda:0' if torch.cuda.is_available() else 'cpu') - self.model_id = None - - def clear(self) -> None: - self.model_id = None - del self.pipe - self.pipe = None - torch.cuda.empty_cache() - gc.collect() - - @staticmethod - def check_if_model_is_local(model_id: str) -> bool: - return pathlib.Path(model_id).exists() - - @staticmethod - def get_model_card(model_id: str, - hf_token: str | None = None) -> ModelCard: - if InferencePipeline.check_if_model_is_local(model_id): - card_path = (pathlib.Path(model_id) / 'README.md').as_posix() - else: - card_path = model_id - return ModelCard.load(card_path, token=hf_token) - - @staticmethod - def get_base_model_info(model_id: str, hf_token: str | None = None) -> str: - card = InferencePipeline.get_model_card(model_id, hf_token) - return card.data.base_model - - def load_pipe(self, model_id: str) -> None: - if model_id == self.model_id: - return - base_model_id = self.get_base_model_info(model_id, self.hf_token) - unet = UNet3DConditionModel.from_pretrained( - model_id, - subfolder='unet', - torch_dtype=torch.float16, - use_auth_token=self.hf_token) - pipe = TuneAVideoPipeline.from_pretrained(base_model_id, - unet=unet, - torch_dtype=torch.float16, - use_auth_token=self.hf_token) - pipe = pipe.to(self.device) - if is_xformers_available(): - pipe.unet.enable_xformers_memory_efficient_attention() - self.pipe = pipe - self.model_id = model_id # type: ignore - - def run( - self, - model_id: str, - prompt: str, - video_length: int, - fps: int, - seed: int, - n_steps: int, - guidance_scale: float, - ) -> PIL.Image.Image: - if not torch.cuda.is_available(): - raise gr.Error('CUDA is not available.') - - self.load_pipe(model_id) - - generator = torch.Generator(device=self.device).manual_seed(seed) - out = self.pipe( - prompt, - video_length=video_length, - width=512, - height=512, - num_inference_steps=n_steps, - guidance_scale=guidance_scale, - generator=generator, - ) # type: ignore - - frames = rearrange(out.videos[0], 'c t h w -> t h w c') - frames = (frames * 255).to(torch.uint8).numpy() - - out_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) - writer = imageio.get_writer(out_file.name, fps=fps) - for frame in frames: - writer.append_data(frame) - writer.close() - - return out_file.name diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/schedulers/test_scheduler_dpm_sde.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/schedulers/test_scheduler_dpm_sde.py deleted file mode 100644 index 7906c8d5d4e9a4d7c2175e40a74ede0c83170b28..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/schedulers/test_scheduler_dpm_sde.py +++ /dev/null @@ -1,168 +0,0 @@ -import torch - -from diffusers import DPMSolverSDEScheduler -from diffusers.utils import torch_device -from diffusers.utils.testing_utils import require_torchsde - -from .test_schedulers import SchedulerCommonTest - - -@require_torchsde -class DPMSolverSDESchedulerTest(SchedulerCommonTest): - scheduler_classes = (DPMSolverSDEScheduler,) - num_inference_steps = 10 - - def get_scheduler_config(self, **kwargs): - config = { - "num_train_timesteps": 1100, - "beta_start": 0.0001, - "beta_end": 0.02, - "beta_schedule": "linear", - "noise_sampler_seed": 0, - } - - config.update(**kwargs) - return config - - def test_timesteps(self): - for timesteps in [10, 50, 100, 1000]: - self.check_over_configs(num_train_timesteps=timesteps) - - def test_betas(self): - for beta_start, beta_end in zip([0.00001, 0.0001, 0.001], [0.0002, 0.002, 0.02]): - self.check_over_configs(beta_start=beta_start, beta_end=beta_end) - - def test_schedules(self): - for schedule in ["linear", "scaled_linear"]: - self.check_over_configs(beta_schedule=schedule) - - def test_prediction_type(self): - for prediction_type in ["epsilon", "v_prediction"]: - self.check_over_configs(prediction_type=prediction_type) - - def test_full_loop_no_noise(self): - scheduler_class = self.scheduler_classes[0] - scheduler_config = self.get_scheduler_config() - scheduler = scheduler_class(**scheduler_config) - - scheduler.set_timesteps(self.num_inference_steps) - - model = self.dummy_model() - sample = self.dummy_sample_deter * scheduler.init_noise_sigma - sample = sample.to(torch_device) - - for i, t in enumerate(scheduler.timesteps): - sample = scheduler.scale_model_input(sample, t) - - model_output = model(sample, t) - - output = scheduler.step(model_output, t, sample) - sample = output.prev_sample - - result_sum = torch.sum(torch.abs(sample)) - result_mean = torch.mean(torch.abs(sample)) - - if torch_device in ["mps"]: - assert abs(result_sum.item() - 167.47821044921875) < 1e-2 - assert abs(result_mean.item() - 0.2178705964565277) < 1e-3 - elif torch_device in ["cuda"]: - assert abs(result_sum.item() - 171.59352111816406) < 1e-2 - assert abs(result_mean.item() - 0.22342906892299652) < 1e-3 - else: - assert abs(result_sum.item() - 162.52383422851562) < 1e-2 - assert abs(result_mean.item() - 0.211619570851326) < 1e-3 - - def test_full_loop_with_v_prediction(self): - scheduler_class = self.scheduler_classes[0] - scheduler_config = self.get_scheduler_config(prediction_type="v_prediction") - scheduler = scheduler_class(**scheduler_config) - - scheduler.set_timesteps(self.num_inference_steps) - - model = self.dummy_model() - sample = self.dummy_sample_deter * scheduler.init_noise_sigma - sample = sample.to(torch_device) - - for i, t in enumerate(scheduler.timesteps): - sample = scheduler.scale_model_input(sample, t) - - model_output = model(sample, t) - - output = scheduler.step(model_output, t, sample) - sample = output.prev_sample - - result_sum = torch.sum(torch.abs(sample)) - result_mean = torch.mean(torch.abs(sample)) - - if torch_device in ["mps"]: - assert abs(result_sum.item() - 124.77149200439453) < 1e-2 - assert abs(result_mean.item() - 0.16226289014816284) < 1e-3 - elif torch_device in ["cuda"]: - assert abs(result_sum.item() - 128.1663360595703) < 1e-2 - assert abs(result_mean.item() - 0.16688326001167297) < 1e-3 - else: - assert abs(result_sum.item() - 119.8487548828125) < 1e-2 - assert abs(result_mean.item() - 0.1560530662536621) < 1e-3 - - def test_full_loop_device(self): - scheduler_class = self.scheduler_classes[0] - scheduler_config = self.get_scheduler_config() - scheduler = scheduler_class(**scheduler_config) - - scheduler.set_timesteps(self.num_inference_steps, device=torch_device) - - model = self.dummy_model() - sample = self.dummy_sample_deter.to(torch_device) * scheduler.init_noise_sigma - - for t in scheduler.timesteps: - sample = scheduler.scale_model_input(sample, t) - - model_output = model(sample, t) - - output = scheduler.step(model_output, t, sample) - sample = output.prev_sample - - result_sum = torch.sum(torch.abs(sample)) - result_mean = torch.mean(torch.abs(sample)) - - if torch_device in ["mps"]: - assert abs(result_sum.item() - 167.46957397460938) < 1e-2 - assert abs(result_mean.item() - 0.21805934607982635) < 1e-3 - elif torch_device in ["cuda"]: - assert abs(result_sum.item() - 171.59353637695312) < 1e-2 - assert abs(result_mean.item() - 0.22342908382415771) < 1e-3 - else: - assert abs(result_sum.item() - 162.52383422851562) < 1e-2 - assert abs(result_mean.item() - 0.211619570851326) < 1e-3 - - def test_full_loop_device_karras_sigmas(self): - scheduler_class = self.scheduler_classes[0] - scheduler_config = self.get_scheduler_config() - scheduler = scheduler_class(**scheduler_config, use_karras_sigmas=True) - - scheduler.set_timesteps(self.num_inference_steps, device=torch_device) - - model = self.dummy_model() - sample = self.dummy_sample_deter.to(torch_device) * scheduler.init_noise_sigma - sample = sample.to(torch_device) - - for t in scheduler.timesteps: - sample = scheduler.scale_model_input(sample, t) - - model_output = model(sample, t) - - output = scheduler.step(model_output, t, sample) - sample = output.prev_sample - - result_sum = torch.sum(torch.abs(sample)) - result_mean = torch.mean(torch.abs(sample)) - - if torch_device in ["mps"]: - assert abs(result_sum.item() - 176.66974135742188) < 1e-2 - assert abs(result_mean.item() - 0.23003872730981811) < 1e-2 - elif torch_device in ["cuda"]: - assert abs(result_sum.item() - 177.63653564453125) < 1e-2 - assert abs(result_mean.item() - 0.23003872730981811) < 1e-2 - else: - assert abs(result_sum.item() - 170.3135223388672) < 1e-2 - assert abs(result_mean.item() - 0.23003872730981811) < 1e-2 diff --git a/spaces/Andy1621/uniformer_image_detection/mmdet/core/bbox/assigners/__init__.py b/spaces/Andy1621/uniformer_image_detection/mmdet/core/bbox/assigners/__init__.py deleted file mode 100644 index 95e34a848652f2ab3ca6d3489aa2934d24817888..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/mmdet/core/bbox/assigners/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -from .approx_max_iou_assigner import ApproxMaxIoUAssigner -from .assign_result import AssignResult -from .atss_assigner import ATSSAssigner -from .base_assigner import BaseAssigner -from .center_region_assigner import CenterRegionAssigner -from .grid_assigner import GridAssigner -from .hungarian_assigner import HungarianAssigner -from .max_iou_assigner import MaxIoUAssigner -from .point_assigner import PointAssigner -from .region_assigner import RegionAssigner - -__all__ = [ - 'BaseAssigner', 'MaxIoUAssigner', 'ApproxMaxIoUAssigner', 'AssignResult', - 'PointAssigner', 'ATSSAssigner', 'CenterRegionAssigner', 'GridAssigner', - 'HungarianAssigner', 'RegionAssigner' -] diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/fcn/fcn_d6_r101-d16_512x1024_80k_cityscapes.py b/spaces/Andy1621/uniformer_image_segmentation/configs/fcn/fcn_d6_r101-d16_512x1024_80k_cityscapes.py deleted file mode 100644 index d0bafc52abdb3d9bda87411e8199e86fc9d5a8b8..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_segmentation/configs/fcn/fcn_d6_r101-d16_512x1024_80k_cityscapes.py +++ /dev/null @@ -1,2 +0,0 @@ -_base_ = './fcn_d6_r50-d16_512x1024_80k_cityscapes.py' -model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101)) diff --git a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/extensions/superbooga/chromadb.py b/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/extensions/superbooga/chromadb.py deleted file mode 100644 index 1fb7a71848a8c99ab29b90c49902b545a1595f03..0000000000000000000000000000000000000000 --- a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/extensions/superbooga/chromadb.py +++ /dev/null @@ -1,125 +0,0 @@ -import chromadb -import posthog -import torch -from chromadb.config import Settings -from sentence_transformers import SentenceTransformer - -from modules.logging_colors import logger - -logger.info('Intercepting all calls to posthog :)') -posthog.capture = lambda *args, **kwargs: None - - -class Collecter(): - def __init__(self): - pass - - def add(self, texts: list[str]): - pass - - def get(self, search_strings: list[str], n_results: int) -> list[str]: - pass - - def clear(self): - pass - - -class Embedder(): - def __init__(self): - pass - - def embed(self, text: str) -> list[torch.Tensor]: - pass - - -class ChromaCollector(Collecter): - def __init__(self, embedder: Embedder): - super().__init__() - self.chroma_client = chromadb.Client(Settings(anonymized_telemetry=False)) - self.embedder = embedder - self.collection = self.chroma_client.create_collection(name="context", embedding_function=embedder.embed) - self.ids = [] - - def add(self, texts: list[str]): - if len(texts) == 0: - return - - self.ids = [f"id{i}" for i in range(len(texts))] - self.collection.add(documents=texts, ids=self.ids) - - def get_documents_ids_distances(self, search_strings: list[str], n_results: int): - n_results = min(len(self.ids), n_results) - if n_results == 0: - return [], [], [] - - result = self.collection.query(query_texts=search_strings, n_results=n_results, include=['documents', 'distances']) - documents = result['documents'][0] - ids = list(map(lambda x: int(x[2:]), result['ids'][0])) - distances = result['distances'][0] - return documents, ids, distances - - # Get chunks by similarity - def get(self, search_strings: list[str], n_results: int) -> list[str]: - documents, _, _ = self.get_documents_ids_distances(search_strings, n_results) - return documents - - # Get ids by similarity - def get_ids(self, search_strings: list[str], n_results: int) -> list[str]: - _, ids, _ = self.get_documents_ids_distances(search_strings, n_results) - return ids - - # Get chunks by similarity and then sort by insertion order - def get_sorted(self, search_strings: list[str], n_results: int) -> list[str]: - documents, ids, _ = self.get_documents_ids_distances(search_strings, n_results) - return [x for _, x in sorted(zip(ids, documents))] - - # Multiply distance by factor within [0, time_weight] where more recent is lower - def apply_time_weight_to_distances(self, ids: list[int], distances: list[float], time_weight: float = 1.0) -> list[float]: - if len(self.ids) <= 1: - return distances.copy() - - return [distance * (1 - _id / (len(self.ids) - 1) * time_weight) for _id, distance in zip(ids, distances)] - - # Get ids by similarity and then sort by insertion order - def get_ids_sorted(self, search_strings: list[str], n_results: int, n_initial: int = None, time_weight: float = 1.0) -> list[str]: - do_time_weight = time_weight > 0 - if not (do_time_weight and n_initial is not None): - n_initial = n_results - elif n_initial == -1: - n_initial = len(self.ids) - - if n_initial < n_results: - raise ValueError(f"n_initial {n_initial} should be >= n_results {n_results}") - - _, ids, distances = self.get_documents_ids_distances(search_strings, n_initial) - if do_time_weight: - distances_w = self.apply_time_weight_to_distances(ids, distances, time_weight=time_weight) - results = zip(ids, distances, distances_w) - results = sorted(results, key=lambda x: x[2])[:n_results] - results = sorted(results, key=lambda x: x[0]) - ids = [x[0] for x in results] - - return sorted(ids) - - def clear(self): - self.collection.delete(ids=self.ids) - self.ids = [] - - -class SentenceTransformerEmbedder(Embedder): - def __init__(self) -> None: - self.model = SentenceTransformer("sentence-transformers/all-mpnet-base-v2") - self.embed = self.model.encode - - -def make_collector(): - global embedder - return ChromaCollector(embedder) - - -def add_chunks_to_collector(chunks, collector): - collector.clear() - collector.add(chunks) - - -embedder = SentenceTransformerEmbedder() diff --git a/spaces/Audio-AGI/AudioSep/models/CLAP/open_clip/feature_fusion.py b/spaces/Audio-AGI/AudioSep/models/CLAP/open_clip/feature_fusion.py deleted file mode 100644 index dbe4e170e05894c12ebdc36ba1dc1de65e441b89..0000000000000000000000000000000000000000 --- a/spaces/Audio-AGI/AudioSep/models/CLAP/open_clip/feature_fusion.py +++ /dev/null @@ -1,192 +0,0 @@ -""" -Feature Fusion for Varible-Length Data Processing -AFF/iAFF is referred and modified from https://github.com/YimianDai/open-aff/blob/master/aff_pytorch/aff_net/fusion.py -According to the paper: Yimian Dai et al, Attentional Feature Fusion, IEEE Winter Conference on Applications of Computer Vision, WACV 2021 -""" - -import torch -import torch.nn as nn - - -class DAF(nn.Module): - """ - 直接相加 DirectAddFuse - """ - - def __init__(self): - super(DAF, self).__init__() - - def forward(self, x, residual): - return x + residual - - -class iAFF(nn.Module): - """ - 多特征融合 iAFF - """ - - def __init__(self, channels=64, r=4, type="2D"): - super(iAFF, self).__init__() - inter_channels = int(channels // r) - - if type == "1D": - # 本地注意力 - self.local_att = nn.Sequential( - nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(channels), - ) - - # 全局注意力 - self.global_att = nn.Sequential( - nn.AdaptiveAvgPool1d(1), - nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(channels), - ) - - # 第二次本地注意力 - self.local_att2 = nn.Sequential( - nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(channels), - ) - # 第二次全局注意力 - self.global_att2 = nn.Sequential( - nn.AdaptiveAvgPool1d(1), - nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(channels), - ) - elif type == "2D": - # 本地注意力 - self.local_att = nn.Sequential( - nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(channels), - ) - - # 全局注意力 - self.global_att = nn.Sequential( - nn.AdaptiveAvgPool2d(1), - nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(channels), - ) - - # 第二次本地注意力 - self.local_att2 = nn.Sequential( - nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(channels), - ) - # 第二次全局注意力 - self.global_att2 = nn.Sequential( - nn.AdaptiveAvgPool2d(1), - nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(channels), - ) - else: - raise f"the type is not supported" - - self.sigmoid = nn.Sigmoid() - - def forward(self, x, residual): - flag = False - xa = x + residual - if xa.size(0) == 1: - xa = torch.cat([xa, xa], dim=0) - flag = True - xl = self.local_att(xa) - xg = self.global_att(xa) - xlg = xl + xg - wei = self.sigmoid(xlg) - xi = x * wei + residual * (1 - wei) - - xl2 = self.local_att2(xi) - xg2 = self.global_att(xi) - xlg2 = xl2 + xg2 - wei2 = self.sigmoid(xlg2) - xo = x * wei2 + residual * (1 - wei2) - if flag: - xo = xo[0].unsqueeze(0) - return xo - - -class AFF(nn.Module): - """ - 多特征融合 AFF - """ - - def __init__(self, channels=64, r=4, type="2D"): - super(AFF, self).__init__() - inter_channels = int(channels // r) - - if type == "1D": - self.local_att = nn.Sequential( - nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(channels), - ) - self.global_att = nn.Sequential( - nn.AdaptiveAvgPool1d(1), - nn.Conv1d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv1d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm1d(channels), - ) - elif type == "2D": - self.local_att = nn.Sequential( - nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(channels), - ) - self.global_att = nn.Sequential( - nn.AdaptiveAvgPool2d(1), - nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(inter_channels), - nn.ReLU(inplace=True), - nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0), - nn.BatchNorm2d(channels), - ) - else: - raise f"the type is not supported." - - self.sigmoid = nn.Sigmoid() - - def forward(self, x, residual): - flag = False - xa = x + residual - if xa.size(0) == 1: - xa = torch.cat([xa, xa], dim=0) - flag = True - xl = self.local_att(xa) - xg = self.global_att(xa) - xlg = xl + xg - wei = self.sigmoid(xlg) - xo = 2 * x * wei + 2 * residual * (1 - wei) - if flag: - xo = xo[0].unsqueeze(0) - return xo diff --git a/spaces/Awiny/Image2Paragraph/models/controlnet_model.py b/spaces/Awiny/Image2Paragraph/models/controlnet_model.py deleted file mode 100644 index 473e0927510ef817655b413d181ce79e576e9684..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/controlnet_model.py +++ /dev/null @@ -1,56 +0,0 @@ -import cv2 -import torch -import numpy as np -from PIL import Image -from diffusers import ( - StableDiffusionControlNetPipeline, - ControlNetModel, - UniPCMultistepScheduler, -) - - -class TextToImage: - def __init__(self, device): - self.device = device - self.model = self.initialize_model() - - def initialize_model(self): - controlnet = ControlNetModel.from_pretrained( - "fusing/stable-diffusion-v1-5-controlnet-canny", - torch_dtype=torch.float16, - ) - pipeline = StableDiffusionControlNetPipeline.from_pretrained( - "runwayml/stable-diffusion-v1-5", - controlnet=controlnet, - safety_checker=None, - torch_dtype=torch.float16, - ) - pipeline.scheduler = UniPCMultistepScheduler.from_config( - pipeline.scheduler.config - ) - pipeline.enable_model_cpu_offload() - pipeline.to(self.device) - return pipeline - - @staticmethod - def preprocess_image(image): - image = np.array(image) - low_threshold = 100 - high_threshold = 200 - image = cv2.Canny(image, low_threshold, high_threshold) - image = np.stack([image, image, image], axis=2) - image = Image.fromarray(image) - return image - - def text_to_image(self, text, image): - print('\033[1;35m' + '*' * 100 + '\033[0m') - print('\nStep5, Text to Image:') - image = self.preprocess_image(image) - generated_image = self.model(text, image, num_inference_steps=20).images[0] - print("Generated image has been svaed.") - print('\033[1;35m' + '*' * 100 + '\033[0m') - return generated_image - - def text_to_image_debug(self, text, image): - print("text_to_image_debug") - return image \ No newline at end of file diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/datasets/prepare_cocofied_lvis.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/datasets/prepare_cocofied_lvis.py deleted file mode 100644 index 245c88482a9e2405e5a912b5c560aed78a614a13..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/datasets/prepare_cocofied_lvis.py +++ /dev/null @@ -1,176 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright (c) Facebook, Inc. and its affiliates. - -import copy -import json -import os -from collections import defaultdict - -# This mapping is extracted from the official LVIS mapping: -# https://github.com/lvis-dataset/lvis-api/blob/master/data/coco_to_synset.json -COCO_SYNSET_CATEGORIES = [ - {"synset": "person.n.01", "coco_cat_id": 1}, - {"synset": "bicycle.n.01", "coco_cat_id": 2}, - {"synset": "car.n.01", "coco_cat_id": 3}, - {"synset": "motorcycle.n.01", "coco_cat_id": 4}, - {"synset": "airplane.n.01", "coco_cat_id": 5}, - {"synset": "bus.n.01", "coco_cat_id": 6}, - {"synset": "train.n.01", "coco_cat_id": 7}, - {"synset": "truck.n.01", "coco_cat_id": 8}, - {"synset": "boat.n.01", "coco_cat_id": 9}, - {"synset": "traffic_light.n.01", "coco_cat_id": 10}, - {"synset": "fireplug.n.01", "coco_cat_id": 11}, - {"synset": "stop_sign.n.01", "coco_cat_id": 13}, - {"synset": "parking_meter.n.01", "coco_cat_id": 14}, - {"synset": "bench.n.01", "coco_cat_id": 15}, - {"synset": "bird.n.01", "coco_cat_id": 16}, - {"synset": "cat.n.01", "coco_cat_id": 17}, - {"synset": "dog.n.01", "coco_cat_id": 18}, - {"synset": "horse.n.01", "coco_cat_id": 19}, - {"synset": "sheep.n.01", "coco_cat_id": 20}, - {"synset": "beef.n.01", "coco_cat_id": 21}, - {"synset": "elephant.n.01", "coco_cat_id": 22}, - {"synset": "bear.n.01", "coco_cat_id": 23}, - {"synset": "zebra.n.01", "coco_cat_id": 24}, - {"synset": "giraffe.n.01", "coco_cat_id": 25}, - {"synset": "backpack.n.01", "coco_cat_id": 27}, - {"synset": "umbrella.n.01", "coco_cat_id": 28}, - {"synset": "bag.n.04", "coco_cat_id": 31}, - {"synset": "necktie.n.01", "coco_cat_id": 32}, - {"synset": "bag.n.06", "coco_cat_id": 33}, - {"synset": "frisbee.n.01", "coco_cat_id": 34}, - {"synset": "ski.n.01", "coco_cat_id": 35}, - {"synset": "snowboard.n.01", "coco_cat_id": 36}, - {"synset": "ball.n.06", "coco_cat_id": 37}, - {"synset": "kite.n.03", "coco_cat_id": 38}, - {"synset": "baseball_bat.n.01", "coco_cat_id": 39}, - {"synset": "baseball_glove.n.01", "coco_cat_id": 40}, - {"synset": "skateboard.n.01", "coco_cat_id": 41}, - {"synset": "surfboard.n.01", "coco_cat_id": 42}, - {"synset": "tennis_racket.n.01", "coco_cat_id": 43}, - {"synset": "bottle.n.01", "coco_cat_id": 44}, - {"synset": "wineglass.n.01", "coco_cat_id": 46}, - {"synset": "cup.n.01", "coco_cat_id": 47}, - {"synset": "fork.n.01", "coco_cat_id": 48}, - {"synset": "knife.n.01", "coco_cat_id": 49}, - {"synset": "spoon.n.01", "coco_cat_id": 50}, - {"synset": "bowl.n.03", "coco_cat_id": 51}, - {"synset": "banana.n.02", "coco_cat_id": 52}, - {"synset": "apple.n.01", "coco_cat_id": 53}, - {"synset": "sandwich.n.01", "coco_cat_id": 54}, - {"synset": "orange.n.01", "coco_cat_id": 55}, - {"synset": "broccoli.n.01", "coco_cat_id": 56}, - {"synset": "carrot.n.01", "coco_cat_id": 57}, - {"synset": "frank.n.02", "coco_cat_id": 58}, - {"synset": "pizza.n.01", "coco_cat_id": 59}, - {"synset": "doughnut.n.02", "coco_cat_id": 60}, - {"synset": "cake.n.03", "coco_cat_id": 61}, - {"synset": "chair.n.01", "coco_cat_id": 62}, - {"synset": "sofa.n.01", "coco_cat_id": 63}, - {"synset": "pot.n.04", "coco_cat_id": 64}, - {"synset": "bed.n.01", "coco_cat_id": 65}, - {"synset": "dining_table.n.01", "coco_cat_id": 67}, - {"synset": "toilet.n.02", "coco_cat_id": 70}, - {"synset": "television_receiver.n.01", "coco_cat_id": 72}, - {"synset": "laptop.n.01", "coco_cat_id": 73}, - {"synset": "mouse.n.04", "coco_cat_id": 74}, - {"synset": "remote_control.n.01", "coco_cat_id": 75}, - {"synset": "computer_keyboard.n.01", "coco_cat_id": 76}, - {"synset": "cellular_telephone.n.01", "coco_cat_id": 77}, - {"synset": "microwave.n.02", "coco_cat_id": 78}, - {"synset": "oven.n.01", "coco_cat_id": 79}, - {"synset": "toaster.n.02", "coco_cat_id": 80}, - {"synset": "sink.n.01", "coco_cat_id": 81}, - {"synset": "electric_refrigerator.n.01", "coco_cat_id": 82}, - {"synset": "book.n.01", "coco_cat_id": 84}, - {"synset": "clock.n.01", "coco_cat_id": 85}, - {"synset": "vase.n.01", "coco_cat_id": 86}, - {"synset": "scissors.n.01", "coco_cat_id": 87}, - {"synset": "teddy.n.01", "coco_cat_id": 88}, - {"synset": "hand_blower.n.01", "coco_cat_id": 89}, - {"synset": "toothbrush.n.01", "coco_cat_id": 90}, -] - - -def cocofy_lvis(input_filename, output_filename): - """ - Filter LVIS instance segmentation annotations to remove all categories that are not included in - COCO. The new json files can be used to evaluate COCO AP using `lvis-api`. The category ids in - the output json are the incontiguous COCO dataset ids. - - Args: - input_filename (str): path to the LVIS json file. - output_filename (str): path to the COCOfied json file. - """ - - with open(input_filename, "r") as f: - lvis_json = json.load(f) - - lvis_annos = lvis_json.pop("annotations") - cocofied_lvis = copy.deepcopy(lvis_json) - lvis_json["annotations"] = lvis_annos - - # Mapping from lvis cat id to coco cat id via synset - lvis_cat_id_to_synset = {cat["id"]: cat["synset"] for cat in lvis_json["categories"]} - synset_to_coco_cat_id = {x["synset"]: x["coco_cat_id"] for x in COCO_SYNSET_CATEGORIES} - # Synsets that we will keep in the dataset - synsets_to_keep = set(synset_to_coco_cat_id.keys()) - coco_cat_id_with_instances = defaultdict(int) - - new_annos = [] - ann_id = 1 - for ann in lvis_annos: - lvis_cat_id = ann["category_id"] - synset = lvis_cat_id_to_synset[lvis_cat_id] - if synset not in synsets_to_keep: - continue - coco_cat_id = synset_to_coco_cat_id[synset] - new_ann = copy.deepcopy(ann) - new_ann["category_id"] = coco_cat_id - new_ann["id"] = ann_id - ann_id += 1 - new_annos.append(new_ann) - coco_cat_id_with_instances[coco_cat_id] += 1 - cocofied_lvis["annotations"] = new_annos - - for image in cocofied_lvis["images"]: - for key in ["not_exhaustive_category_ids", "neg_category_ids"]: - new_category_list = [] - for lvis_cat_id in image[key]: - synset = lvis_cat_id_to_synset[lvis_cat_id] - if synset not in synsets_to_keep: - continue - coco_cat_id = synset_to_coco_cat_id[synset] - new_category_list.append(coco_cat_id) - coco_cat_id_with_instances[coco_cat_id] += 1 - image[key] = new_category_list - - coco_cat_id_with_instances = set(coco_cat_id_with_instances.keys()) - - new_categories = [] - for cat in lvis_json["categories"]: - synset = cat["synset"] - if synset not in synsets_to_keep: - continue - coco_cat_id = synset_to_coco_cat_id[synset] - if coco_cat_id not in coco_cat_id_with_instances: - continue - new_cat = copy.deepcopy(cat) - new_cat["id"] = coco_cat_id - new_categories.append(new_cat) - cocofied_lvis["categories"] = new_categories - - with open(output_filename, "w") as f: - json.dump(cocofied_lvis, f) - print("{} is COCOfied and stored in {}.".format(input_filename, output_filename)) - - -if __name__ == "__main__": - dataset_dir = os.path.join(os.getenv("DETECTRON2_DATASETS", "datasets"), "lvis") - for s in ["lvis_v0.5_train", "lvis_v0.5_val"]: - print("Start COCOfing {}.".format(s)) - cocofy_lvis( - os.path.join(dataset_dir, "{}.json".format(s)), - os.path.join(dataset_dir, "{}_cocofied.json".format(s)), - ) diff --git a/spaces/Banbri/zcvzcv/src/app/engine/forbidden.ts b/spaces/Banbri/zcvzcv/src/app/engine/forbidden.ts deleted file mode 100644 index 512b65e22b18f3bd39f6aec58198576b2ffc67f5..0000000000000000000000000000000000000000 --- a/spaces/Banbri/zcvzcv/src/app/engine/forbidden.ts +++ /dev/null @@ -1,6 +0,0 @@ - -// the NSFW has to contain bad words, but doing so might get the code flagged -// or attract unwanted attention, so we hash them -export const forbidden = [ - // TODO implement this -] \ No newline at end of file diff --git a/spaces/Bart92/RVC_HF/demucs/compressed.py b/spaces/Bart92/RVC_HF/demucs/compressed.py deleted file mode 100644 index eb8fbb75463ba71ca86729b22baebf24598ade57..0000000000000000000000000000000000000000 --- a/spaces/Bart92/RVC_HF/demucs/compressed.py +++ /dev/null @@ -1,115 +0,0 @@ -# Copyright (c) Facebook, Inc. and its 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. - -import json -from fractions import Fraction -from concurrent import futures - -import musdb -from torch import distributed - -from .audio import AudioFile - - -def get_musdb_tracks(root, *args, **kwargs): - mus = musdb.DB(root, *args, **kwargs) - return {track.name: track.path for track in mus} - - -class StemsSet: - def __init__(self, tracks, metadata, duration=None, stride=1, - samplerate=44100, channels=2, streams=slice(None)): - - self.metadata = [] - for name, path in tracks.items(): - meta = dict(metadata[name]) - meta["path"] = path - meta["name"] = name - self.metadata.append(meta) - if duration is not None and meta["duration"] < duration: - raise ValueError(f"Track {name} duration is too small {meta['duration']}") - self.metadata.sort(key=lambda x: x["name"]) - self.duration = duration - self.stride = stride - self.channels = channels - self.samplerate = samplerate - self.streams = streams - - def __len__(self): - return sum(self._examples_count(m) for m in self.metadata) - - def _examples_count(self, meta): - if self.duration is None: - return 1 - else: - return int((meta["duration"] - self.duration) // self.stride + 1) - - def track_metadata(self, index): - for meta in self.metadata: - examples = self._examples_count(meta) - if index >= examples: - index -= examples - continue - return meta - - def __getitem__(self, index): - for meta in self.metadata: - examples = self._examples_count(meta) - if index >= examples: - index -= examples - continue - streams = AudioFile(meta["path"]).read(seek_time=index * self.stride, - duration=self.duration, - channels=self.channels, - samplerate=self.samplerate, - streams=self.streams) - return (streams - meta["mean"]) / meta["std"] - - -def _get_track_metadata(path): - # use mono at 44kHz as reference. For any other settings data won't be perfectly - # normalized but it should be good enough. - audio = AudioFile(path) - mix = audio.read(streams=0, channels=1, samplerate=44100) - return {"duration": audio.duration, "std": mix.std().item(), "mean": mix.mean().item()} - - -def _build_metadata(tracks, workers=10): - pendings = [] - with futures.ProcessPoolExecutor(workers) as pool: - for name, path in tracks.items(): - pendings.append((name, pool.submit(_get_track_metadata, path))) - return {name: p.result() for name, p in pendings} - - -def _build_musdb_metadata(path, musdb, workers): - tracks = get_musdb_tracks(musdb) - metadata = _build_metadata(tracks, workers) - path.parent.mkdir(exist_ok=True, parents=True) - json.dump(metadata, open(path, "w")) - - -def get_compressed_datasets(args, samples): - metadata_file = args.metadata / "musdb.json" - if not metadata_file.is_file() and args.rank == 0: - _build_musdb_metadata(metadata_file, args.musdb, args.workers) - if args.world_size > 1: - distributed.barrier() - metadata = json.load(open(metadata_file)) - duration = Fraction(samples, args.samplerate) - stride = Fraction(args.data_stride, args.samplerate) - train_set = StemsSet(get_musdb_tracks(args.musdb, subsets=["train"], split="train"), - metadata, - duration=duration, - stride=stride, - streams=slice(1, None), - samplerate=args.samplerate, - channels=args.audio_channels) - valid_set = StemsSet(get_musdb_tracks(args.musdb, subsets=["train"], split="valid"), - metadata, - samplerate=args.samplerate, - channels=args.audio_channels) - return train_set, valid_set diff --git a/spaces/Benson/text-generation/Examples/Autobs Simulador Indonesia Apk ltima Versin.md b/spaces/Benson/text-generation/Examples/Autobs Simulador Indonesia Apk ltima Versin.md deleted file mode 100644 index 724502eaa3ecaf3352e38594c736359ca8e8287b..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Autobs Simulador Indonesia Apk ltima Versin.md +++ /dev/null @@ -1,71 +0,0 @@ -
-

Grupo de Fuerzas Especiales 2 Mod APK versión antigua: Una guía para los jugadores

-

Si eres un fan de los juegos de disparos en primera persona, es posible que hayas oído hablar de Special Forces Group 2. Este es un popular juego multijugador en línea que te permite experimentar intensas batallas con diferentes modos, armas, mapas y personajes. Pero ¿sabías que también se puede descargar la versión antigua apk mod de este juego y disfrutar de algunas características y ventajas adicionales? En este artículo, le diremos todo lo que necesita saber sobre Special Forces Group 2 mod apk versión antigua, incluyendo lo que es, por qué debe descargarlo, cómo descargarlo, y cómo usarlo. ¡Vamos a empezar!

-

autobús simulador indonesia apk última versión


Downloadhttps://bltlly.com/2v6Jxg



-

¿Qué es el Grupo de Fuerzas Especiales 2?

-

Una breve introducción al juego

-

Special Forces Group 2 es un juego de acción en 3D desarrollado por ForgeGames. Fue lanzado en 2016 para dispositivos Android e iOS. El juego tiene más de 100 millones de descargas en Google Play Store y tiene una calificación de 4.5 de 5 estrellas. El juego está inspirado en la famosa serie Counter-Strike y ofrece una jugabilidad y gráficos similares.

-

Las características y la jugabilidad del Grupo de Fuerzas Especiales 2

-

El juego tiene muchas características que lo hacen divertido y adictivo. Algunos de ellos son:

-
    -
  • 9 modos de juego: Clásico, Resurrección, Capturar la bandera, Modo Zombie, Modo Bomba, Cuchillos, Deathmatch, Carrera de Armas y Francotirador.
  • -
  • 30 mapas: Puede elegir entre diferentes lugares como desierto, ciudad, nieve, bosque, etc.
  • -
  • 25 armas: Puede equiparse con varias armas como pistolas, rifles, escopetas, francotiradores, granadas, etc.
  • -
  • 8 caracteres por equipo: puede personalizar su apariencia y elegir entre diferentes pieles y trajes.
  • -
  • Modo multijugador: Puedes jugar online con tus amigos u otros jugadores de todo el mundo.
  • -
  • Modo offline: También puedes jugar offline con bots o practicar tus habilidades.
  • -
  • Chat de voz: Puedes comunicarte con tus compañeros de equipo usando chat de voz.
  • - -
-

El modo de juego de Special Forces Group 2 es simple y directo. Usted tiene que unirse a un equipo (ya sea terroristas o antiterroristas) y completar los objetivos de cada modo. Por ejemplo, en el modo Clásico, tienes que eliminar a todos los enemigos o desactivar la bomba. En el modo Zombie, tienes que sobrevivir a los ataques zombi o infectar a otros jugadores. En el modo Capturar la bandera, tienes que capturar la bandera enemiga y llevarla de vuelta a tu base. Y así sucesivamente.

-

¿Por qué descargar la versión antigua mod apk de Special Forces Group 2?

-

Los beneficios de usar la versión antigua mod apk

-

La versión antigua apk mod de Special Forces Group 2 es una versión modificada del juego original que tiene algunas características y ventajas adicionales. Algunos de ellos son:

-
    -
  • Dinero ilimitado: Puede comprar cualquier arma o artículo sin preocuparse por el costo.
  • -
  • Pieles y trajes desbloqueados: Puede acceder a todas las pieles y trajes de forma gratuita.
  • -
  • No hay anuncios: Puedes disfrutar del juego sin anuncios molestos.
  • -
  • No se requiere raíz: No es necesario rootear el dispositivo para instalar la versión antigua mod apk.
  • -
-

Los inconvenientes y riesgos de usar la versión antigua apk mod

-

Sin embargo, el uso de la versión antigua apk mod también tiene algunos inconvenientes y riesgos que usted debe ser consciente de. Algunos de ellos son:

- Problemas de compatibilidad: La versión antigua mod apk puede no funcionar correctamente en algunos dispositivos o con algunas actualizaciones.

-

- Riesgo de prohibición: La versión antigua mod apk puede ser detectado por los desarrolladores de juegos y dar lugar a una prohibición del modo en línea.

-

-

- Riesgo de virus: La versión antigua apk mod puede contener malware o spyware que puede dañar su dispositivo o robar sus datos.

-

- Cuestiones éticas: La versión antigua apk mod puede darle una ventaja injusta sobre otros jugadores y arruinar el equilibrio y la diversión del juego.

- -

Cómo descargar e instalar la versión antigua mod apk de Special Forces Group 2?

-

Los pasos para descargar e instalar la versión antigua apk mod

-

Si todavía desea probar la versión antigua apk mod de Special Forces Group 2, aquí están los pasos para descargarlo e instalarlo:

-
    -
  1. Ir a un sitio web de confianza que proporciona la versión antigua apk mod de Special Forces Group 2. Por ejemplo, puede visitar [este enlace] para descargar la versión antigua apk mod 4.21 del juego.
  2. -
  3. Descargar el archivo apk mod y el archivo obb a su dispositivo. Asegúrese de que tiene suficiente espacio de almacenamiento y una conexión a Internet estable.
  4. -
  5. Habilite la instalación de aplicaciones de fuentes desconocidas en su dispositivo. Para hacer esto, vaya a Configuración > Seguridad > Fuentes desconocidas y conéctelo.
  6. -
  7. Busque los archivos descargados en su dispositivo e instale el archivo apk mod. No lo abra todavía.
  8. -
  9. Extraiga el archivo obb usando una aplicación de administrador de archivos y copie la carpeta llamada "com.ForgeGames.SpecialForcesGroup2" al directorio Android/obb en su dispositivo.
  10. -
  11. Iniciar el juego y disfrutar de la versión antigua apk mod de Grupo de Fuerzas Especiales 2.
  12. -
-

Los consejos y trucos para disfrutar de la versión antigua apk mod

-

Aquí hay algunos consejos y trucos para disfrutar de la versión antigua apk mod de Special Forces Group 2:

-
    -
  • Usa diferentes armas y modos para explorar el juego y divertirte.
  • -
  • Juega con tus amigos o únete a un clan para cooperar y competir con otros jugadores.
  • -
  • Ajuste la configuración de los gráficos y los controles de acuerdo con su preferencia y el rendimiento del dispositivo.
  • -
  • Sé respetuoso y amigable con otros jugadores y evita hacer trampa o abusar del juego.
  • -
  • Actualizar el juego con regularidad para obtener nuevas características y correcciones de errores.
  • -
-

Conclusión

- -

Preguntas frecuentes

-

¿Qué es el Grupo de Fuerzas Especiales 2?

-

Special Forces Group 2 es un popular juego multijugador en primera persona desarrollado por ForgeGames. Fue lanzado en 2016 para dispositivos Android e iOS.

-

¿Qué es el grupo de fuerzas especiales 2 mod apk versión antigua?

-

Grupo de Fuerzas Especiales 2 mod apk versión antigua es una versión modificada del juego original que tiene algunas características y ventajas adicionales como dinero ilimitado, pieles desbloqueadas, sin anuncios, etc.

-

¿Cómo descargar el grupo de fuerzas especiales 2 mod apk versión antigua?

-

Puede descargar Grupo de Fuerzas Especiales 2 mod apk versión antigua de un sitio web de confianza que lo proporciona. También necesita descargar el archivo obb y seguir algunos pasos para instalarlo en su dispositivo.

-

¿Es seguro el grupo de fuerzas especiales 2 mod apk versión antigua?

-

No, Grupo de Fuerzas Especiales 2 mod apk versión antigua no es seguro. Puede tener problemas de compatibilidad, riesgo de prohibición, riesgo de virus, cuestiones éticas, etc. Debe usarlo bajo su propio riesgo y discreción.

-

¿Cómo disfrutar de Special Forces Group 2 mod apk versión antigua?

-

Puedes disfrutar de Special Forces Group 2 mod apk versión antigua mediante el uso de diferentes armas y modos, jugando con tus amigos o unirse a un clan, ajustar la configuración de gráficos y controles, ser respetuoso y amigable con otros jugadores, y actualizar el juego regularmente.

64aa2da5cf
-
-
\ No newline at end of file diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/ansi.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/ansi.py deleted file mode 100644 index 66365e6536080bd9372d2a7a58b8ffa3447fec34..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/ansi.py +++ /dev/null @@ -1,240 +0,0 @@ -import re -import sys -from contextlib import suppress -from typing import Iterable, NamedTuple, Optional - -from .color import Color -from .style import Style -from .text import Text - -re_ansi = re.compile( - r""" -(?:\x1b\](.*?)\x1b\\)| -(?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~])) -""", - re.VERBOSE, -) - - -class _AnsiToken(NamedTuple): - """Result of ansi tokenized string.""" - - plain: str = "" - sgr: Optional[str] = "" - osc: Optional[str] = "" - - -def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]: - """Tokenize a string in to plain text and ANSI codes. - - Args: - ansi_text (str): A String containing ANSI codes. - - Yields: - AnsiToken: A named tuple of (plain, sgr, osc) - """ - - position = 0 - sgr: Optional[str] - osc: Optional[str] - for match in re_ansi.finditer(ansi_text): - start, end = match.span(0) - osc, sgr = match.groups() - if start > position: - yield _AnsiToken(ansi_text[position:start]) - if sgr: - if sgr == "(": - position = end + 1 - continue - if sgr.endswith("m"): - yield _AnsiToken("", sgr[1:-1], osc) - else: - yield _AnsiToken("", sgr, osc) - position = end - if position < len(ansi_text): - yield _AnsiToken(ansi_text[position:]) - - -SGR_STYLE_MAP = { - 1: "bold", - 2: "dim", - 3: "italic", - 4: "underline", - 5: "blink", - 6: "blink2", - 7: "reverse", - 8: "conceal", - 9: "strike", - 21: "underline2", - 22: "not dim not bold", - 23: "not italic", - 24: "not underline", - 25: "not blink", - 26: "not blink2", - 27: "not reverse", - 28: "not conceal", - 29: "not strike", - 30: "color(0)", - 31: "color(1)", - 32: "color(2)", - 33: "color(3)", - 34: "color(4)", - 35: "color(5)", - 36: "color(6)", - 37: "color(7)", - 39: "default", - 40: "on color(0)", - 41: "on color(1)", - 42: "on color(2)", - 43: "on color(3)", - 44: "on color(4)", - 45: "on color(5)", - 46: "on color(6)", - 47: "on color(7)", - 49: "on default", - 51: "frame", - 52: "encircle", - 53: "overline", - 54: "not frame not encircle", - 55: "not overline", - 90: "color(8)", - 91: "color(9)", - 92: "color(10)", - 93: "color(11)", - 94: "color(12)", - 95: "color(13)", - 96: "color(14)", - 97: "color(15)", - 100: "on color(8)", - 101: "on color(9)", - 102: "on color(10)", - 103: "on color(11)", - 104: "on color(12)", - 105: "on color(13)", - 106: "on color(14)", - 107: "on color(15)", -} - - -class AnsiDecoder: - """Translate ANSI code in to styled Text.""" - - def __init__(self) -> None: - self.style = Style.null() - - def decode(self, terminal_text: str) -> Iterable[Text]: - """Decode ANSI codes in an iterable of lines. - - Args: - lines (Iterable[str]): An iterable of lines of terminal output. - - Yields: - Text: Marked up Text. - """ - for line in terminal_text.splitlines(): - yield self.decode_line(line) - - def decode_line(self, line: str) -> Text: - """Decode a line containing ansi codes. - - Args: - line (str): A line of terminal output. - - Returns: - Text: A Text instance marked up according to ansi codes. - """ - from_ansi = Color.from_ansi - from_rgb = Color.from_rgb - _Style = Style - text = Text() - append = text.append - line = line.rsplit("\r", 1)[-1] - for plain_text, sgr, osc in _ansi_tokenize(line): - if plain_text: - append(plain_text, self.style or None) - elif osc is not None: - if osc.startswith("8;"): - _params, semicolon, link = osc[2:].partition(";") - if semicolon: - self.style = self.style.update_link(link or None) - elif sgr is not None: - # Translate in to semi-colon separated codes - # Ignore invalid codes, because we want to be lenient - codes = [ - min(255, int(_code) if _code else 0) - for _code in sgr.split(";") - if _code.isdigit() or _code == "" - ] - iter_codes = iter(codes) - for code in iter_codes: - if code == 0: - # reset - self.style = _Style.null() - elif code in SGR_STYLE_MAP: - # styles - self.style += _Style.parse(SGR_STYLE_MAP[code]) - elif code == 38: - #  Foreground - with suppress(StopIteration): - color_type = next(iter_codes) - if color_type == 5: - self.style += _Style.from_color( - from_ansi(next(iter_codes)) - ) - elif color_type == 2: - self.style += _Style.from_color( - from_rgb( - next(iter_codes), - next(iter_codes), - next(iter_codes), - ) - ) - elif code == 48: - # Background - with suppress(StopIteration): - color_type = next(iter_codes) - if color_type == 5: - self.style += _Style.from_color( - None, from_ansi(next(iter_codes)) - ) - elif color_type == 2: - self.style += _Style.from_color( - None, - from_rgb( - next(iter_codes), - next(iter_codes), - next(iter_codes), - ), - ) - - return text - - -if sys.platform != "win32" and __name__ == "__main__": # pragma: no cover - import io - import os - import pty - import sys - - decoder = AnsiDecoder() - - stdout = io.BytesIO() - - def read(fd: int) -> bytes: - data = os.read(fd, 1024) - stdout.write(data) - return data - - pty.spawn(sys.argv[1:], read) - - from .console import Console - - console = Console(record=True) - - stdout_result = stdout.getvalue().decode("utf-8") - print(stdout_result) - - for line in decoder.decode(stdout_result): - console.print(line) - - console.save_html("stdout.html") diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/packages/backports/__init__.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/packages/backports/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/filelist.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/filelist.py deleted file mode 100644 index 987931a9883ff36862dbd0831bd0a16903977879..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/filelist.py +++ /dev/null @@ -1,371 +0,0 @@ -"""distutils.filelist - -Provides the FileList class, used for poking about the filesystem -and building lists of files. -""" - -import os -import re -import fnmatch -import functools - -from distutils.util import convert_path -from distutils.errors import DistutilsTemplateError, DistutilsInternalError -from distutils import log - - -class FileList: - """A list of files built by on exploring the filesystem and filtered by - applying various patterns to what we find there. - - Instance attributes: - dir - directory from which files will be taken -- only used if - 'allfiles' not supplied to constructor - files - list of filenames currently being built/filtered/manipulated - allfiles - complete list of files under consideration (ie. without any - filtering applied) - """ - - def __init__(self, warn=None, debug_print=None): - # ignore argument to FileList, but keep them for backwards - # compatibility - self.allfiles = None - self.files = [] - - def set_allfiles(self, allfiles): - self.allfiles = allfiles - - def findall(self, dir=os.curdir): - self.allfiles = findall(dir) - - def debug_print(self, msg): - """Print 'msg' to stdout if the global DEBUG (taken from the - DISTUTILS_DEBUG environment variable) flag is true. - """ - from distutils.debug import DEBUG - - if DEBUG: - print(msg) - - # Collection methods - - def append(self, item): - self.files.append(item) - - def extend(self, items): - self.files.extend(items) - - def sort(self): - # Not a strict lexical sort! - sortable_files = sorted(map(os.path.split, self.files)) - self.files = [] - for sort_tuple in sortable_files: - self.files.append(os.path.join(*sort_tuple)) - - # Other miscellaneous utility methods - - def remove_duplicates(self): - # Assumes list has been sorted! - for i in range(len(self.files) - 1, 0, -1): - if self.files[i] == self.files[i - 1]: - del self.files[i] - - # "File template" methods - - def _parse_template_line(self, line): - words = line.split() - action = words[0] - - patterns = dir = dir_pattern = None - - if action in ('include', 'exclude', 'global-include', 'global-exclude'): - if len(words) < 2: - raise DistutilsTemplateError( - "'%s' expects ..." % action - ) - patterns = [convert_path(w) for w in words[1:]] - elif action in ('recursive-include', 'recursive-exclude'): - if len(words) < 3: - raise DistutilsTemplateError( - "'%s' expects ..." % action - ) - dir = convert_path(words[1]) - patterns = [convert_path(w) for w in words[2:]] - elif action in ('graft', 'prune'): - if len(words) != 2: - raise DistutilsTemplateError( - "'%s' expects a single " % action - ) - dir_pattern = convert_path(words[1]) - else: - raise DistutilsTemplateError("unknown action '%s'" % action) - - return (action, patterns, dir, dir_pattern) - - def process_template_line(self, line): # noqa: C901 - # Parse the line: split it up, make sure the right number of words - # is there, and return the relevant words. 'action' is always - # defined: it's the first word of the line. Which of the other - # three are defined depends on the action; it'll be either - # patterns, (dir and patterns), or (dir_pattern). - (action, patterns, dir, dir_pattern) = self._parse_template_line(line) - - # OK, now we know that the action is valid and we have the - # right number of words on the line for that action -- so we - # can proceed with minimal error-checking. - if action == 'include': - self.debug_print("include " + ' '.join(patterns)) - for pattern in patterns: - if not self.include_pattern(pattern, anchor=1): - log.warn("warning: no files found matching '%s'", pattern) - - elif action == 'exclude': - self.debug_print("exclude " + ' '.join(patterns)) - for pattern in patterns: - if not self.exclude_pattern(pattern, anchor=1): - log.warn( - ( - "warning: no previously-included files " - "found matching '%s'" - ), - pattern, - ) - - elif action == 'global-include': - self.debug_print("global-include " + ' '.join(patterns)) - for pattern in patterns: - if not self.include_pattern(pattern, anchor=0): - log.warn( - ( - "warning: no files found matching '%s' " - "anywhere in distribution" - ), - pattern, - ) - - elif action == 'global-exclude': - self.debug_print("global-exclude " + ' '.join(patterns)) - for pattern in patterns: - if not self.exclude_pattern(pattern, anchor=0): - log.warn( - ( - "warning: no previously-included files matching " - "'%s' found anywhere in distribution" - ), - pattern, - ) - - elif action == 'recursive-include': - self.debug_print("recursive-include {} {}".format(dir, ' '.join(patterns))) - for pattern in patterns: - if not self.include_pattern(pattern, prefix=dir): - msg = ( - "warning: no files found matching '%s' " "under directory '%s'" - ) - log.warn(msg, pattern, dir) - - elif action == 'recursive-exclude': - self.debug_print("recursive-exclude {} {}".format(dir, ' '.join(patterns))) - for pattern in patterns: - if not self.exclude_pattern(pattern, prefix=dir): - log.warn( - ( - "warning: no previously-included files matching " - "'%s' found under directory '%s'" - ), - pattern, - dir, - ) - - elif action == 'graft': - self.debug_print("graft " + dir_pattern) - if not self.include_pattern(None, prefix=dir_pattern): - log.warn("warning: no directories found matching '%s'", dir_pattern) - - elif action == 'prune': - self.debug_print("prune " + dir_pattern) - if not self.exclude_pattern(None, prefix=dir_pattern): - log.warn( - ("no previously-included directories found " "matching '%s'"), - dir_pattern, - ) - else: - raise DistutilsInternalError( - "this cannot happen: invalid action '%s'" % action - ) - - # Filtering/selection methods - - def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): - """Select strings (presumably filenames) from 'self.files' that - match 'pattern', a Unix-style wildcard (glob) pattern. Patterns - are not quite the same as implemented by the 'fnmatch' module: '*' - and '?' match non-special characters, where "special" is platform- - dependent: slash on Unix; colon, slash, and backslash on - DOS/Windows; and colon on Mac OS. - - If 'anchor' is true (the default), then the pattern match is more - stringent: "*.py" will match "foo.py" but not "foo/bar.py". If - 'anchor' is false, both of these will match. - - If 'prefix' is supplied, then only filenames starting with 'prefix' - (itself a pattern) and ending with 'pattern', with anything in between - them, will match. 'anchor' is ignored in this case. - - If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and - 'pattern' is assumed to be either a string containing a regex or a - regex object -- no translation is done, the regex is just compiled - and used as-is. - - Selected strings will be added to self.files. - - Return True if files are found, False otherwise. - """ - # XXX docstring lying about what the special chars are? - files_found = False - pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) - self.debug_print("include_pattern: applying regex r'%s'" % pattern_re.pattern) - - # delayed loading of allfiles list - if self.allfiles is None: - self.findall() - - for name in self.allfiles: - if pattern_re.search(name): - self.debug_print(" adding " + name) - self.files.append(name) - files_found = True - return files_found - - def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): - """Remove strings (presumably filenames) from 'files' that match - 'pattern'. Other parameters are the same as for - 'include_pattern()', above. - The list 'self.files' is modified in place. - Return True if files are found, False otherwise. - """ - files_found = False - pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) - self.debug_print("exclude_pattern: applying regex r'%s'" % pattern_re.pattern) - for i in range(len(self.files) - 1, -1, -1): - if pattern_re.search(self.files[i]): - self.debug_print(" removing " + self.files[i]) - del self.files[i] - files_found = True - return files_found - - -# Utility functions - - -def _find_all_simple(path): - """ - Find all files under 'path' - """ - all_unique = _UniqueDirs.filter(os.walk(path, followlinks=True)) - results = ( - os.path.join(base, file) for base, dirs, files in all_unique for file in files - ) - return filter(os.path.isfile, results) - - -class _UniqueDirs(set): - """ - Exclude previously-seen dirs from walk results, - avoiding infinite recursion. - Ref https://bugs.python.org/issue44497. - """ - - def __call__(self, walk_item): - """ - Given an item from an os.walk result, determine - if the item represents a unique dir for this instance - and if not, prevent further traversal. - """ - base, dirs, files = walk_item - stat = os.stat(base) - candidate = stat.st_dev, stat.st_ino - found = candidate in self - if found: - del dirs[:] - self.add(candidate) - return not found - - @classmethod - def filter(cls, items): - return filter(cls(), items) - - -def findall(dir=os.curdir): - """ - Find all files under 'dir' and return the list of full filenames. - Unless dir is '.', return full filenames with dir prepended. - """ - files = _find_all_simple(dir) - if dir == os.curdir: - make_rel = functools.partial(os.path.relpath, start=dir) - files = map(make_rel, files) - return list(files) - - -def glob_to_re(pattern): - """Translate a shell-like glob pattern to a regular expression; return - a string containing the regex. Differs from 'fnmatch.translate()' in - that '*' does not match "special characters" (which are - platform-specific). - """ - pattern_re = fnmatch.translate(pattern) - - # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which - # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix, - # and by extension they shouldn't match such "special characters" under - # any OS. So change all non-escaped dots in the RE to match any - # character except the special characters (currently: just os.sep). - sep = os.sep - if os.sep == '\\': - # we're using a regex to manipulate a regex, so we need - # to escape the backslash twice - sep = r'\\\\' - escaped = r'\1[^%s]' % sep - pattern_re = re.sub(r'((?>> for item in Sectioned.read(Sectioned._sample): - ... print(item) - Pair(name='sec1', value='# comments ignored') - Pair(name='sec1', value='a = 1') - Pair(name='sec1', value='b = 2') - Pair(name='sec2', value='a = 2') - - >>> res = Sectioned.section_pairs(Sectioned._sample) - >>> item = next(res) - >>> item.name - 'sec1' - >>> item.value - Pair(name='a', value='1') - >>> item = next(res) - >>> item.value - Pair(name='b', value='2') - >>> item = next(res) - >>> item.name - 'sec2' - >>> item.value - Pair(name='a', value='2') - >>> list(res) - [] - """ - - _sample = textwrap.dedent( - """ - [sec1] - # comments ignored - a = 1 - b = 2 - - [sec2] - a = 2 - """ - ).lstrip() - - @classmethod - def section_pairs(cls, text): - return ( - section._replace(value=Pair.parse(section.value)) - for section in cls.read(text, filter_=cls.valid) - if section.name is not None - ) - - @staticmethod - def read(text, filter_=None): - lines = filter(filter_, map(str.strip, text.splitlines())) - name = None - for value in lines: - section_match = value.startswith('[') and value.endswith(']') - if section_match: - name = value.strip('[]') - continue - yield Pair(name, value) - - @staticmethod - def valid(line): - return line and not line.startswith('#') - - -class DeprecatedTuple: - """ - Provide subscript item access for backward compatibility. - - >>> recwarn = getfixture('recwarn') - >>> ep = EntryPoint(name='name', value='value', group='group') - >>> ep[:] - ('name', 'value', 'group') - >>> ep[0] - 'name' - >>> len(recwarn) - 1 - """ - - _warn = functools.partial( - warnings.warn, - "EntryPoint tuple interface is deprecated. Access members by name.", - DeprecationWarning, - stacklevel=pypy_partial(2), - ) - - def __getitem__(self, item): - self._warn() - return self._key()[item] - - -class EntryPoint(DeprecatedTuple): - """An entry point as defined by Python packaging conventions. - - See `the packaging docs on entry points - `_ - for more information. - """ - - pattern = re.compile( - r'(?P[\w.]+)\s*' - r'(:\s*(?P[\w.]+)\s*)?' - r'((?P\[.*\])\s*)?$' - ) - """ - A regular expression describing the syntax for an entry point, - which might look like: - - - module - - package.module - - package.module:attribute - - package.module:object.attribute - - package.module:attr [extra1, extra2] - - Other combinations are possible as well. - - The expression is lenient about whitespace around the ':', - following the attr, and following any extras. - """ - - dist: Optional['Distribution'] = None - - def __init__(self, name, value, group): - vars(self).update(name=name, value=value, group=group) - - def load(self): - """Load the entry point from its definition. If only a module - is indicated by the value, return that module. Otherwise, - return the named object. - """ - match = self.pattern.match(self.value) - module = import_module(match.group('module')) - attrs = filter(None, (match.group('attr') or '').split('.')) - return functools.reduce(getattr, attrs, module) - - @property - def module(self): - match = self.pattern.match(self.value) - return match.group('module') - - @property - def attr(self): - match = self.pattern.match(self.value) - return match.group('attr') - - @property - def extras(self): - match = self.pattern.match(self.value) - return list(re.finditer(r'\w+', match.group('extras') or '')) - - def _for(self, dist): - vars(self).update(dist=dist) - return self - - def __iter__(self): - """ - Supply iter so one may construct dicts of EntryPoints by name. - """ - msg = ( - "Construction of dict of EntryPoints is deprecated in " - "favor of EntryPoints." - ) - warnings.warn(msg, DeprecationWarning) - return iter((self.name, self)) - - def matches(self, **params): - attrs = (getattr(self, param) for param in params) - return all(map(operator.eq, params.values(), attrs)) - - def _key(self): - return self.name, self.value, self.group - - def __lt__(self, other): - return self._key() < other._key() - - def __eq__(self, other): - return self._key() == other._key() - - def __setattr__(self, name, value): - raise AttributeError("EntryPoint objects are immutable.") - - def __repr__(self): - return ( - f'EntryPoint(name={self.name!r}, value={self.value!r}, ' - f'group={self.group!r})' - ) - - def __hash__(self): - return hash(self._key()) - - -class DeprecatedList(list): - """ - Allow an otherwise immutable object to implement mutability - for compatibility. - - >>> recwarn = getfixture('recwarn') - >>> dl = DeprecatedList(range(3)) - >>> dl[0] = 1 - >>> dl.append(3) - >>> del dl[3] - >>> dl.reverse() - >>> dl.sort() - >>> dl.extend([4]) - >>> dl.pop(-1) - 4 - >>> dl.remove(1) - >>> dl += [5] - >>> dl + [6] - [1, 2, 5, 6] - >>> dl + (6,) - [1, 2, 5, 6] - >>> dl.insert(0, 0) - >>> dl - [0, 1, 2, 5] - >>> dl == [0, 1, 2, 5] - True - >>> dl == (0, 1, 2, 5) - True - >>> len(recwarn) - 1 - """ - - __slots__ = () - - _warn = functools.partial( - warnings.warn, - "EntryPoints list interface is deprecated. Cast to list if needed.", - DeprecationWarning, - stacklevel=pypy_partial(2), - ) - - def _wrap_deprecated_method(method_name: str): # type: ignore - def wrapped(self, *args, **kwargs): - self._warn() - return getattr(super(), method_name)(*args, **kwargs) - - return method_name, wrapped - - locals().update( - map( - _wrap_deprecated_method, - '__setitem__ __delitem__ append reverse extend pop remove ' - '__iadd__ insert sort'.split(), - ) - ) - - def __add__(self, other): - if not isinstance(other, tuple): - self._warn() - other = tuple(other) - return self.__class__(tuple(self) + other) - - def __eq__(self, other): - if not isinstance(other, tuple): - self._warn() - other = tuple(other) - - return tuple(self).__eq__(other) - - -class EntryPoints(DeprecatedList): - """ - An immutable collection of selectable EntryPoint objects. - """ - - __slots__ = () - - def __getitem__(self, name): # -> EntryPoint: - """ - Get the EntryPoint in self matching name. - """ - if isinstance(name, int): - warnings.warn( - "Accessing entry points by index is deprecated. " - "Cast to tuple if needed.", - DeprecationWarning, - stacklevel=2, - ) - return super().__getitem__(name) - try: - return next(iter(self.select(name=name))) - except StopIteration: - raise KeyError(name) - - def select(self, **params): - """ - Select entry points from self that match the - given parameters (typically group and/or name). - """ - return EntryPoints(ep for ep in self if ep.matches(**params)) - - @property - def names(self): - """ - Return the set of all names of all entry points. - """ - return {ep.name for ep in self} - - @property - def groups(self): - """ - Return the set of all groups of all entry points. - - For coverage while SelectableGroups is present. - >>> EntryPoints().groups - set() - """ - return {ep.group for ep in self} - - @classmethod - def _from_text_for(cls, text, dist): - return cls(ep._for(dist) for ep in cls._from_text(text)) - - @staticmethod - def _from_text(text): - return ( - EntryPoint(name=item.value.name, value=item.value.value, group=item.name) - for item in Sectioned.section_pairs(text or '') - ) - - -class Deprecated: - """ - Compatibility add-in for mapping to indicate that - mapping behavior is deprecated. - - >>> recwarn = getfixture('recwarn') - >>> class DeprecatedDict(Deprecated, dict): pass - >>> dd = DeprecatedDict(foo='bar') - >>> dd.get('baz', None) - >>> dd['foo'] - 'bar' - >>> list(dd) - ['foo'] - >>> list(dd.keys()) - ['foo'] - >>> 'foo' in dd - True - >>> list(dd.values()) - ['bar'] - >>> len(recwarn) - 1 - """ - - _warn = functools.partial( - warnings.warn, - "SelectableGroups dict interface is deprecated. Use select.", - DeprecationWarning, - stacklevel=pypy_partial(2), - ) - - def __getitem__(self, name): - self._warn() - return super().__getitem__(name) - - def get(self, name, default=None): - self._warn() - return super().get(name, default) - - def __iter__(self): - self._warn() - return super().__iter__() - - def __contains__(self, *args): - self._warn() - return super().__contains__(*args) - - def keys(self): - self._warn() - return super().keys() - - def values(self): - self._warn() - return super().values() - - -class SelectableGroups(Deprecated, dict): - """ - A backward- and forward-compatible result from - entry_points that fully implements the dict interface. - """ - - @classmethod - def load(cls, eps): - by_group = operator.attrgetter('group') - ordered = sorted(eps, key=by_group) - grouped = itertools.groupby(ordered, by_group) - return cls((group, EntryPoints(eps)) for group, eps in grouped) - - @property - def _all(self): - """ - Reconstruct a list of all entrypoints from the groups. - """ - groups = super(Deprecated, self).values() - return EntryPoints(itertools.chain.from_iterable(groups)) - - @property - def groups(self): - return self._all.groups - - @property - def names(self): - """ - for coverage: - >>> SelectableGroups().names - set() - """ - return self._all.names - - def select(self, **params): - if not params: - return self - return self._all.select(**params) - - -class PackagePath(pathlib.PurePosixPath): - """A reference to a path in a package""" - - def read_text(self, encoding='utf-8'): - with self.locate().open(encoding=encoding) as stream: - return stream.read() - - def read_binary(self): - with self.locate().open('rb') as stream: - return stream.read() - - def locate(self): - """Return a path-like object for this path""" - return self.dist.locate_file(self) - - -class FileHash: - def __init__(self, spec): - self.mode, _, self.value = spec.partition('=') - - def __repr__(self): - return f'' - - -class Distribution: - """A Python distribution package.""" - - @abc.abstractmethod - def read_text(self, filename): - """Attempt to load metadata file given by the name. - - :param filename: The name of the file in the distribution info. - :return: The text if found, otherwise None. - """ - - @abc.abstractmethod - def locate_file(self, path): - """ - Given a path to a file in this distribution, return a path - to it. - """ - - @classmethod - def from_name(cls, name): - """Return the Distribution for the given package name. - - :param name: The name of the distribution package to search for. - :return: The Distribution instance (or subclass thereof) for the named - package, if found. - :raises PackageNotFoundError: When the named package's distribution - metadata cannot be found. - """ - for resolver in cls._discover_resolvers(): - dists = resolver(DistributionFinder.Context(name=name)) - dist = next(iter(dists), None) - if dist is not None: - return dist - else: - raise PackageNotFoundError(name) - - @classmethod - def discover(cls, **kwargs): - """Return an iterable of Distribution objects for all packages. - - Pass a ``context`` or pass keyword arguments for constructing - a context. - - :context: A ``DistributionFinder.Context`` object. - :return: Iterable of Distribution objects for all packages. - """ - context = kwargs.pop('context', None) - if context and kwargs: - raise ValueError("cannot accept context and kwargs") - context = context or DistributionFinder.Context(**kwargs) - return itertools.chain.from_iterable( - resolver(context) for resolver in cls._discover_resolvers() - ) - - @staticmethod - def at(path): - """Return a Distribution for the indicated metadata path - - :param path: a string or path-like object - :return: a concrete Distribution instance for the path - """ - return PathDistribution(pathlib.Path(path)) - - @staticmethod - def _discover_resolvers(): - """Search the meta_path for resolvers.""" - declared = ( - getattr(finder, 'find_distributions', None) for finder in sys.meta_path - ) - return filter(None, declared) - - @property - def metadata(self) -> _meta.PackageMetadata: - """Return the parsed metadata for this Distribution. - - The returned object will have keys that name the various bits of - metadata. See PEP 566 for details. - """ - text = ( - self.read_text('METADATA') - or self.read_text('PKG-INFO') - # This last clause is here to support old egg-info files. Its - # effect is to just end up using the PathDistribution's self._path - # (which points to the egg-info file) attribute unchanged. - or self.read_text('') - ) - return _adapters.Message(email.message_from_string(text)) - - @property - def name(self): - """Return the 'Name' metadata for the distribution package.""" - return self.metadata['Name'] - - @property - def _normalized_name(self): - """Return a normalized version of the name.""" - return Prepared.normalize(self.name) - - @property - def version(self): - """Return the 'Version' metadata for the distribution package.""" - return self.metadata['Version'] - - @property - def entry_points(self): - return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self) - - @property - def files(self): - """Files in this distribution. - - :return: List of PackagePath for this distribution or None - - Result is `None` if the metadata file that enumerates files - (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is - missing. - Result may be empty if the metadata exists but is empty. - """ - - def make_file(name, hash=None, size_str=None): - result = PackagePath(name) - result.hash = FileHash(hash) if hash else None - result.size = int(size_str) if size_str else None - result.dist = self - return result - - @pass_none - def make_files(lines): - return list(starmap(make_file, csv.reader(lines))) - - return make_files(self._read_files_distinfo() or self._read_files_egginfo()) - - def _read_files_distinfo(self): - """ - Read the lines of RECORD - """ - text = self.read_text('RECORD') - return text and text.splitlines() - - def _read_files_egginfo(self): - """ - SOURCES.txt might contain literal commas, so wrap each line - in quotes. - """ - text = self.read_text('SOURCES.txt') - return text and map('"{}"'.format, text.splitlines()) - - @property - def requires(self): - """Generated requirements specified for this Distribution""" - reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs() - return reqs and list(reqs) - - def _read_dist_info_reqs(self): - return self.metadata.get_all('Requires-Dist') - - def _read_egg_info_reqs(self): - source = self.read_text('requires.txt') - return pass_none(self._deps_from_requires_text)(source) - - @classmethod - def _deps_from_requires_text(cls, source): - return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source)) - - @staticmethod - def _convert_egg_info_reqs_to_simple_reqs(sections): - """ - Historically, setuptools would solicit and store 'extra' - requirements, including those with environment markers, - in separate sections. More modern tools expect each - dependency to be defined separately, with any relevant - extras and environment markers attached directly to that - requirement. This method converts the former to the - latter. See _test_deps_from_requires_text for an example. - """ - - def make_condition(name): - return name and f'extra == "{name}"' - - def quoted_marker(section): - section = section or '' - extra, sep, markers = section.partition(':') - if extra and markers: - markers = f'({markers})' - conditions = list(filter(None, [markers, make_condition(extra)])) - return '; ' + ' and '.join(conditions) if conditions else '' - - def url_req_space(req): - """ - PEP 508 requires a space between the url_spec and the quoted_marker. - Ref python/importlib_metadata#357. - """ - # '@' is uniquely indicative of a url_req. - return ' ' * ('@' in req) - - for section in sections: - space = url_req_space(section.value) - yield section.value + space + quoted_marker(section.name) - - -class DistributionFinder(MetaPathFinder): - """ - A MetaPathFinder capable of discovering installed distributions. - """ - - class Context: - """ - Keyword arguments presented by the caller to - ``distributions()`` or ``Distribution.discover()`` - to narrow the scope of a search for distributions - in all DistributionFinders. - - Each DistributionFinder may expect any parameters - and should attempt to honor the canonical - parameters defined below when appropriate. - """ - - name = None - """ - Specific name for which a distribution finder should match. - A name of ``None`` matches all distributions. - """ - - def __init__(self, **kwargs): - vars(self).update(kwargs) - - @property - def path(self): - """ - The sequence of directory path that a distribution finder - should search. - - Typically refers to Python installed package paths such as - "site-packages" directories and defaults to ``sys.path``. - """ - return vars(self).get('path', sys.path) - - @abc.abstractmethod - def find_distributions(self, context=Context()): - """ - Find distributions. - - Return an iterable of all Distribution instances capable of - loading the metadata for packages matching the ``context``, - a DistributionFinder.Context instance. - """ - - -class FastPath: - """ - Micro-optimized class for searching a path for - children. - - >>> FastPath('').children() - ['...'] - """ - - @functools.lru_cache() # type: ignore - def __new__(cls, root): - return super().__new__(cls) - - def __init__(self, root): - self.root = str(root) - - def joinpath(self, child): - return pathlib.Path(self.root, child) - - def children(self): - with suppress(Exception): - return os.listdir(self.root or '.') - with suppress(Exception): - return self.zip_children() - return [] - - def zip_children(self): - zip_path = zipp.Path(self.root) - names = zip_path.root.namelist() - self.joinpath = zip_path.joinpath - - return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names) - - def search(self, name): - return self.lookup(self.mtime).search(name) - - @property - def mtime(self): - with suppress(OSError): - return os.stat(self.root).st_mtime - self.lookup.cache_clear() - - @method_cache - def lookup(self, mtime): - return Lookup(self) - - -class Lookup: - def __init__(self, path: FastPath): - base = os.path.basename(path.root).lower() - base_is_egg = base.endswith(".egg") - self.infos = FreezableDefaultDict(list) - self.eggs = FreezableDefaultDict(list) - - for child in path.children(): - low = child.lower() - if low.endswith((".dist-info", ".egg-info")): - # rpartition is faster than splitext and suitable for this purpose. - name = low.rpartition(".")[0].partition("-")[0] - normalized = Prepared.normalize(name) - self.infos[normalized].append(path.joinpath(child)) - elif base_is_egg and low == "egg-info": - name = base.rpartition(".")[0].partition("-")[0] - legacy_normalized = Prepared.legacy_normalize(name) - self.eggs[legacy_normalized].append(path.joinpath(child)) - - self.infos.freeze() - self.eggs.freeze() - - def search(self, prepared): - infos = ( - self.infos[prepared.normalized] - if prepared - else itertools.chain.from_iterable(self.infos.values()) - ) - eggs = ( - self.eggs[prepared.legacy_normalized] - if prepared - else itertools.chain.from_iterable(self.eggs.values()) - ) - return itertools.chain(infos, eggs) - - -class Prepared: - """ - A prepared search for metadata on a possibly-named package. - """ - - normalized = None - legacy_normalized = None - - def __init__(self, name): - self.name = name - if name is None: - return - self.normalized = self.normalize(name) - self.legacy_normalized = self.legacy_normalize(name) - - @staticmethod - def normalize(name): - """ - PEP 503 normalization plus dashes as underscores. - """ - return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') - - @staticmethod - def legacy_normalize(name): - """ - Normalize the package name as found in the convention in - older packaging tools versions and specs. - """ - return name.lower().replace('-', '_') - - def __bool__(self): - return bool(self.name) - - -@install -class MetadataPathFinder(NullFinder, DistributionFinder): - """A degenerate finder for distribution packages on the file system. - - This finder supplies only a find_distributions() method for versions - of Python that do not have a PathFinder find_distributions(). - """ - - def find_distributions(self, context=DistributionFinder.Context()): - """ - Find distributions. - - Return an iterable of all Distribution instances capable of - loading the metadata for packages matching ``context.name`` - (or all names if ``None`` indicated) along the paths in the list - of directories ``context.path``. - """ - found = self._search_paths(context.name, context.path) - return map(PathDistribution, found) - - @classmethod - def _search_paths(cls, name, paths): - """Find metadata directories in paths heuristically.""" - prepared = Prepared(name) - return itertools.chain.from_iterable( - path.search(prepared) for path in map(FastPath, paths) - ) - - def invalidate_caches(cls): - FastPath.__new__.cache_clear() - - -class PathDistribution(Distribution): - def __init__(self, path: SimplePath): - """Construct a distribution. - - :param path: SimplePath indicating the metadata directory. - """ - self._path = path - - def read_text(self, filename): - with suppress( - FileNotFoundError, - IsADirectoryError, - KeyError, - NotADirectoryError, - PermissionError, - ): - return self._path.joinpath(filename).read_text(encoding='utf-8') - - read_text.__doc__ = Distribution.read_text.__doc__ - - def locate_file(self, path): - return self._path.parent / path - - @property - def _normalized_name(self): - """ - Performance optimization: where possible, resolve the - normalized name from the file system path. - """ - stem = os.path.basename(str(self._path)) - return self._name_from_stem(stem) or super()._normalized_name - - def _name_from_stem(self, stem): - name, ext = os.path.splitext(stem) - if ext not in ('.dist-info', '.egg-info'): - return - name, sep, rest = stem.partition('-') - return name - - -def distribution(distribution_name): - """Get the ``Distribution`` instance for the named package. - - :param distribution_name: The name of the distribution package as a string. - :return: A ``Distribution`` instance (or subclass thereof). - """ - return Distribution.from_name(distribution_name) - - -def distributions(**kwargs): - """Get all ``Distribution`` instances in the current environment. - - :return: An iterable of ``Distribution`` instances. - """ - return Distribution.discover(**kwargs) - - -def metadata(distribution_name) -> _meta.PackageMetadata: - """Get the metadata for the named package. - - :param distribution_name: The name of the distribution package to query. - :return: A PackageMetadata containing the parsed metadata. - """ - return Distribution.from_name(distribution_name).metadata - - -def version(distribution_name): - """Get the version string for the named package. - - :param distribution_name: The name of the distribution package to query. - :return: The version string for the package as defined in the package's - "Version" metadata key. - """ - return distribution(distribution_name).version - - -def entry_points(**params) -> Union[EntryPoints, SelectableGroups]: - """Return EntryPoint objects for all installed packages. - - Pass selection parameters (group or name) to filter the - result to entry points matching those properties (see - EntryPoints.select()). - - For compatibility, returns ``SelectableGroups`` object unless - selection parameters are supplied. In the future, this function - will return ``EntryPoints`` instead of ``SelectableGroups`` - even when no selection parameters are supplied. - - For maximum future compatibility, pass selection parameters - or invoke ``.select`` with parameters on the result. - - :return: EntryPoints or SelectableGroups for all installed packages. - """ - norm_name = operator.attrgetter('_normalized_name') - unique = functools.partial(unique_everseen, key=norm_name) - eps = itertools.chain.from_iterable( - dist.entry_points for dist in unique(distributions()) - ) - return SelectableGroups.load(eps).select(**params) - - -def files(distribution_name): - """Return a list of files for the named package. - - :param distribution_name: The name of the distribution package to query. - :return: List of files composing the distribution. - """ - return distribution(distribution_name).files - - -def requires(distribution_name): - """ - Return a list of requirements for the named package. - - :return: An iterator of requirements, suitable for - packaging.requirement.Requirement. - """ - return distribution(distribution_name).requires - - -def packages_distributions() -> Mapping[str, List[str]]: - """ - Return a mapping of top-level packages to their - distributions. - - >>> import collections.abc - >>> pkgs = packages_distributions() - >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values()) - True - """ - pkg_to_dist = collections.defaultdict(list) - for dist in distributions(): - for pkg in _top_level_declared(dist) or _top_level_inferred(dist): - pkg_to_dist[pkg].append(dist.metadata['Name']) - return dict(pkg_to_dist) - - -def _top_level_declared(dist): - return (dist.read_text('top_level.txt') or '').split() - - -def _top_level_inferred(dist): - return { - f.parts[0] if len(f.parts) > 1 else f.with_suffix('').name - for f in always_iterable(dist.files) - if f.suffix == ".py" - } diff --git a/spaces/BilalSardar/Voice-Cloning/app.py b/spaces/BilalSardar/Voice-Cloning/app.py deleted file mode 100644 index 778e84d07de39404d953894513627e7eb138b397..0000000000000000000000000000000000000000 --- a/spaces/BilalSardar/Voice-Cloning/app.py +++ /dev/null @@ -1,165 +0,0 @@ -from turtle import title -import gradio as gr - -import git -import os -os.system('git clone https://github.com/Edresson/Coqui-TTS -b multilingual-torchaudio-SE TTS') -os.system('pip install -q -e TTS/') -os.system('pip install -q torchaudio==0.9.0') - -import sys -TTS_PATH = "TTS/" - -# add libraries into environment -sys.path.append(TTS_PATH) # set this if TTS is not installed globally - -import os -import string -import time -import argparse -import json - -import numpy as np -import IPython -from IPython.display import Audio - - -import torch - -from TTS.tts.utils.synthesis import synthesis -#from TTS.tts.utils.text.symbols import make_symbols, phonemes, symbols -try: - from TTS.utils.audio import AudioProcessor -except: - from TTS.utils.audio import AudioProcessor - - -from TTS.tts.models import setup_model -from TTS.config import load_config -from TTS.tts.models.vits import * - -OUT_PATH = 'out/' - -# create output path -os.makedirs(OUT_PATH, exist_ok=True) - -# model vars -MODEL_PATH = '/home/user/app/best_model_latest.pth.tar' -CONFIG_PATH = '/home/user/app/config.json' -TTS_LANGUAGES = "/home/user/app/language_ids.json" -TTS_SPEAKERS = "/home/user/app/speakers.json" -USE_CUDA = torch.cuda.is_available() - -# load the config -C = load_config(CONFIG_PATH) - - -# load the audio processor -ap = AudioProcessor(**C.audio) - -speaker_embedding = None - -C.model_args['d_vector_file'] = TTS_SPEAKERS -C.model_args['use_speaker_encoder_as_loss'] = False - -model = setup_model(C) -model.language_manager.set_language_ids_from_file(TTS_LANGUAGES) -# print(model.language_manager.num_languages, model.embedded_language_dim) -# print(model.emb_l) -cp = torch.load(MODEL_PATH, map_location=torch.device('cpu')) -# remove speaker encoder -model_weights = cp['model'].copy() -for key in list(model_weights.keys()): - if "speaker_encoder" in key: - del model_weights[key] - -model.load_state_dict(model_weights) - - -model.eval() - -if USE_CUDA: - model = model.cuda() - -# synthesize voice -use_griffin_lim = False - -os.system('pip install -q pydub ffmpeg-normalize') - -CONFIG_SE_PATH = "config_se.json" -CHECKPOINT_SE_PATH = "SE_checkpoint.pth.tar" - -from TTS.tts.utils.speakers import SpeakerManager -from pydub import AudioSegment -import librosa - -SE_speaker_manager = SpeakerManager(encoder_model_path=CHECKPOINT_SE_PATH, encoder_config_path=CONFIG_SE_PATH, use_cuda=USE_CUDA) - -def compute_spec(ref_file): - y, sr = librosa.load(ref_file, sr=ap.sample_rate) - spec = ap.spectrogram(y) - spec = torch.FloatTensor(spec).unsqueeze(0) - return spec - - - -def greet(Text,Voicetoclone,VoiceMicrophone): - text= "%s" % (Text) - if Voicetoclone is not None: - reference_files= "%s" % (Voicetoclone) - print("path url") - print(Voicetoclone) - sample= str(Voicetoclone) - else: - reference_files= "%s" % (VoiceMicrophone) - print("path url") - print(VoiceMicrophone) - sample= str(VoiceMicrophone) - size= len(reference_files)*sys.getsizeof(reference_files) - size2= size / 1000000 - if (size2 > 0.012) or len(text)>2000: - message="File is greater than 30mb or Text inserted is longer than 2000 characters. Please re-try with smaller sizes." - print(message) - raise SystemExit("File is greater than 30mb. Please re-try or Text inserted is longer than 2000 characters. Please re-try with smaller sizes.") - else: - os.system('ffmpeg-normalize $sample -nt rms -t=-27 -o $sample -ar 16000 -f') - reference_emb = SE_speaker_manager.compute_d_vector_from_clip(reference_files) - model.length_scale = 1 # scaler for the duration predictor. The larger it is, the slower the speech. - model.inference_noise_scale = 0.3 # defines the noise variance applied to the random z vector at inference. - model.inference_noise_scale_dp = 0.3 # defines the noise variance applied to the duration predictor z vector at inference. - text = text - model.language_manager.language_id_mapping - language_id = 0 - - print(" > text: {}".format(text)) - wav, alignment, _, _ = synthesis( - model, - text, - C, - "cuda" in str(next(model.parameters()).device), - ap, - speaker_id=None, - d_vector=reference_emb, - style_wav=None, - language_id=language_id, - enable_eos_bos_chars=C.enable_eos_bos_chars, - use_griffin_lim=True, - do_trim_silence=False, - ).values() - print("Generated Audio") - IPython.display.display(Audio(wav, rate=ap.sample_rate)) - #file_name = text.replace(" ", "_") - #file_name = file_name.translate(str.maketrans('', '', string.punctuation.replace('_', ''))) + '.wav' - file_name="Audio.wav" - out_path = os.path.join(OUT_PATH, file_name) - print(" > Saving output to {}".format(out_path)) - ap.save_wav(wav, out_path) - return out_path - -demo = gr.Interface( - fn=greet, - inputs=[gr.inputs.Textbox(label='What would you like the voice to say? (max. 2000 characters per request)'),gr.Audio(type="filepath", source="upload",label='Please upload a voice to clone (max. 30mb)'),gr.Audio(source="microphone", type="filepath", streaming=True)], - outputs="audio", - title="Bilal's Voice Cloning Tool" - ) -demo.launch() \ No newline at end of file diff --git a/spaces/CVPR/LIVE/pybind11/include/pybind11/eigen.h b/spaces/CVPR/LIVE/pybind11/include/pybind11/eigen.h deleted file mode 100644 index 22139def6013b47005df22be778bd6984e05ea1d..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/pybind11/include/pybind11/eigen.h +++ /dev/null @@ -1,607 +0,0 @@ -/* - pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices - - Copyright (c) 2016 Wenzel Jakob - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#pragma once - -#include "numpy.h" - -#if defined(__INTEL_COMPILER) -# pragma warning(disable: 1682) // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem) -#elif defined(__GNUG__) || defined(__clang__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wconversion" -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" -# ifdef __clang__ -// Eigen generates a bunch of implicit-copy-constructor-is-deprecated warnings with -Wdeprecated -// under Clang, so disable that warning here: -# pragma GCC diagnostic ignored "-Wdeprecated" -# endif -# if __GNUC__ >= 7 -# pragma GCC diagnostic ignored "-Wint-in-bool-context" -# endif -#endif - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant -# pragma warning(disable: 4996) // warning C4996: std::unary_negate is deprecated in C++17 -#endif - -#include -#include - -// Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit -// move constructors that break things. We could detect this an explicitly copy, but an extra copy -// of matrices seems highly undesirable. -static_assert(EIGEN_VERSION_AT_LEAST(3,2,7), "Eigen support in pybind11 requires Eigen >= 3.2.7"); - -PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) - -// Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides: -using EigenDStride = Eigen::Stride; -template using EigenDRef = Eigen::Ref; -template using EigenDMap = Eigen::Map; - -PYBIND11_NAMESPACE_BEGIN(detail) - -#if EIGEN_VERSION_AT_LEAST(3,3,0) -using EigenIndex = Eigen::Index; -#else -using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE; -#endif - -// Matches Eigen::Map, Eigen::Ref, blocks, etc: -template using is_eigen_dense_map = all_of, std::is_base_of, T>>; -template using is_eigen_mutable_map = std::is_base_of, T>; -template using is_eigen_dense_plain = all_of>, is_template_base_of>; -template using is_eigen_sparse = is_template_base_of; -// Test for objects inheriting from EigenBase that aren't captured by the above. This -// basically covers anything that can be assigned to a dense matrix but that don't have a typical -// matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and -// SelfAdjointView fall into this category. -template using is_eigen_other = all_of< - is_template_base_of, - negation, is_eigen_dense_plain, is_eigen_sparse>> ->; - -// Captures numpy/eigen conformability status (returned by EigenProps::conformable()): -template struct EigenConformable { - bool conformable = false; - EigenIndex rows = 0, cols = 0; - EigenDStride stride{0, 0}; // Only valid if negativestrides is false! - bool negativestrides = false; // If true, do not use stride! - - EigenConformable(bool fits = false) : conformable{fits} {} - // Matrix type: - EigenConformable(EigenIndex r, EigenIndex c, - EigenIndex rstride, EigenIndex cstride) : - conformable{true}, rows{r}, cols{c} { - // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity. http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747 - if (rstride < 0 || cstride < 0) { - negativestrides = true; - } else { - stride = {EigenRowMajor ? rstride : cstride /* outer stride */, - EigenRowMajor ? cstride : rstride /* inner stride */ }; - } - } - // Vector type: - EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride) - : EigenConformable(r, c, r == 1 ? c*stride : stride, c == 1 ? r : r*stride) {} - - template bool stride_compatible() const { - // To have compatible strides, we need (on both dimensions) one of fully dynamic strides, - // matching strides, or a dimension size of 1 (in which case the stride value is irrelevant) - return - !negativestrides && - (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner() || - (EigenRowMajor ? cols : rows) == 1) && - (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer() || - (EigenRowMajor ? rows : cols) == 1); - } - operator bool() const { return conformable; } -}; - -template struct eigen_extract_stride { using type = Type; }; -template -struct eigen_extract_stride> { using type = StrideType; }; -template -struct eigen_extract_stride> { using type = StrideType; }; - -// Helper struct for extracting information from an Eigen type -template struct EigenProps { - using Type = Type_; - using Scalar = typename Type::Scalar; - using StrideType = typename eigen_extract_stride::type; - static constexpr EigenIndex - rows = Type::RowsAtCompileTime, - cols = Type::ColsAtCompileTime, - size = Type::SizeAtCompileTime; - static constexpr bool - row_major = Type::IsRowMajor, - vector = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1 - fixed_rows = rows != Eigen::Dynamic, - fixed_cols = cols != Eigen::Dynamic, - fixed = size != Eigen::Dynamic, // Fully-fixed size - dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size - - template using if_zero = std::integral_constant; - static constexpr EigenIndex inner_stride = if_zero::value, - outer_stride = if_zero::value; - static constexpr bool dynamic_stride = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic; - static constexpr bool requires_row_major = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1; - static constexpr bool requires_col_major = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1; - - // Takes an input array and determines whether we can make it fit into the Eigen type. If - // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector - // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type). - static EigenConformable conformable(const array &a) { - const auto dims = a.ndim(); - if (dims < 1 || dims > 2) - return false; - - if (dims == 2) { // Matrix type: require exact match (or dynamic) - - EigenIndex - np_rows = a.shape(0), - np_cols = a.shape(1), - np_rstride = a.strides(0) / static_cast(sizeof(Scalar)), - np_cstride = a.strides(1) / static_cast(sizeof(Scalar)); - if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols)) - return false; - - return {np_rows, np_cols, np_rstride, np_cstride}; - } - - // Otherwise we're storing an n-vector. Only one of the strides will be used, but whichever - // is used, we want the (single) numpy stride value. - const EigenIndex n = a.shape(0), - stride = a.strides(0) / static_cast(sizeof(Scalar)); - - if (vector) { // Eigen type is a compile-time vector - if (fixed && size != n) - return false; // Vector size mismatch - return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride}; - } - else if (fixed) { - // The type has a fixed size, but is not a vector: abort - return false; - } - else if (fixed_cols) { - // Since this isn't a vector, cols must be != 1. We allow this only if it exactly - // equals the number of elements (rows is Dynamic, and so 1 row is allowed). - if (cols != n) return false; - return {1, n, stride}; - } - else { - // Otherwise it's either fully dynamic, or column dynamic; both become a column vector - if (fixed_rows && rows != n) return false; - return {n, 1, stride}; - } - } - - static constexpr bool show_writeable = is_eigen_dense_map::value && is_eigen_mutable_map::value; - static constexpr bool show_order = is_eigen_dense_map::value; - static constexpr bool show_c_contiguous = show_order && requires_row_major; - static constexpr bool show_f_contiguous = !show_c_contiguous && show_order && requires_col_major; - - static constexpr auto descriptor = - _("numpy.ndarray[") + npy_format_descriptor::name + - _("[") + _(_<(size_t) rows>(), _("m")) + - _(", ") + _(_<(size_t) cols>(), _("n")) + - _("]") + - // For a reference type (e.g. Ref) we have other constraints that might need to be - // satisfied: writeable=True (for a mutable reference), and, depending on the map's stride - // options, possibly f_contiguous or c_contiguous. We include them in the descriptor output - // to provide some hint as to why a TypeError is occurring (otherwise it can be confusing to - // see that a function accepts a 'numpy.ndarray[float64[3,2]]' and an error message that you - // *gave* a numpy.ndarray of the right type and dimensions. - _(", flags.writeable", "") + - _(", flags.c_contiguous", "") + - _(", flags.f_contiguous", "") + - _("]"); -}; - -// Casts an Eigen type to numpy array. If given a base, the numpy array references the src data, -// otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array. -template handle eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) { - constexpr ssize_t elem_size = sizeof(typename props::Scalar); - array a; - if (props::vector) - a = array({ src.size() }, { elem_size * src.innerStride() }, src.data(), base); - else - a = array({ src.rows(), src.cols() }, { elem_size * src.rowStride(), elem_size * src.colStride() }, - src.data(), base); - - if (!writeable) - array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_; - - return a.release(); -} - -// Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that -// reference the Eigen object's data with `base` as the python-registered base class (if omitted, -// the base will be set to None, and lifetime management is up to the caller). The numpy array is -// non-writeable if the given type is const. -template -handle eigen_ref_array(Type &src, handle parent = none()) { - // none here is to get past array's should-we-copy detection, which currently always - // copies when there is no base. Setting the base to None should be harmless. - return eigen_array_cast(src, parent, !std::is_const::value); -} - -// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a numpy -// array that references the encapsulated data with a python-side reference to the capsule to tie -// its destruction to that of any dependent python objects. Const-ness is determined by whether or -// not the Type of the pointer given is const. -template ::value>> -handle eigen_encapsulate(Type *src) { - capsule base(src, [](void *o) { delete static_cast(o); }); - return eigen_ref_array(*src, base); -} - -// Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense -// types. -template -struct type_caster::value>> { - using Scalar = typename Type::Scalar; - using props = EigenProps; - - bool load(handle src, bool convert) { - // If we're in no-convert mode, only load if given an array of the correct type - if (!convert && !isinstance>(src)) - return false; - - // Coerce into an array, but don't do type conversion yet; the copy below handles it. - auto buf = array::ensure(src); - - if (!buf) - return false; - - auto dims = buf.ndim(); - if (dims < 1 || dims > 2) - return false; - - auto fits = props::conformable(buf); - if (!fits) - return false; - - // Allocate the new type, then build a numpy reference into it - value = Type(fits.rows, fits.cols); - auto ref = reinterpret_steal(eigen_ref_array(value)); - if (dims == 1) ref = ref.squeeze(); - else if (ref.ndim() == 1) buf = buf.squeeze(); - - int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr()); - - if (result < 0) { // Copy failed! - PyErr_Clear(); - return false; - } - - return true; - } - -private: - - // Cast implementation - template - static handle cast_impl(CType *src, return_value_policy policy, handle parent) { - switch (policy) { - case return_value_policy::take_ownership: - case return_value_policy::automatic: - return eigen_encapsulate(src); - case return_value_policy::move: - return eigen_encapsulate(new CType(std::move(*src))); - case return_value_policy::copy: - return eigen_array_cast(*src); - case return_value_policy::reference: - case return_value_policy::automatic_reference: - return eigen_ref_array(*src); - case return_value_policy::reference_internal: - return eigen_ref_array(*src, parent); - default: - throw cast_error("unhandled return_value_policy: should not happen!"); - }; - } - -public: - - // Normal returned non-reference, non-const value: - static handle cast(Type &&src, return_value_policy /* policy */, handle parent) { - return cast_impl(&src, return_value_policy::move, parent); - } - // If you return a non-reference const, we mark the numpy array readonly: - static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) { - return cast_impl(&src, return_value_policy::move, parent); - } - // lvalue reference return; default (automatic) becomes copy - static handle cast(Type &src, return_value_policy policy, handle parent) { - if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) - policy = return_value_policy::copy; - return cast_impl(&src, policy, parent); - } - // const lvalue reference return; default (automatic) becomes copy - static handle cast(const Type &src, return_value_policy policy, handle parent) { - if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) - policy = return_value_policy::copy; - return cast(&src, policy, parent); - } - // non-const pointer return - static handle cast(Type *src, return_value_policy policy, handle parent) { - return cast_impl(src, policy, parent); - } - // const pointer return - static handle cast(const Type *src, return_value_policy policy, handle parent) { - return cast_impl(src, policy, parent); - } - - static constexpr auto name = props::descriptor; - - operator Type*() { return &value; } - operator Type&() { return value; } - operator Type&&() && { return std::move(value); } - template using cast_op_type = movable_cast_op_type; - -private: - Type value; -}; - -// Base class for casting reference/map/block/etc. objects back to python. -template struct eigen_map_caster { -private: - using props = EigenProps; - -public: - - // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has - // to stay around), but we'll allow it under the assumption that you know what you're doing (and - // have an appropriate keep_alive in place). We return a numpy array pointing directly at the - // ref's data (The numpy array ends up read-only if the ref was to a const matrix type.) Note - // that this means you need to ensure you don't destroy the object in some other way (e.g. with - // an appropriate keep_alive, or with a reference to a statically allocated matrix). - static handle cast(const MapType &src, return_value_policy policy, handle parent) { - switch (policy) { - case return_value_policy::copy: - return eigen_array_cast(src); - case return_value_policy::reference_internal: - return eigen_array_cast(src, parent, is_eigen_mutable_map::value); - case return_value_policy::reference: - case return_value_policy::automatic: - case return_value_policy::automatic_reference: - return eigen_array_cast(src, none(), is_eigen_mutable_map::value); - default: - // move, take_ownership don't make any sense for a ref/map: - pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type"); - } - } - - static constexpr auto name = props::descriptor; - - // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return - // types but not bound arguments). We still provide them (with an explicitly delete) so that - // you end up here if you try anyway. - bool load(handle, bool) = delete; - operator MapType() = delete; - template using cast_op_type = MapType; -}; - -// We can return any map-like object (but can only load Refs, specialized next): -template struct type_caster::value>> - : eigen_map_caster {}; - -// Loader for Ref<...> arguments. See the documentation for info on how to make this work without -// copying (it requires some extra effort in many cases). -template -struct type_caster< - Eigen::Ref, - enable_if_t>::value> -> : public eigen_map_caster> { -private: - using Type = Eigen::Ref; - using props = EigenProps; - using Scalar = typename props::Scalar; - using MapType = Eigen::Map; - using Array = array_t; - static constexpr bool need_writeable = is_eigen_mutable_map::value; - // Delay construction (these have no default constructor) - std::unique_ptr map; - std::unique_ptr ref; - // Our array. When possible, this is just a numpy array pointing to the source data, but - // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an incompatible - // layout, or is an array of a type that needs to be converted). Using a numpy temporary - // (rather than an Eigen temporary) saves an extra copy when we need both type conversion and - // storage order conversion. (Note that we refuse to use this temporary copy when loading an - // argument for a Ref with M non-const, i.e. a read-write reference). - Array copy_or_ref; -public: - bool load(handle src, bool convert) { - // First check whether what we have is already an array of the right type. If not, we can't - // avoid a copy (because the copy is also going to do type conversion). - bool need_copy = !isinstance(src); - - EigenConformable fits; - if (!need_copy) { - // We don't need a converting copy, but we also need to check whether the strides are - // compatible with the Ref's stride requirements - Array aref = reinterpret_borrow(src); - - if (aref && (!need_writeable || aref.writeable())) { - fits = props::conformable(aref); - if (!fits) return false; // Incompatible dimensions - if (!fits.template stride_compatible()) - need_copy = true; - else - copy_or_ref = std::move(aref); - } - else { - need_copy = true; - } - } - - if (need_copy) { - // We need to copy: If we need a mutable reference, or we're not supposed to convert - // (either because we're in the no-convert overload pass, or because we're explicitly - // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading. - if (!convert || need_writeable) return false; - - Array copy = Array::ensure(src); - if (!copy) return false; - fits = props::conformable(copy); - if (!fits || !fits.template stride_compatible()) - return false; - copy_or_ref = std::move(copy); - loader_life_support::add_patient(copy_or_ref); - } - - ref.reset(); - map.reset(new MapType(data(copy_or_ref), fits.rows, fits.cols, make_stride(fits.stride.outer(), fits.stride.inner()))); - ref.reset(new Type(*map)); - - return true; - } - - operator Type*() { return ref.get(); } - operator Type&() { return *ref; } - template using cast_op_type = pybind11::detail::cast_op_type<_T>; - -private: - template ::value, int> = 0> - Scalar *data(Array &a) { return a.mutable_data(); } - - template ::value, int> = 0> - const Scalar *data(Array &a) { return a.data(); } - - // Attempt to figure out a constructor of `Stride` that will work. - // If both strides are fixed, use a default constructor: - template using stride_ctor_default = bool_constant< - S::InnerStrideAtCompileTime != Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic && - std::is_default_constructible::value>; - // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like - // Eigen::Stride, and use it: - template using stride_ctor_dual = bool_constant< - !stride_ctor_default::value && std::is_constructible::value>; - // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use - // it (passing whichever stride is dynamic). - template using stride_ctor_outer = bool_constant< - !any_of, stride_ctor_dual>::value && - S::OuterStrideAtCompileTime == Eigen::Dynamic && S::InnerStrideAtCompileTime != Eigen::Dynamic && - std::is_constructible::value>; - template using stride_ctor_inner = bool_constant< - !any_of, stride_ctor_dual>::value && - S::InnerStrideAtCompileTime == Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic && - std::is_constructible::value>; - - template ::value, int> = 0> - static S make_stride(EigenIndex, EigenIndex) { return S(); } - template ::value, int> = 0> - static S make_stride(EigenIndex outer, EigenIndex inner) { return S(outer, inner); } - template ::value, int> = 0> - static S make_stride(EigenIndex outer, EigenIndex) { return S(outer); } - template ::value, int> = 0> - static S make_stride(EigenIndex, EigenIndex inner) { return S(inner); } - -}; - -// type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not -// EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout). -// load() is not supported, but we can cast them into the python domain by first copying to a -// regular Eigen::Matrix, then casting that. -template -struct type_caster::value>> { -protected: - using Matrix = Eigen::Matrix; - using props = EigenProps; -public: - static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) { - handle h = eigen_encapsulate(new Matrix(src)); - return h; - } - static handle cast(const Type *src, return_value_policy policy, handle parent) { return cast(*src, policy, parent); } - - static constexpr auto name = props::descriptor; - - // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return - // types but not bound arguments). We still provide them (with an explicitly delete) so that - // you end up here if you try anyway. - bool load(handle, bool) = delete; - operator Type() = delete; - template using cast_op_type = Type; -}; - -template -struct type_caster::value>> { - typedef typename Type::Scalar Scalar; - typedef remove_reference_t().outerIndexPtr())> StorageIndex; - typedef typename Type::Index Index; - static constexpr bool rowMajor = Type::IsRowMajor; - - bool load(handle src, bool) { - if (!src) - return false; - - auto obj = reinterpret_borrow(src); - object sparse_module = module::import("scipy.sparse"); - object matrix_type = sparse_module.attr( - rowMajor ? "csr_matrix" : "csc_matrix"); - - if (!obj.get_type().is(matrix_type)) { - try { - obj = matrix_type(obj); - } catch (const error_already_set &) { - return false; - } - } - - auto values = array_t((object) obj.attr("data")); - auto innerIndices = array_t((object) obj.attr("indices")); - auto outerIndices = array_t((object) obj.attr("indptr")); - auto shape = pybind11::tuple((pybind11::object) obj.attr("shape")); - auto nnz = obj.attr("nnz").cast(); - - if (!values || !innerIndices || !outerIndices) - return false; - - value = Eigen::MappedSparseMatrix( - shape[0].cast(), shape[1].cast(), nnz, - outerIndices.mutable_data(), innerIndices.mutable_data(), values.mutable_data()); - - return true; - } - - static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) { - const_cast(src).makeCompressed(); - - object matrix_type = module::import("scipy.sparse").attr( - rowMajor ? "csr_matrix" : "csc_matrix"); - - array data(src.nonZeros(), src.valuePtr()); - array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr()); - array innerIndices(src.nonZeros(), src.innerIndexPtr()); - - return matrix_type( - std::make_tuple(data, innerIndices, outerIndices), - std::make_pair(src.rows(), src.cols()) - ).release(); - } - - PYBIND11_TYPE_CASTER(Type, _<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[", "scipy.sparse.csc_matrix[") - + npy_format_descriptor::name + _("]")); -}; - -PYBIND11_NAMESPACE_END(detail) -PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) - -#if defined(__GNUG__) || defined(__clang__) -# pragma GCC diagnostic pop -#elif defined(_MSC_VER) -# pragma warning(pop) -#endif diff --git a/spaces/CVPR/LIVE/setup.py b/spaces/CVPR/LIVE/setup.py deleted file mode 100644 index fdb9f6735b7adb7684bc72cbcb74c4284afd4119..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/setup.py +++ /dev/null @@ -1,98 +0,0 @@ -# Adapted from https://github.com/pybind/cmake_example/blob/master/setup.py -import os -import re -import sys -import platform -import subprocess -import importlib -from sysconfig import get_paths - -import importlib -from setuptools import setup, Extension -from setuptools.command.build_ext import build_ext -from setuptools.command.install import install -from distutils.sysconfig import get_config_var -from distutils.version import LooseVersion - -class CMakeExtension(Extension): - def __init__(self, name, sourcedir, build_with_cuda): - Extension.__init__(self, name, sources=[]) - self.sourcedir = os.path.abspath(sourcedir) - self.build_with_cuda = build_with_cuda - -class Build(build_ext): - def run(self): - try: - out = subprocess.check_output(['cmake', '--version']) - except OSError: - raise RuntimeError("CMake must be installed to build the following extensions: " + - ", ".join(e.name for e in self.extensions)) - - super().run() - - def build_extension(self, ext): - if isinstance(ext, CMakeExtension): - extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) - info = get_paths() - include_path = info['include'] - cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, - '-DPYTHON_INCLUDE_PATH=' + include_path] - - cfg = 'Debug' if self.debug else 'Release' - build_args = ['--config', cfg] - - if platform.system() == "Windows": - cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir), - '-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] - if sys.maxsize > 2**32: - cmake_args += ['-A', 'x64'] - build_args += ['--', '/m'] - else: - cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] - build_args += ['--', '-j8'] - - if ext.build_with_cuda: - cmake_args += ['-DDIFFVG_CUDA=1'] - else: - cmake_args += ['-DDIFFVG_CUDA=0'] - - env = os.environ.copy() - env['CXXFLAGS'] = '{} -DVERSION_INFO=\\"{}\\"'.format(env.get('CXXFLAGS', ''), - self.distribution.get_version()) - if not os.path.exists(self.build_temp): - os.makedirs(self.build_temp) - subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) - subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_temp) - else: - super().build_extension(ext) - -torch_spec = importlib.util.find_spec("torch") -tf_spec = importlib.util.find_spec("tensorflow") -packages = [] -build_with_cuda = False -if torch_spec is not None: - packages.append('pydiffvg') - import torch - if torch.cuda.is_available(): - build_with_cuda = True -if tf_spec is not None and sys.platform != 'win32': - packages.append('pydiffvg_tensorflow') - if not build_with_cuda: - import tensorflow as tf - if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): - build_with_cuda = True -if len(packages) == 0: - print('Error: PyTorch or Tensorflow must be installed. For Windows platform only PyTorch is supported.') - exit() -# Override build_with_cuda with environment variable -if 'DIFFVG_CUDA' in os.environ: - build_with_cuda = os.environ['DIFFVG_CUDA'] == '1' - -setup(name = 'diffvg', - version = '0.0.1', - install_requires = ["svgpathtools"], - description = 'Differentiable Vector Graphics', - ext_modules = [CMakeExtension('diffvg', '', build_with_cuda)], - cmdclass = dict(build_ext=Build, install=install), - packages = packages, - zip_safe = False) diff --git a/spaces/CVPR/LIVE/thrust/thrust/detail/type_traits/has_member_function.h b/spaces/CVPR/LIVE/thrust/thrust/detail/type_traits/has_member_function.h deleted file mode 100644 index 03ed61b6db5ad47106ed3746f3725e3676c69d33..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/detail/type_traits/has_member_function.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#define __THRUST_DEFINE_HAS_MEMBER_FUNCTION(trait_name, member_function_name) \ -template class trait_name; \ - \ -template \ -class trait_name \ -{ \ - class yes { char m; }; \ - class no { yes m[2]; }; \ - struct base_mixin \ - { \ - Result member_function_name(); \ - }; \ - struct base : public T, public base_mixin {}; \ - template class helper{}; \ - template \ - static no deduce(U*, helper* = 0); \ - static yes deduce(...); \ -public: \ - static const bool value = sizeof(yes) == sizeof(deduce(static_cast(0))); \ - typedef thrust::detail::integral_constant type; \ -}; \ - \ -template \ -class trait_name \ -{ \ - class yes { char m; }; \ - class no { yes m[2]; }; \ - struct base_mixin \ - { \ - Result member_function_name(Arg); \ - }; \ - struct base : public T, public base_mixin {}; \ - template class helper{}; \ - template \ - static no deduce(U*, helper* = 0); \ - static yes deduce(...); \ -public: \ - static const bool value = sizeof(yes) == sizeof(deduce(static_cast(0))); \ - typedef thrust::detail::integral_constant type; \ -}; \ - \ -template \ -class trait_name \ -{ \ - class yes { char m; }; \ - class no { yes m[2]; }; \ - struct base_mixin \ - { \ - Result member_function_name(Arg1,Arg2); \ - }; \ - struct base : public T, public base_mixin {}; \ - template class helper{}; \ - template \ - static no deduce(U*, helper* = 0); \ - static yes deduce(...); \ -public: \ - static const bool value = sizeof(yes) == sizeof(deduce(static_cast(0))); \ - typedef thrust::detail::integral_constant type; \ -}; \ - \ -template \ -class trait_name \ -{ \ - class yes { char m; }; \ - class no { yes m[2]; }; \ - struct base_mixin \ - { \ - Result member_function_name(Arg1,Arg2,Arg3); \ - }; \ - struct base : public T, public base_mixin {}; \ - template class helper{}; \ - template \ - static no deduce(U*, helper* = 0); \ - static yes deduce(...); \ -public: \ - static const bool value = sizeof(yes) == sizeof(deduce(static_cast(0))); \ - typedef thrust::detail::integral_constant type; \ -}; \ - \ -template \ -class trait_name \ -{ \ - class yes { char m; }; \ - class no { yes m[2]; }; \ - struct base_mixin \ - { \ - Result member_function_name(Arg1,Arg2,Arg3,Arg4); \ - }; \ - struct base : public T, public base_mixin {}; \ - template class helper{}; \ - template \ - static no deduce(U*, helper* = 0); \ - static yes deduce(...); \ -public: \ - static const bool value = sizeof(yes) == sizeof(deduce(static_cast(0))); \ - typedef thrust::detail::integral_constant type; \ -}; - diff --git a/spaces/CVPR/LIVE/thrust/thrust/sort.h b/spaces/CVPR/LIVE/thrust/thrust/sort.h deleted file mode 100644 index a100f960281394c5a178396c54cec2a73265ccc8..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/sort.h +++ /dev/null @@ -1,1362 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -/*! \file thrust/sort.h - * \brief Functions for reorganizing ranges into sorted order - */ - -#pragma once - -#include -#include - -namespace thrust -{ - - -/*! \addtogroup sorting - * \ingroup algorithms - * \{ - */ - - -/*! \p sort sorts the elements in [first, last) into - * ascending order, meaning that if \c i and \c j are any two valid - * iterators in [first, last) such that \c i precedes \c j, - * then \c *j is not less than \c *i. Note: \c sort is not guaranteed - * to be stable. That is, suppose that \c *i and \c *j are equivalent: - * neither one is less than the other. It is not guaranteed that the - * relative order of these two elements will be preserved by \p sort. - * - * This version of \p sort compares objects using \c operator<. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam RandomAccessIterator is a model of Random Access Iterator, - * \p RandomAccessIterator is mutable, - * and \p RandomAccessIterator's \c value_type is a model of LessThan Comparable, - * and the ordering relation on \p RandomAccessIterator's \c value_type is a strict weak ordering, as defined in the - * LessThan Comparable requirements. - * - * The following code snippet demonstrates how to use \p sort to sort - * a sequence of integers using the \p thrust::host execution policy for parallelization: - * - * \code - * #include - * #include - * ... - * const int N = 6; - * int A[N] = {1, 4, 2, 8, 5, 7}; - * thrust::sort(thrust::host, A, A + N); - * // A is now {1, 2, 4, 5, 7, 8} - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p stable_sort - * \see \p sort_by_key - */ -template -__host__ __device__ - void sort(const thrust::detail::execution_policy_base &exec, - RandomAccessIterator first, - RandomAccessIterator last); - - -/*! \p sort sorts the elements in [first, last) into - * ascending order, meaning that if \c i and \c j are any two valid - * iterators in [first, last) such that \c i precedes \c j, - * then \c *j is not less than \c *i. Note: \c sort is not guaranteed - * to be stable. That is, suppose that \c *i and \c *j are equivalent: - * neither one is less than the other. It is not guaranteed that the - * relative order of these two elements will be preserved by \p sort. - * - * This version of \p sort compares objects using \c operator<. - * - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * - * \tparam RandomAccessIterator is a model of Random Access Iterator, - * \p RandomAccessIterator is mutable, - * and \p RandomAccessIterator's \c value_type is a model of LessThan Comparable, - * and the ordering relation on \p RandomAccessIterator's \c value_type is a strict weak ordering, as defined in the - * LessThan Comparable requirements. - * - * The following code snippet demonstrates how to use \p sort to sort - * a sequence of integers. - * - * \code - * #include - * ... - * const int N = 6; - * int A[N] = {1, 4, 2, 8, 5, 7}; - * thrust::sort(A, A + N); - * // A is now {1, 2, 4, 5, 7, 8} - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p stable_sort - * \see \p sort_by_key - */ -template - void sort(RandomAccessIterator first, - RandomAccessIterator last); - - -/*! \p sort sorts the elements in [first, last) into - * ascending order, meaning that if \c i and \c j are any two valid - * iterators in [first, last) such that \c i precedes \c j, - * then \c *j is not less than \c *i. Note: \c sort is not guaranteed - * to be stable. That is, suppose that \c *i and \c *j are equivalent: - * neither one is less than the other. It is not guaranteed that the - * relative order of these two elements will be preserved by \p sort. - * - * This version of \p sort compares objects using a function object - * \p comp. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * \param comp Comparison operator. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam RandomAccessIterator is a model of Random Access Iterator, - * \p RandomAccessIterator is mutable, - * and \p RandomAccessIterator's \c value_type is convertible to \p StrictWeakOrdering's - * \c first_argument_type and \c second_argument_type. - * \tparam StrictWeakOrdering is a model of Strict Weak Ordering. - * - * The following code demonstrates how to sort integers in descending order - * using the greater comparison operator using the \p thrust::host execution policy for parallelization: - * - * \code - * #include - * #include - * #include - * ... - * const int N = 6; - * int A[N] = {1, 4, 2, 8, 5, 7}; - * thrust::sort(thrust::host, A, A + N, thrust::greater()); - * // A is now {8, 7, 5, 4, 2, 1}; - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p stable_sort - * \see \p sort_by_key - */ -template -__host__ __device__ - void sort(const thrust::detail::execution_policy_base &exec, - RandomAccessIterator first, - RandomAccessIterator last, - StrictWeakOrdering comp); - - -/*! \p sort sorts the elements in [first, last) into - * ascending order, meaning that if \c i and \c j are any two valid - * iterators in [first, last) such that \c i precedes \c j, - * then \c *j is not less than \c *i. Note: \c sort is not guaranteed - * to be stable. That is, suppose that \c *i and \c *j are equivalent: - * neither one is less than the other. It is not guaranteed that the - * relative order of these two elements will be preserved by \p sort. - * - * This version of \p sort compares objects using a function object - * \p comp. - * - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * \param comp Comparison operator. - * - * \tparam RandomAccessIterator is a model of Random Access Iterator, - * \p RandomAccessIterator is mutable, - * and \p RandomAccessIterator's \c value_type is convertible to \p StrictWeakOrdering's - * \c first_argument_type and \c second_argument_type. - * \tparam StrictWeakOrdering is a model of Strict Weak Ordering. - * - * The following code demonstrates how to sort integers in descending order - * using the greater comparison operator. - * - * \code - * #include - * #include - * ... - * const int N = 6; - * int A[N] = {1, 4, 2, 8, 5, 7}; - * thrust::sort(A, A + N, thrust::greater()); - * // A is now {8, 7, 5, 4, 2, 1}; - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p stable_sort - * \see \p sort_by_key - */ -template -__host__ __device__ - void sort(RandomAccessIterator first, - RandomAccessIterator last, - StrictWeakOrdering comp); - - -/*! \p stable_sort is much like \c sort: it sorts the elements in - * [first, last) into ascending order, meaning that if \c i - * and \c j are any two valid iterators in [first, last) such - * that \c i precedes \c j, then \c *j is not less than \c *i. - * - * As the name suggests, \p stable_sort is stable: it preserves the - * relative ordering of equivalent elements. That is, if \c x and \c y - * are elements in [first, last) such that \c x precedes \c y, - * and if the two elements are equivalent (neither x < y nor - * y < x) then a postcondition of \p stable_sort is that \c x - * still precedes \c y. - * - * This version of \p stable_sort compares objects using \c operator<. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam RandomAccessIterator is a model of Random Access Iterator, - * \p RandomAccessIterator is mutable, - * and \p RandomAccessIterator's \c value_type is a model of LessThan Comparable, - * and the ordering relation on \p RandomAccessIterator's \c value_type is a strict weak ordering, as defined in the - * LessThan Comparable requirements. - * - * The following code snippet demonstrates how to use \p sort to sort - * a sequence of integers using the \p thrust::host execution policy for parallelization: - * - * \code - * #include - * #include - * ... - * const int N = 6; - * int A[N] = {1, 4, 2, 8, 5, 7}; - * thrust::stable_sort(thrust::host, A, A + N); - * // A is now {1, 2, 4, 5, 7, 8} - * \endcode - * - * \see http://www.sgi.com/tech/stl/stable_sort.html - * \see \p sort - * \see \p stable_sort_by_key - */ -template -__host__ __device__ - void stable_sort(const thrust::detail::execution_policy_base &exec, - RandomAccessIterator first, - RandomAccessIterator last); - - -/*! \p stable_sort is much like \c sort: it sorts the elements in - * [first, last) into ascending order, meaning that if \c i - * and \c j are any two valid iterators in [first, last) such - * that \c i precedes \c j, then \c *j is not less than \c *i. - * - * As the name suggests, \p stable_sort is stable: it preserves the - * relative ordering of equivalent elements. That is, if \c x and \c y - * are elements in [first, last) such that \c x precedes \c y, - * and if the two elements are equivalent (neither x < y nor - * y < x) then a postcondition of \p stable_sort is that \c x - * still precedes \c y. - * - * This version of \p stable_sort compares objects using \c operator<. - * - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * - * \tparam RandomAccessIterator is a model of Random Access Iterator, - * \p RandomAccessIterator is mutable, - * and \p RandomAccessIterator's \c value_type is a model of LessThan Comparable, - * and the ordering relation on \p RandomAccessIterator's \c value_type is a strict weak ordering, as defined in the - * LessThan Comparable requirements. - * - * The following code snippet demonstrates how to use \p sort to sort - * a sequence of integers. - * - * \code - * #include - * ... - * const int N = 6; - * int A[N] = {1, 4, 2, 8, 5, 7}; - * thrust::stable_sort(A, A + N); - * // A is now {1, 2, 4, 5, 7, 8} - * \endcode - * - * \see http://www.sgi.com/tech/stl/stable_sort.html - * \see \p sort - * \see \p stable_sort_by_key - */ -template - void stable_sort(RandomAccessIterator first, - RandomAccessIterator last); - - -/*! \p stable_sort is much like \c sort: it sorts the elements in - * [first, last) into ascending order, meaning that if \c i - * and \c j are any two valid iterators in [first, last) such - * that \c i precedes \c j, then \c *j is not less than \c *i. - * - * As the name suggests, \p stable_sort is stable: it preserves the - * relative ordering of equivalent elements. That is, if \c x and \c y - * are elements in [first, last) such that \c x precedes \c y, - * and if the two elements are equivalent (neither x < y nor - * y < x) then a postcondition of \p stable_sort is that \c x - * still precedes \c y. - * - * This version of \p stable_sort compares objects using a function object - * \p comp. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * \param comp Comparison operator. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam RandomAccessIterator is a model of Random Access Iterator, - * \p RandomAccessIterator is mutable, - * and \p RandomAccessIterator's \c value_type is convertible to \p StrictWeakOrdering's - * \c first_argument_type and \c second_argument_type. - * \tparam StrictWeakOrdering is a model of Strict Weak Ordering. - * - * The following code demonstrates how to sort integers in descending order - * using the greater comparison operator using the \p thrust::host execution policy for parallelization: - * - * \code - * #include - * #include - * #include - * ... - * const int N = 6; - * int A[N] = {1, 4, 2, 8, 5, 7}; - * thrust::sort(A, A + N, thrust::greater()); - * // A is now {8, 7, 5, 4, 2, 1}; - * \endcode - * - * \see http://www.sgi.com/tech/stl/stable_sort.html - * \see \p sort - * \see \p stable_sort_by_key - */ -template -__host__ __device__ - void stable_sort(const thrust::detail::execution_policy_base &exec, - RandomAccessIterator first, - RandomAccessIterator last, - StrictWeakOrdering comp); - - -/*! \p stable_sort is much like \c sort: it sorts the elements in - * [first, last) into ascending order, meaning that if \c i - * and \c j are any two valid iterators in [first, last) such - * that \c i precedes \c j, then \c *j is not less than \c *i. - * - * As the name suggests, \p stable_sort is stable: it preserves the - * relative ordering of equivalent elements. That is, if \c x and \c y - * are elements in [first, last) such that \c x precedes \c y, - * and if the two elements are equivalent (neither x < y nor - * y < x) then a postcondition of \p stable_sort is that \c x - * still precedes \c y. - * - * This version of \p stable_sort compares objects using a function object - * \p comp. - * - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * \param comp Comparison operator. - * - * \tparam RandomAccessIterator is a model of Random Access Iterator, - * \p RandomAccessIterator is mutable, - * and \p RandomAccessIterator's \c value_type is convertible to \p StrictWeakOrdering's - * \c first_argument_type and \c second_argument_type. - * \tparam StrictWeakOrdering is a model of Strict Weak Ordering. - * - * The following code demonstrates how to sort integers in descending order - * using the greater comparison operator. - * - * \code - * #include - * #include - * ... - * const int N = 6; - * int A[N] = {1, 4, 2, 8, 5, 7}; - * thrust::sort(A, A + N, thrust::greater()); - * // A is now {8, 7, 5, 4, 2, 1}; - * \endcode - * - * \see http://www.sgi.com/tech/stl/stable_sort.html - * \see \p sort - * \see \p stable_sort_by_key - */ -template - void stable_sort(RandomAccessIterator first, - RandomAccessIterator last, - StrictWeakOrdering comp); - - -/////////////// -// Key Value // -/////////////// - - -/*! \p sort_by_key performs a key-value sort. That is, \p sort_by_key sorts the - * elements in [keys_first, keys_last) and [values_first, - * values_first + (keys_last - keys_first)) into ascending key order, - * meaning that if \c i and \c j are any two valid iterators in [keys_first, - * keys_last) such that \c i precedes \c j, and \c p and \c q are iterators - * in [values_first, values_first + (keys_last - keys_first)) - * corresponding to \c i and \c j respectively, then \c *j is not less than - * \c *i. - * - * Note: \c sort_by_key is not guaranteed to be stable. That is, suppose that - * \c *i and \c *j are equivalent: neither one is less than the other. It is not - * guaranteed that the relative order of these two keys or the relative - * order of their corresponding values will be preserved by \p sort_by_key. - * - * This version of \p sort_by_key compares key objects using \c operator<. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param keys_first The beginning of the key sequence. - * \param keys_last The end of the key sequence. - * \param values_first The beginning of the value sequence. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam RandomAccessIterator1 is a model of Random Access Iterator, - * \p RandomAccessIterator1 is mutable, - * and \p RandomAccessIterator1's \c value_type is a model of LessThan Comparable, - * and the ordering relation on \p RandomAccessIterator1's \c value_type is a strict weak ordering, as defined in the - * LessThan Comparable requirements. - * \tparam RandomAccessIterator2 is a model of Random Access Iterator, - * and \p RandomAccessIterator2 is mutable. - * - * \pre The range [keys_first, keys_last)) shall not overlap the range [values_first, values_first + (keys_last - keys_first)). - * - * The following code snippet demonstrates how to use \p sort_by_key to sort - * an array of character values using integers as sorting keys using the \p thrust::host execution policy - * for parallelization: - * - * \code - * #include - * #include - * ... - * const int N = 6; - * int keys[N] = { 1, 4, 2, 8, 5, 7}; - * char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'}; - * thrust::sort_by_key(thrust::host, keys, keys + N, values); - * // keys is now { 1, 2, 4, 5, 7, 8} - * // values is now {'a', 'c', 'b', 'e', 'f', 'd'} - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p stable_sort_by_key - * \see \p sort - */ -template -__host__ __device__ - void sort_by_key(const thrust::detail::execution_policy_base &exec, - RandomAccessIterator1 keys_first, - RandomAccessIterator1 keys_last, - RandomAccessIterator2 values_first); - - -/*! \p sort_by_key performs a key-value sort. That is, \p sort_by_key sorts the - * elements in [keys_first, keys_last) and [values_first, - * values_first + (keys_last - keys_first)) into ascending key order, - * meaning that if \c i and \c j are any two valid iterators in [keys_first, - * keys_last) such that \c i precedes \c j, and \c p and \c q are iterators - * in [values_first, values_first + (keys_last - keys_first)) - * corresponding to \c i and \c j respectively, then \c *j is not less than - * \c *i. - * - * Note: \c sort_by_key is not guaranteed to be stable. That is, suppose that - * \c *i and \c *j are equivalent: neither one is less than the other. It is not - * guaranteed that the relative order of these two keys or the relative - * order of their corresponding values will be preserved by \p sort_by_key. - * - * This version of \p sort_by_key compares key objects using \c operator<. - * - * \param keys_first The beginning of the key sequence. - * \param keys_last The end of the key sequence. - * \param values_first The beginning of the value sequence. - * - * \tparam RandomAccessIterator1 is a model of Random Access Iterator, - * \p RandomAccessIterator1 is mutable, - * and \p RandomAccessIterator1's \c value_type is a model of LessThan Comparable, - * and the ordering relation on \p RandomAccessIterator1's \c value_type is a strict weak ordering, as defined in the - * LessThan Comparable requirements. - * \tparam RandomAccessIterator2 is a model of Random Access Iterator, - * and \p RandomAccessIterator2 is mutable. - * - * \pre The range [keys_first, keys_last)) shall not overlap the range [values_first, values_first + (keys_last - keys_first)). - * - * The following code snippet demonstrates how to use \p sort_by_key to sort - * an array of character values using integers as sorting keys. - * - * \code - * #include - * ... - * const int N = 6; - * int keys[N] = { 1, 4, 2, 8, 5, 7}; - * char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'}; - * thrust::sort_by_key(keys, keys + N, values); - * // keys is now { 1, 2, 4, 5, 7, 8} - * // values is now {'a', 'c', 'b', 'e', 'f', 'd'} - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p stable_sort_by_key - * \see \p sort - */ -template - void sort_by_key(RandomAccessIterator1 keys_first, - RandomAccessIterator1 keys_last, - RandomAccessIterator2 values_first); - - -/*! \p sort_by_key performs a key-value sort. That is, \p sort_by_key sorts the - * elements in [keys_first, keys_last) and [values_first, - * values_first + (keys_last - keys_first)) into ascending key order, - * meaning that if \c i and \c j are any two valid iterators in [keys_first, - * keys_last) such that \c i precedes \c j, and \c p and \c q are iterators - * in [values_first, values_first + (keys_last - keys_first)) - * corresponding to \c i and \c j respectively, then \c *j is not less than - * \c *i. - * - * Note: \c sort_by_key is not guaranteed to be stable. That is, suppose that - * \c *i and \c *j are equivalent: neither one is less than the other. It is not - * guaranteed that the relative order of these two keys or the relative - * order of their corresponding values will be preserved by \p sort_by_key. - * - * This version of \p sort_by_key compares key objects using a function object - * \c comp. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param keys_first The beginning of the key sequence. - * \param keys_last The end of the key sequence. - * \param values_first The beginning of the value sequence. - * \param comp Comparison operator. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam RandomAccessIterator1 is a model of Random Access Iterator, - * \p RandomAccessIterator1 is mutable, - * and \p RandomAccessIterator1's \c value_type is convertible to \p StrictWeakOrdering's - * \c first_argument_type and \c second_argument_type. - * \tparam RandomAccessIterator2 is a model of Random Access Iterator, - * and \p RandomAccessIterator2 is mutable. - * \tparam StrictWeakOrdering is a model of Strict Weak Ordering. - * - * \pre The range [keys_first, keys_last)) shall not overlap the range [values_first, values_first + (keys_last - keys_first)). - * - * The following code snippet demonstrates how to use \p sort_by_key to sort - * an array of character values using integers as sorting keys using the \p thrust::host execution policy - * for parallelization.The keys are sorted in descending order using the greater comparison operator. - * - * \code - * #include - * #include - * ... - * const int N = 6; - * int keys[N] = { 1, 4, 2, 8, 5, 7}; - * char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'}; - * thrust::sort_by_key(thrust::host, keys, keys + N, values, thrust::greater()); - * // keys is now { 8, 7, 5, 4, 2, 1} - * // values is now {'d', 'f', 'e', 'b', 'c', 'a'} - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p stable_sort_by_key - * \see \p sort - */ -template -__host__ __device__ - void sort_by_key(const thrust::detail::execution_policy_base &exec, - RandomAccessIterator1 keys_first, - RandomAccessIterator1 keys_last, - RandomAccessIterator2 values_first, - StrictWeakOrdering comp); - - -/*! \p sort_by_key performs a key-value sort. That is, \p sort_by_key sorts the - * elements in [keys_first, keys_last) and [values_first, - * values_first + (keys_last - keys_first)) into ascending key order, - * meaning that if \c i and \c j are any two valid iterators in [keys_first, - * keys_last) such that \c i precedes \c j, and \c p and \c q are iterators - * in [values_first, values_first + (keys_last - keys_first)) - * corresponding to \c i and \c j respectively, then \c *j is not less than - * \c *i. - * - * Note: \c sort_by_key is not guaranteed to be stable. That is, suppose that - * \c *i and \c *j are equivalent: neither one is less than the other. It is not - * guaranteed that the relative order of these two keys or the relative - * order of their corresponding values will be preserved by \p sort_by_key. - * - * This version of \p sort_by_key compares key objects using a function object - * \c comp. - * - * \param keys_first The beginning of the key sequence. - * \param keys_last The end of the key sequence. - * \param values_first The beginning of the value sequence. - * \param comp Comparison operator. - * - * \tparam RandomAccessIterator1 is a model of Random Access Iterator, - * \p RandomAccessIterator1 is mutable, - * and \p RandomAccessIterator1's \c value_type is convertible to \p StrictWeakOrdering's - * \c first_argument_type and \c second_argument_type. - * \tparam RandomAccessIterator2 is a model of Random Access Iterator, - * and \p RandomAccessIterator2 is mutable. - * \tparam StrictWeakOrdering is a model of Strict Weak Ordering. - * - * \pre The range [keys_first, keys_last)) shall not overlap the range [values_first, values_first + (keys_last - keys_first)). - * - * The following code snippet demonstrates how to use \p sort_by_key to sort - * an array of character values using integers as sorting keys. The keys - * are sorted in descending order using the greater comparison operator. - * - * \code - * #include - * ... - * const int N = 6; - * int keys[N] = { 1, 4, 2, 8, 5, 7}; - * char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'}; - * thrust::sort_by_key(keys, keys + N, values, thrust::greater()); - * // keys is now { 8, 7, 5, 4, 2, 1} - * // values is now {'d', 'f', 'e', 'b', 'c', 'a'} - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p stable_sort_by_key - * \see \p sort - */ -template - void sort_by_key(RandomAccessIterator1 keys_first, - RandomAccessIterator1 keys_last, - RandomAccessIterator2 values_first, - StrictWeakOrdering comp); - - -/*! \p stable_sort_by_key performs a key-value sort. That is, \p stable_sort_by_key - * sorts the elements in [keys_first, keys_last) and [values_first, - * values_first + (keys_last - keys_first)) into ascending key order, - * meaning that if \c i and \c j are any two valid iterators in [keys_first, - * keys_last) such that \c i precedes \c j, and \c p and \c q are iterators - * in [values_first, values_first + (keys_last - keys_first)) - * corresponding to \c i and \c j respectively, then \c *j is not less than - * \c *i. - * - * As the name suggests, \p stable_sort_by_key is stable: it preserves the - * relative ordering of equivalent elements. That is, if \c x and \c y - * are elements in [keys_first, keys_last) such that \c x precedes \c y, - * and if the two elements are equivalent (neither x < y nor - * y < x) then a postcondition of \p stable_sort_by_key is that \c x - * still precedes \c y. - * - * This version of \p stable_sort_by_key compares key objects using \c operator<. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param keys_first The beginning of the key sequence. - * \param keys_last The end of the key sequence. - * \param values_first The beginning of the value sequence. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam RandomAccessIterator1 is a model of Random Access Iterator, - * \p RandomAccessIterator1 is mutable, - * and \p RandomAccessIterator1's \c value_type is a model of LessThan Comparable, - * and the ordering relation on \p RandomAccessIterator1's \c value_type is a strict weak ordering, as defined in the - * LessThan Comparable requirements. - * \tparam RandomAccessIterator2 is a model of Random Access Iterator, - * and \p RandomAccessIterator2 is mutable. - * - * \pre The range [keys_first, keys_last)) shall not overlap the range [values_first, values_first + (keys_last - keys_first)). - * - * The following code snippet demonstrates how to use \p stable_sort_by_key to sort - * an array of characters using integers as sorting keys using the \p thrust::host execution policy for - * parallelization: - * - * \code - * #include - * #include - * ... - * const int N = 6; - * int keys[N] = { 1, 4, 2, 8, 5, 7}; - * char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'}; - * thrust::stable_sort_by_key(thrust::host, keys, keys + N, values); - * // keys is now { 1, 2, 4, 5, 7, 8} - * // values is now {'a', 'c', 'b', 'e', 'f', 'd'} - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p sort_by_key - * \see \p stable_sort - */ -template -__host__ __device__ - void stable_sort_by_key(const thrust::detail::execution_policy_base &exec, - RandomAccessIterator1 keys_first, - RandomAccessIterator1 keys_last, - RandomAccessIterator2 values_first); - - -/*! \p stable_sort_by_key performs a key-value sort. That is, \p stable_sort_by_key - * sorts the elements in [keys_first, keys_last) and [values_first, - * values_first + (keys_last - keys_first)) into ascending key order, - * meaning that if \c i and \c j are any two valid iterators in [keys_first, - * keys_last) such that \c i precedes \c j, and \c p and \c q are iterators - * in [values_first, values_first + (keys_last - keys_first)) - * corresponding to \c i and \c j respectively, then \c *j is not less than - * \c *i. - * - * As the name suggests, \p stable_sort_by_key is stable: it preserves the - * relative ordering of equivalent elements. That is, if \c x and \c y - * are elements in [keys_first, keys_last) such that \c x precedes \c y, - * and if the two elements are equivalent (neither x < y nor - * y < x) then a postcondition of \p stable_sort_by_key is that \c x - * still precedes \c y. - * - * This version of \p stable_sort_by_key compares key objects using \c operator<. - * - * \param keys_first The beginning of the key sequence. - * \param keys_last The end of the key sequence. - * \param values_first The beginning of the value sequence. - * - * \tparam RandomAccessIterator1 is a model of Random Access Iterator, - * \p RandomAccessIterator1 is mutable, - * and \p RandomAccessIterator1's \c value_type is a model of LessThan Comparable, - * and the ordering relation on \p RandomAccessIterator1's \c value_type is a strict weak ordering, as defined in the - * LessThan Comparable requirements. - * \tparam RandomAccessIterator2 is a model of Random Access Iterator, - * and \p RandomAccessIterator2 is mutable. - * - * \pre The range [keys_first, keys_last)) shall not overlap the range [values_first, values_first + (keys_last - keys_first)). - * - * The following code snippet demonstrates how to use \p stable_sort_by_key to sort - * an array of characters using integers as sorting keys. - * - * \code - * #include - * ... - * const int N = 6; - * int keys[N] = { 1, 4, 2, 8, 5, 7}; - * char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'}; - * thrust::stable_sort_by_key(keys, keys + N, values); - * // keys is now { 1, 2, 4, 5, 7, 8} - * // values is now {'a', 'c', 'b', 'e', 'f', 'd'} - * \endcode - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p sort_by_key - * \see \p stable_sort - */ -template - void stable_sort_by_key(RandomAccessIterator1 keys_first, - RandomAccessIterator1 keys_last, - RandomAccessIterator2 values_first); - - -/*! \p stable_sort_by_key performs a key-value sort. That is, \p stable_sort_by_key - * sorts the elements in [keys_first, keys_last) and [values_first, - * values_first + (keys_last - keys_first)) into ascending key order, - * meaning that if \c i and \c j are any two valid iterators in [keys_first, - * keys_last) such that \c i precedes \c j, and \c p and \c q are iterators - * in [values_first, values_first + (keys_last - keys_first)) - * corresponding to \c i and \c j respectively, then \c *j is not less than - * \c *i. - * - * As the name suggests, \p stable_sort_by_key is stable: it preserves the - * relative ordering of equivalent elements. That is, if \c x and \c y - * are elements in [keys_first, keys_last) such that \c x precedes \c y, - * and if the two elements are equivalent (neither x < y nor - * y < x) then a postcondition of \p stable_sort_by_key is that \c x - * still precedes \c y. - * - * This version of \p stable_sort_by_key compares key objects using the function - * object \p comp. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param keys_first The beginning of the key sequence. - * \param keys_last The end of the key sequence. - * \param values_first The beginning of the value sequence. - * \param comp Comparison operator. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam RandomAccessIterator1 is a model of Random Access Iterator, - * \p RandomAccessIterator1 is mutable, - * and \p RandomAccessIterator1's \c value_type is convertible to \p StrictWeakOrdering's - * \c first_argument_type and \c second_argument_type. - * \tparam RandomAccessIterator2 is a model of Random Access Iterator, - * and \p RandomAccessIterator2 is mutable. - * \tparam StrictWeakOrdering is a model of Strict Weak Ordering. - * - * \pre The range [keys_first, keys_last)) shall not overlap the range [values_first, values_first + (keys_last - keys_first)). - * - * The following code snippet demonstrates how to use \p sort_by_key to sort - * an array of character values using integers as sorting keys using the \p thrust::host execution policy for - * parallelization. The keys are sorted in descending order using the greater comparison operator. - * - * \code - * #include - * #include - * ... - * const int N = 6; - * int keys[N] = { 1, 4, 2, 8, 5, 7}; - * char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'}; - * thrust::stable_sort_by_key(thrust::host, keys, keys + N, values, thrust::greater()); - * // keys is now { 8, 7, 5, 4, 2, 1} - * // values is now {'d', 'f', 'e', 'b', 'c', 'a'} - * \endcode - * - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p sort_by_key - * \see \p stable_sort - */ -template -__host__ __device__ - void stable_sort_by_key(const thrust::detail::execution_policy_base &exec, - RandomAccessIterator1 keys_first, - RandomAccessIterator1 keys_last, - RandomAccessIterator2 values_first, - StrictWeakOrdering comp); - - -/*! \p stable_sort_by_key performs a key-value sort. That is, \p stable_sort_by_key - * sorts the elements in [keys_first, keys_last) and [values_first, - * values_first + (keys_last - keys_first)) into ascending key order, - * meaning that if \c i and \c j are any two valid iterators in [keys_first, - * keys_last) such that \c i precedes \c j, and \c p and \c q are iterators - * in [values_first, values_first + (keys_last - keys_first)) - * corresponding to \c i and \c j respectively, then \c *j is not less than - * \c *i. - * - * As the name suggests, \p stable_sort_by_key is stable: it preserves the - * relative ordering of equivalent elements. That is, if \c x and \c y - * are elements in [keys_first, keys_last) such that \c x precedes \c y, - * and if the two elements are equivalent (neither x < y nor - * y < x) then a postcondition of \p stable_sort_by_key is that \c x - * still precedes \c y. - * - * This version of \p stable_sort_by_key compares key objects using the function - * object \p comp. - * - * \param keys_first The beginning of the key sequence. - * \param keys_last The end of the key sequence. - * \param values_first The beginning of the value sequence. - * \param comp Comparison operator. - * - * \tparam RandomAccessIterator1 is a model of Random Access Iterator, - * \p RandomAccessIterator1 is mutable, - * and \p RandomAccessIterator1's \c value_type is convertible to \p StrictWeakOrdering's - * \c first_argument_type and \c second_argument_type. - * \tparam RandomAccessIterator2 is a model of Random Access Iterator, - * and \p RandomAccessIterator2 is mutable. - * \tparam StrictWeakOrdering is a model of Strict Weak Ordering. - * - * \pre The range [keys_first, keys_last)) shall not overlap the range [values_first, values_first + (keys_last - keys_first)). - * - * The following code snippet demonstrates how to use \p sort_by_key to sort - * an array of character values using integers as sorting keys. The keys - * are sorted in descending order using the greater comparison operator. - * - * \code - * #include - * ... - * const int N = 6; - * int keys[N] = { 1, 4, 2, 8, 5, 7}; - * char values[N] = {'a', 'b', 'c', 'd', 'e', 'f'}; - * thrust::stable_sort_by_key(keys, keys + N, values, thrust::greater()); - * // keys is now { 8, 7, 5, 4, 2, 1} - * // values is now {'d', 'f', 'e', 'b', 'c', 'a'} - * \endcode - * - * - * \see http://www.sgi.com/tech/stl/sort.html - * \see \p sort_by_key - * \see \p stable_sort - */ -template - void stable_sort_by_key(RandomAccessIterator1 keys_first, - RandomAccessIterator1 keys_last, - RandomAccessIterator2 values_first, - StrictWeakOrdering comp); - - -/*! \} // end sorting - */ - - -/*! \addtogroup reductions - * \{ - * \addtogroup predicates - * \{ - */ - - -/*! \p is_sorted returns \c true if the range [first, last) is - * sorted in ascending order, and \c false otherwise. - * - * Specifically, this version of \p is_sorted returns \c false if for - * some iterator \c i in the range [first, last - 1) the - * expression *(i + 1) < *i is \c true. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * \return \c true, if the sequence is sorted; \c false, otherwise. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam ForwardIterator is a model of Forward Iterator, - * \p ForwardIterator's \c value_type is a model of LessThan Comparable, - * and the ordering on objects of \p ForwardIterator's \c value_type is a strict weak ordering, as defined - * in the LessThan Comparable requirements. - * - * - * The following code demonstrates how to use \p is_sorted to test whether the - * contents of a \c device_vector are stored in ascending order using the \p thrust::device execution policy - * for parallelization: - * - * \code - * #include - * #include - * #include - * #include - * ... - * thrust::device_vector v(6); - * v[0] = 1; - * v[1] = 4; - * v[2] = 2; - * v[3] = 8; - * v[4] = 5; - * v[5] = 7; - * - * bool result = thrust::is_sorted(thrust::device, v.begin(), v.end()); - * - * // result == false - * - * thrust::sort(v.begin(), v.end()); - * result = thrust::is_sorted(thrust::device, v.begin(), v.end()); - * - * // result == true - * \endcode - * - * \see http://www.sgi.com/tech/stl/is_sorted.html - * \see is_sorted_until - * \see \c sort - * \see \c stable_sort - * \see \c less - */ -template -__host__ __device__ - bool is_sorted(const thrust::detail::execution_policy_base &exec, - ForwardIterator first, - ForwardIterator last); - - -/*! \p is_sorted returns \c true if the range [first, last) is - * sorted in ascending order, and \c false otherwise. - * - * Specifically, this version of \p is_sorted returns \c false if for - * some iterator \c i in the range [first, last - 1) the - * expression *(i + 1) < *i is \c true. - * - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * \return \c true, if the sequence is sorted; \c false, otherwise. - * - * \tparam ForwardIterator is a model of Forward Iterator, - * \p ForwardIterator's \c value_type is a model of LessThan Comparable, - * and the ordering on objects of \p ForwardIterator's \c value_type is a strict weak ordering, as defined - * in the LessThan Comparable requirements. - * - * - * The following code demonstrates how to use \p is_sorted to test whether the - * contents of a \c device_vector are stored in ascending order. - * - * \code - * #include - * #include - * #include - * ... - * thrust::device_vector v(6); - * v[0] = 1; - * v[1] = 4; - * v[2] = 2; - * v[3] = 8; - * v[4] = 5; - * v[5] = 7; - * - * bool result = thrust::is_sorted(v.begin(), v.end()); - * - * // result == false - * - * thrust::sort(v.begin(), v.end()); - * result = thrust::is_sorted(v.begin(), v.end()); - * - * // result == true - * \endcode - * - * \see http://www.sgi.com/tech/stl/is_sorted.html - * \see is_sorted_until - * \see \c sort - * \see \c stable_sort - * \see \c less - */ -template - bool is_sorted(ForwardIterator first, - ForwardIterator last); - - -/*! \p is_sorted returns \c true if the range [first, last) is sorted in ascending - * order accoring to a user-defined comparison operation, and \c false otherwise. - * - * Specifically, this version of \p is_sorted returns \c false if for some iterator \c i in - * the range [first, last - 1) the expression comp(*(i + 1), *i) is \c true. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * \param comp Comparison operator. - * \return \c true, if the sequence is sorted according to comp; \c false, otherwise. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam ForwardIterator is a model of Forward Iterator, - * and \p ForwardIterator's \c value_type is convertible to both \c StrictWeakOrdering's \c first_argument_type - * and \c second_argument_type. - * \tparam Compare is a model of Strict Weak Ordering. - * - * The following code snippet demonstrates how to use \p is_sorted to test whether the - * contents of a \c device_vector are stored in descending order using the \p thrust::device execution - * policy for parallelization: - * - * \code - * #include - * #include - * #include - * #include - * ... - * thrust::device_vector v(6); - * v[0] = 1; - * v[1] = 4; - * v[2] = 2; - * v[3] = 8; - * v[4] = 5; - * v[5] = 7; - * - * thrust::greater comp; - * bool result = thrust::is_sorted(thrust::device, v.begin(), v.end(), comp); - * - * // result == false - * - * thrust::sort(v.begin(), v.end(), comp); - * result = thrust::is_sorted(thrust::device, v.begin(), v.end(), comp); - * - * // result == true - * \endcode - * - * \see http://www.sgi.com/tech/stl/is_sorted.html - * \see \c sort - * \see \c stable_sort - * \see \c less - */ -template -__host__ __device__ - bool is_sorted(const thrust::detail::execution_policy_base &exec, - ForwardIterator first, - ForwardIterator last, - Compare comp); - - -/*! \p is_sorted returns \c true if the range [first, last) is sorted in ascending - * order accoring to a user-defined comparison operation, and \c false otherwise. - * - * Specifically, this version of \p is_sorted returns \c false if for some iterator \c i in - * the range [first, last - 1) the expression comp(*(i + 1), *i) is \c true. - * - * \param first The beginning of the sequence. - * \param last The end of the sequence. - * \param comp Comparison operator. - * \return \c true, if the sequence is sorted according to comp; \c false, otherwise. - * - * \tparam ForwardIterator is a model of Forward Iterator, - * and \p ForwardIterator's \c value_type is convertible to both \c StrictWeakOrdering's \c first_argument_type - * and \c second_argument_type. - * \tparam Compare is a model of Strict Weak Ordering. - * - * The following code snippet demonstrates how to use \p is_sorted to test whether the - * contents of a \c device_vector are stored in descending order. - * - * \code - * #include - * #include - * #include - * ... - * thrust::device_vector v(6); - * v[0] = 1; - * v[1] = 4; - * v[2] = 2; - * v[3] = 8; - * v[4] = 5; - * v[5] = 7; - * - * thrust::greater comp; - * bool result = thrust::is_sorted(v.begin(), v.end(), comp); - * - * // result == false - * - * thrust::sort(v.begin(), v.end(), comp); - * result = thrust::is_sorted(v.begin(), v.end(), comp); - * - * // result == true - * \endcode - * - * \see http://www.sgi.com/tech/stl/is_sorted.html - * \see \c sort - * \see \c stable_sort - * \see \c less - */ -template - bool is_sorted(ForwardIterator first, - ForwardIterator last, - Compare comp); - - -/*! This version of \p is_sorted_until returns the last iterator \c i in [first,last] for - * which the range [first,last) is sorted using \c operator<. If distance(first,last) < 2, - * \p is_sorted_until simply returns \p last. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization. - * \param first The beginning of the range of interest. - * \param last The end of the range of interest. - * \return The last iterator in the input range for which it is sorted. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam ForwardIterator is a model of Forward Iterator and - * \p ForwardIterator's \c value_type is a model of LessThan Comparable. - * - * The following code snippet demonstrates how to use \p is_sorted_until to find the first position - * in an array where the data becomes unsorted using the \p thrust::host execution policy for - * parallelization: - * - * \code - * #include - * #include - * - * ... - * - * int A[8] = {0, 1, 2, 3, 0, 1, 2, 3}; - * - * int * B = thrust::is_sorted_until(thrust::host, A, A + 8); - * - * // B - A is 4 - * // [A, B) is sorted - * \endcode - * - * \see \p is_sorted - * \see \p sort - * \see \p sort_by_key - * \see \p stable_sort - * \see \p stable_sort_by_key - */ -template -__host__ __device__ - ForwardIterator is_sorted_until(const thrust::detail::execution_policy_base &exec, - ForwardIterator first, - ForwardIterator last); - - -/*! This version of \p is_sorted_until returns the last iterator \c i in [first,last] for - * which the range [first,last) is sorted using \c operator<. If distance(first,last) < 2, - * \p is_sorted_until simply returns \p last. - * - * \param first The beginning of the range of interest. - * \param last The end of the range of interest. - * \return The last iterator in the input range for which it is sorted. - * - * \tparam ForwardIterator is a model of Forward Iterator and - * \p ForwardIterator's \c value_type is a model of LessThan Comparable. - * - * The following code snippet demonstrates how to use \p is_sorted_until to find the first position - * in an array where the data becomes unsorted: - * - * \code - * #include - * - * ... - * - * int A[8] = {0, 1, 2, 3, 0, 1, 2, 3}; - * - * int * B = thrust::is_sorted_until(A, A + 8); - * - * // B - A is 4 - * // [A, B) is sorted - * \endcode - * - * \see \p is_sorted - * \see \p sort - * \see \p sort_by_key - * \see \p stable_sort - * \see \p stable_sort_by_key - */ -template - ForwardIterator is_sorted_until(ForwardIterator first, - ForwardIterator last); - - -/*! This version of \p is_sorted_until returns the last iterator \c i in [first,last] for - * which the range [first,last) is sorted using the function object \c comp. If distance(first,last) < 2, - * \p is_sorted_until simply returns \p last. - * - * The algorithm's execution is parallelized as determined by \p exec. - * - * \param exec The execution policy to use for parallelization: - * \param first The beginning of the range of interest. - * \param last The end of the range of interest. - * \param comp The function object to use for comparison. - * \return The last iterator in the input range for which it is sorted. - * - * \tparam DerivedPolicy The name of the derived execution policy. - * \tparam ForwardIterator is a model of Forward Iterator and - * \p ForwardIterator's \c value_type is convertible to \p Compare's \c argument_type. - * \tparam Compare is a model of Strict Weak Ordering. - * - * The following code snippet demonstrates how to use \p is_sorted_until to find the first position - * in an array where the data becomes unsorted in descending order using the \p thrust::host execution - * policy for parallelization: - * - * \code - * #include - * #include - * #include - * - * ... - * - * int A[8] = {3, 2, 1, 0, 3, 2, 1, 0}; - * - * thrust::greater comp; - * int * B = thrust::is_sorted_until(thrust::host, A, A + 8, comp); - * - * // B - A is 4 - * // [A, B) is sorted in descending order - * \endcode - * - * \see \p is_sorted - * \see \p sort - * \see \p sort_by_key - * \see \p stable_sort - * \see \p stable_sort_by_key - */ -template -__host__ __device__ - ForwardIterator is_sorted_until(const thrust::detail::execution_policy_base &exec, - ForwardIterator first, - ForwardIterator last, - Compare comp); - - -/*! This version of \p is_sorted_until returns the last iterator \c i in [first,last] for - * which the range [first,last) is sorted using the function object \c comp. If distance(first,last) < 2, - * \p is_sorted_until simply returns \p last. - * - * \param first The beginning of the range of interest. - * \param last The end of the range of interest. - * \param comp The function object to use for comparison. - * \return The last iterator in the input range for which it is sorted. - * - * \tparam ForwardIterator is a model of Forward Iterator and - * \p ForwardIterator's \c value_type is convertible to \p Compare's \c argument_type. - * \tparam Compare is a model of Strict Weak Ordering. - * - * The following code snippet demonstrates how to use \p is_sorted_until to find the first position - * in an array where the data becomes unsorted in descending order: - * - * \code - * #include - * #include - * - * ... - * - * int A[8] = {3, 2, 1, 0, 3, 2, 1, 0}; - * - * thrust::greater comp; - * int * B = thrust::is_sorted_until(A, A + 8, comp); - * - * // B - A is 4 - * // [A, B) is sorted in descending order - * \endcode - * - * \see \p is_sorted - * \see \p sort - * \see \p sort_by_key - * \see \p stable_sort - * \see \p stable_sort_by_key - */ -template - ForwardIterator is_sorted_until(ForwardIterator first, - ForwardIterator last, - Compare comp); - - -/*! \} // end predicates - * \} // end reductions - */ - - -} // end namespace thrust - -#include - diff --git a/spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/gather.h b/spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/gather.h deleted file mode 100644 index 098e0f4fbad4001632ed02ee9e9b39aa17e54ea0..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/gather.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -// this system inherits gather -#include - diff --git a/spaces/CVPR/LIVE/thrust/thrust/type_traits/integer_sequence.h b/spaces/CVPR/LIVE/thrust/thrust/type_traits/integer_sequence.h deleted file mode 100644 index e28e4f95c03c38ab5b0f34edccce42625f7e7b8e..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/type_traits/integer_sequence.h +++ /dev/null @@ -1,262 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// Copyright (c) 2018 NVIDIA Corporation -// Copyright (c) 2015-2018 Bryce Adelstein Lelbach aka wash -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -/////////////////////////////////////////////////////////////////////////////// - -/*! \file integer_sequence.h - * \brief C++14's \c integer_sequence and associated helper aliases plus some - * extensions. - */ - -#pragma once - -#include -#include - -#if THRUST_CPP_DIALECT >= 2011 - -#include -#include -#include -#include - -namespace thrust -{ - -#if THRUST_CPP_DIALECT >= 2014 - -// A compile-time sequence of integral constants of type T. -template -using integer_sequence = std::integer_sequence; - -// A compile-time sequence of std::size_t constants. -template -using index_sequence = std::index_sequence; - -// Create a new integer_sequence with elements 0, 1, 2, ..., N - 1. -template -using make_integer_sequence = std::make_integer_sequence; - -// Create a new index_sequence with elements 0, 1, 2, ..., N - 1. -template -using make_index_sequence = std::make_index_sequence; - -/////////////////////////////////////////////////////////////////////////////// - -#else // Older than C++14. - -// A compile-time sequence of integral constants of type T. -template -struct integer_sequence; - -// A compile-time sequence of std::size_t constants. -template -using index_sequence = integer_sequence; - -/////////////////////////////////////////////////////////////////////////////// - -namespace detail -{ - -// Create a new integer_sequence containing the elements of Sequence0 followed -// by the elements of Sequence1. Sequence0::size() is added to each element from -// Sequence1 in the new sequence. -template - struct merge_and_renumber_integer_sequences_impl; -template - using merge_and_renumber_integer_sequences = - typename merge_and_renumber_integer_sequences_impl< - Sequence0, Sequence1 - >::type; - -// Create a new integer_sequence with elements 0, 1, 2, ..., N - 1. -template - struct make_integer_sequence_impl; - - -} // namespace detail - -/////////////////////////////////////////////////////////////////////////////// - -// Create a new integer_sequence with elements 0, 1, 2, ..., N - 1. -template -using make_integer_sequence = - typename detail::make_integer_sequence_impl::type; - -// Create a new index_sequence with elements 0, 1, 2, ..., N - 1. -template -using make_index_sequence = - make_integer_sequence; - -/////////////////////////////////////////////////////////////////////////////// - -template -struct integer_sequence -{ - using type = integer_sequence; - using value_type = T; - using size_type = std::size_t; - - __host__ __device__ - static constexpr size_type size() noexcept - { - return sizeof...(Is); - } -}; -/////////////////////////////////////////////////////////////////////////////// - -namespace detail -{ - -template -struct merge_and_renumber_integer_sequences_impl< - integer_sequence, integer_sequence -> -{ - using type = integer_sequence; -}; - -/////////////////////////////////////////////////////////////////////////////// - -template -struct make_integer_sequence_impl -{ - using type = merge_and_renumber_integer_sequences< - make_integer_sequence - , make_integer_sequence - >; -}; - -template -struct make_integer_sequence_impl -{ - using type = integer_sequence; -}; - -template -struct make_integer_sequence_impl -{ - using type = integer_sequence; -}; - -} // namespace detail - -#endif // THRUST_CPP_DIALECT >= 2014 - -/////////////////////////////////////////////////////////////////////////////// - -namespace detail -{ - -// Create a new integer_sequence containing the elements of Sequence0 followed -// by the elements of Sequence1. Sequence1::size() is added to each element from -// Sequence0 in the new sequence. -template - struct merge_and_renumber_reversed_integer_sequences_impl; -template - using merge_and_renumber_reversed_integer_sequences = - typename merge_and_renumber_reversed_integer_sequences_impl< - Sequence0, Sequence1 - >::type; - -// Create a new integer_sequence with elements N - 1, N - 2, N - 3, ..., 0. -template -struct make_reversed_integer_sequence_impl; - -// Add a new element to the front of an integer_sequence<>. -template -struct integer_sequence_push_front_impl; - -// Add a new element to the back of an integer_sequence<>. -template -struct integer_sequence_push_back_impl; - -} - -/////////////////////////////////////////////////////////////////////////////// - -// Create a new integer_sequence with elements N - 1, N - 2, N - 3, ..., 0. -template -using make_reversed_integer_sequence = - typename detail::make_reversed_integer_sequence_impl::type; - -// Create a new index_sequence with elements N - 1, N - 2, N - 3, ..., 0. -template -using make_reversed_index_sequence = - make_reversed_integer_sequence; - -// Add a new element to the front of an integer_sequence<>. -template -using integer_sequence_push_front = - typename detail::integer_sequence_push_front_impl::type; - -// Add a new element to the back of an integer_sequence<>. -template -using integer_sequence_push_back = - typename detail::integer_sequence_push_back_impl::type; - -/////////////////////////////////////////////////////////////////////////////// - -namespace detail -{ - -template -struct merge_and_renumber_reversed_integer_sequences_impl< - integer_sequence, integer_sequence -> -{ - using type = integer_sequence; -}; - -/////////////////////////////////////////////////////////////////////////////// - -template -struct make_reversed_integer_sequence_impl -{ - using type = merge_and_renumber_reversed_integer_sequences< - make_reversed_integer_sequence - , make_reversed_integer_sequence - >; -}; - -/////////////////////////////////////////////////////////////////////////////// - -template -struct make_reversed_integer_sequence_impl -{ - using type = integer_sequence; -}; - -template -struct make_reversed_integer_sequence_impl -{ - using type = integer_sequence; -}; - -/////////////////////////////////////////////////////////////////////////////// - -template -struct integer_sequence_push_front_impl > -{ - using type = integer_sequence; -}; - -/////////////////////////////////////////////////////////////////////////////// - -template -struct integer_sequence_push_back_impl > -{ - using type = integer_sequence; -}; - -/////////////////////////////////////////////////////////////////////////////// - -} // namespace detail - -} // end namespace thrust - -#endif // THRUST_CPP_DIALECT >= 2011 - diff --git a/spaces/CVPR/lama-example/models/ade20k/segm_lib/nn/modules/comm.py b/spaces/CVPR/lama-example/models/ade20k/segm_lib/nn/modules/comm.py deleted file mode 100644 index b64bf6ba3b3e7abbab375c6dd4a87d8239e62138..0000000000000000000000000000000000000000 --- a/spaces/CVPR/lama-example/models/ade20k/segm_lib/nn/modules/comm.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: utf-8 -*- -# File : comm.py -# Author : Jiayuan Mao -# Email : maojiayuan@gmail.com -# Date : 27/01/2018 -# -# This file is part of Synchronized-BatchNorm-PyTorch. -# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch -# Distributed under MIT License. - -import queue -import collections -import threading - -__all__ = ['FutureResult', 'SlavePipe', 'SyncMaster'] - - -class FutureResult(object): - """A thread-safe future implementation. Used only as one-to-one pipe.""" - - def __init__(self): - self._result = None - self._lock = threading.Lock() - self._cond = threading.Condition(self._lock) - - def put(self, result): - with self._lock: - assert self._result is None, 'Previous result has\'t been fetched.' - self._result = result - self._cond.notify() - - def get(self): - with self._lock: - if self._result is None: - self._cond.wait() - - res = self._result - self._result = None - return res - - -_MasterRegistry = collections.namedtuple('MasterRegistry', ['result']) -_SlavePipeBase = collections.namedtuple('_SlavePipeBase', ['identifier', 'queue', 'result']) - - -class SlavePipe(_SlavePipeBase): - """Pipe for master-slave communication.""" - - def run_slave(self, msg): - self.queue.put((self.identifier, msg)) - ret = self.result.get() - self.queue.put(True) - return ret - - -class SyncMaster(object): - """An abstract `SyncMaster` object. - - - During the replication, as the data parallel will trigger an callback of each module, all slave devices should - call `register(id)` and obtain an `SlavePipe` to communicate with the master. - - During the forward pass, master device invokes `run_master`, all messages from slave devices will be collected, - and passed to a registered callback. - - After receiving the messages, the master device should gather the information and determine to message passed - back to each slave devices. - """ - - def __init__(self, master_callback): - """ - - Args: - master_callback: a callback to be invoked after having collected messages from slave devices. - """ - self._master_callback = master_callback - self._queue = queue.Queue() - self._registry = collections.OrderedDict() - self._activated = False - - def register_slave(self, identifier): - """ - Register an slave device. - - Args: - identifier: an identifier, usually is the device id. - - Returns: a `SlavePipe` object which can be used to communicate with the master device. - - """ - if self._activated: - assert self._queue.empty(), 'Queue is not clean before next initialization.' - self._activated = False - self._registry.clear() - future = FutureResult() - self._registry[identifier] = _MasterRegistry(future) - return SlavePipe(identifier, self._queue, future) - - def run_master(self, master_msg): - """ - Main entry for the master device in each forward pass. - The messages were first collected from each devices (including the master device), and then - an callback will be invoked to compute the message to be sent back to each devices - (including the master device). - - Args: - master_msg: the message that the master want to send to itself. This will be placed as the first - message when calling `master_callback`. For detailed usage, see `_SynchronizedBatchNorm` for an example. - - Returns: the message to be sent back to the master device. - - """ - self._activated = True - - intermediates = [(0, master_msg)] - for i in range(self.nr_slaves): - intermediates.append(self._queue.get()) - - results = self._master_callback(intermediates) - assert results[0][0] == 0, 'The first result should belongs to the master.' - - for i, res in results: - if i == 0: - continue - self._registry[i].result.put(res) - - for i in range(self.nr_slaves): - assert self._queue.get() is True - - return results[0][1] - - @property - def nr_slaves(self): - return len(self._registry) diff --git a/spaces/Chirag1994/Melanoma_Skin_Cancer_Detection_App/README.md b/spaces/Chirag1994/Melanoma_Skin_Cancer_Detection_App/README.md deleted file mode 100644 index ffd4277e2ec7da71bf92ffa07793493c11a0cf3a..0000000000000000000000000000000000000000 --- a/spaces/Chirag1994/Melanoma_Skin_Cancer_Detection_App/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Melanoma Skin Cancer Detection App -emoji: 💩 -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.27.0 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Chukwuka/FoodVision-Model/README.md b/spaces/Chukwuka/FoodVision-Model/README.md deleted file mode 100644 index bc0c201e7bd989991d9ca965093053f1d9fa5534..0000000000000000000000000000000000000000 --- a/spaces/Chukwuka/FoodVision-Model/README.md +++ /dev/null @@ -1,275 +0,0 @@ ---- -title: FoodVision Model -emoji: 🏢 -colorFrom: blue -colorTo: indigo -sdk: gradio -sdk_version: 3.16.2 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference - -# FoodVision-App -FoodVision App is an App that can classify three different kinds of food; pizza, steak, sushi respectively. - -

Click on this link to visit Github Repo

- -## 09. PyTorch Model Deployment - -Welcome to Milestone Project 3: PyTorch Model Deployment! - -We've come a long way with our FoodVision Mini project. - -But so far our PyTorch models have only been accessible to us. - -How about we bring FoodVision Mini to life and make it publically accessible? - -In other words, **we're going to deploy our FoodVision Mini model to the internet as a usable app!** - -demo of foodvision mini computer vision model being used on a mobile device to predict on an image of sushi and getting it right - -*Trying out the [deployed version of FoodVision Mini](https://huggingface.co/spaces/mrdbourke/foodvision_mini) (what we're going to build) on my lunch. The model got it right too 🍣!* - -### What is machine learning model deployment? - -**Machine learning model deployment** is the process of making your machine learning model accessible to someone or something else. - -Someone else being a person who can interact with your model in some way. - -For example, someone taking a photo on their smartphone of food and then having our FoodVision Mini model classify it into pizza, steak or sushi. - -Something else might be another program, app or even another model that interacts with your machine learning model(s). - -For example, a banking database might rely on a machine learning model making predictions as to whether a transaction is fraudulent or not before transferring funds. - -Or an operating system may lower its resource consumption based on a machine learning model making predictions on how much power someone generally uses at specific times of day. - -These use cases can be mixed and matched as well. - -For example, a Tesla car's computer vision system will interact with the car's route planning program (something else) and then the route planning program will get inputs and feedback from the driver (someone else). - -two use cases for model deployment, making your model available to someone else, for example, someone using it in an app, or making it available to something else such as another program or model - -*Machine learning model deployment involves making your model available to someone or something else. For example, someone might use your model as part of a food recognition app (such as FoodVision Mini or [Nutrify](https://nutrify.app)). And something else might be another model or program using your model such as a banking system using a machine learning model to detect if a transaction is fraud or not.* - - - -### Why deploy a machine learning model? - -One of the most important philosophical questions in machine learning is: - -
-curious dinosaur often referred to as philosoraptor asking the question if a machine learning model never leaves a notebook, does it exist? -
- -Deploying a model is as important as training one. - -Because although you can get a pretty good idea of how your model's going to function by evaluting it on a well crafted test set or visualizing its results, you never really know how it's going to perform until you release it to the wild. - -Having people who've never used your model interact with it will often reveal edge cases you never thought of during training. - -For example, what happens if someone was to upload a photo that *wasn't* of food to our FoodVision Mini model? - -One solution would be to create another model that first classifies images as "food" or "not food" and passing the target image through that model first (this is what [Nutrify](https://nutrify.app) does). - -Then if the image is of "food" it goes to our FoodVision Mini model and gets classified into pizza, steak or sushi. - -And if it's "not food", a message is displayed. - -But what if these predictions were wrong? - -What happens then? - -You can see how these questions could keep going. - -Thus this highlights the importance of model deployment: it helps you figure out errors in your model that aren't obvious during training/testing. - -A PyTorch workflow with added model deployment and monitoring step - -*We covered a PyTorch workflow back in [01. PyTorch Workflow](https://www.learnpytorch.io/01_pytorch_workflow/). But once you've got a good model, deployment is a good next step. Monitoring involves seeing how your model goes on the most important data split: data from the real world. For more resources on deployment and monitoring see [PyTorch Extra Resources](https://www.learnpytorch.io/pytorch_extra_resources/#resources-for-machine-learning-and-deep-learning-engineering).* - - -### Different types of machine learning model deployment - -Whole books could be written on the different types of machine learning model deployment (and many good ones are listed in [PyTorch Extra Resources](https://www.learnpytorch.io/pytorch_extra_resources/#resources-for-machine-learning-and-deep-learning-engineering)). - -And the field is still developing in terms of best practices. - -But I like to start with the question: - -> "What is the most ideal scenario for my machine learning model to be used?" - -And then work backwards from there. - -Of course, you may not know this ahead of time. But you're smart enough to imagine such things. - -In the case of FoodVision Mini, our ideal scenario might be: - -* Someone takes a photo on a mobile device (through an app or web broswer). -* The prediction comes back fast. - -Easy. - -So we've got two main criteria: - -1. The model should work on a mobile device (this means there will be some compute constraints). -2. The model should make predictions *fast* (because a slow app is a boring app). - -And of course, depending on your use case, your requirements may vary. - -You may notice the above two points break down into another two questions: - -1. **Where's it going to go?** - As in, where is it going to be stored? -2. **How's it going to function?** - As in, does it return predictions immediately? Or do they come later? - -some questions to ask when starting to deploy machine learning models, what's the model ideal use case, then work backwards and ask where's my model going to go and how's my model going to function - -*When starting to deploy machine learning models, it's helpful to start by asking what's the most ideal use case and then work backwards from there, asking where the model's going to go and then how it's going to function.* - - -#### Where's it going to go? - -When you deploy your machine learning model, where does it live? - -The main debate here is usually on-device (also called edge/in the browser) or on the cloud (a computer/server that isn't the *actual* device someone/something calls the model from). - -Both have their pros and cons. - -| **Deployment location** | **Pros** | **Cons** | -| :----- | :----- | :----- | -| **On-device (edge/in the browser)** | Can be very fast (since no data leaves the device) | Limited compute power (larger models take longer to run) | -| | Privacy preserving (again no data has to leave the device) | Limited storage space (smaller model size required) | -| | No internet connection required (sometimes) | Device-specific skills often required | -| | | | -| **On cloud** | Near unlimited compute power (can scale up when needed) | Costs can get out of hand (if proper scaling limits aren't enforced) | -| | Can deploy one model and use everywhere (via API) | Predictions can be slower due to data having to leave device and predictions having to come back (network latency) | -| | Links into existing cloud ecosystem | Data has to leave device (this may cause privacy concerns) | - -There are more details to these but I've left resources in the [extra-curriculum](https://www.learnpytorch.io/09_pytorch_model_deployment/#extra-curriculum) to learn more. - -Let's give an example. - -If we're deploying FoodVision Mini as an app, we want it to perform well and fast. - -So which model would we prefer? - -1. A model on-device that performs at 95% accuracy with an inference time (latency) of one second per prediction. -2. A model on the cloud that performs at 98% accuracy with an inference time of 10 seconds per per prediction (bigger, better model but takes longer to compute). - -I've made these numbers up but they showcase a potential difference between on-device and on the cloud. - -Option 1 could potentially be a smaller less performant model that runs fast because its able to fit on a mobile device. - -Option 2 could potentially a larger more performant model that requires more compute and storage but it takes a bit longer to run because we have to send data off the device and get it back (so even though the actual prediction might be fast, the network time and data transfer has to factored in). - -For FoodVision Mini, we'd likely prefer option 1, because the small hit in performance is far outweighed by the faster inference speed. - -tesla computer vision system on device vs on the cloud - -*In the case of a Tesla car's computer vision system, which would be better? A smaller model that performs well on device (model is on the car) or a larger model that performs better that's on the cloud? In this case, you'd much prefer the model being on the car. The extra network time it would take for data to go from the car to the cloud and then back to the car just wouldn't be worth it (or potentially even possible with poor signal areas).* - -> **Note:** For a full example of seeing what it's like to deploy a PyTorch model to an edge device, see the [PyTorch tutorial on achieving real-time inference (30fps+)](https://pytorch.org/tutorials/intermediate/realtime_rpi.html) with a computer vision model on a Raspberry Pi. - - -#### Ways to deploy a machine learning model - -We've discussed a couple of options for deploying machine learning models (on-device and cloud). - -And each of these will have their specific requirements: - -| **Tool/resource** | **Deployment type** | -| :----- | :----- | -| [Google's ML Kit](https://developers.google.com/ml-kit) | On-device (Android and iOS) | -| [Apple's Core ML](https://developer.apple.com/documentation/coreml) and [`coremltools` Python package](https://coremltools.readme.io/docs) | On-device (all Apple devices) | -| [Amazon Web Service's (AWS) Sagemaker](https://aws.amazon.com/sagemaker/) | Cloud | -| [Google Cloud's Vertex AI](https://cloud.google.com/vertex-ai) | Cloud | -| [Microsoft's Azure Machine Learning](https://azure.microsoft.com/en-au/services/machine-learning/) | Cloud | -| [Hugging Face Spaces](https://huggingface.co/spaces) | Cloud | -| API with [FastAPI](https://fastapi.tiangolo.com) | Cloud/self-hosted server | -| API with [TorchServe](https://pytorch.org/serve/) | Cloud/self-hosted server | -| [ONNX (Open Neural Network Exchange)](https://onnx.ai/index.html) | Many/general | -| Many more... | - -> **Note:** An [application programming interface (API)](https://en.wikipedia.org/wiki/API) is a way for two (or more) computer programs to interact with each other. For example, if your model was deployed as API, you would be able to write a program that could send data to it and then receive predictions back. - -Which option you choose will be highly dependent on what you're building/who you're working with. - -But with so many options, it can be very intimidating. - -So best to start small and keep it simple. - -And one of the best ways to do so is by turning your machine learning model into a demo app with [Gradio](https://gradio.app) and then deploying it on Hugging Face Spaces. - -We'll be doing just that with FoodVision Mini later on. - -tools and places to deploy machine learning models - -*A handful of places and tools to host and deploy machine learning models. There are plenty I've missed so if you'd like to add more, please leave a [discussion on GitHub](https://github.com/mrdbourke/pytorch-deep-learning/discussions).* - - -### What we're going to Learn - -Enough talking about deploying a machine learning model. - -Let's become machine learning engineers and actually deploy one. - -Our goal is to deploy our FoodVision Model via a demo Gradio app with the following metrics: -1. **Performance:** 95%+ accuracy. -2. **Speed:** real-time inference of 30FPS+ (each prediction has a latency of lower than ~0.03s). - -Then we'll deploy the one which performs closest to our goal metrics. - -Finally, we'll finish with a (BIG) surprise bonus. - -| **Topic** | **Contents** | -| :----- | :----- | -| **0. Getting setup** | We've written a fair bit of useful code over the past few sections, let's download it and make sure we can use it again. | -| **1. Get data** | Let's download the [`pizza_steak_sushi_20_percent.zip`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/data/pizza_steak_sushi_20_percent.zip) dataset so we can train our previously best performing models on the same dataset. | -| **2. Creating an Model feature extractor** | An EfficientNetB2 feature extractor performed the best on our pizza, steak, sushi dataset in [07. PyTorch Experiment Tracking](https://www.learnpytorch.io/07_pytorch_experiment_tracking/), let's recreate it as a candidate for deployment. | -| **3. Making predictions with our trained models and timing them** | We've built two of the best performing models yet, let's make predictions with them and track their results. | -| **4. Bringing FoodVision Mini to life by creating a Gradio demo** | One of our models performs better than the other (in terms of our goals), so let's turn it into a working app demo! | -| **5. Turning our FoodVision Mini Gradio demo into a deployable app** | Our Gradio app demo works locally, let's prepare it for deployment! | -| **6. Deploying our Gradio demo to HuggingFace Spaces** | Let's take FoodVision Mini to the web and make it pubically accessible for all! | - - -#### Uploading to Hugging Face - -We've verfied our FoodVision Mini app works locally, however, the fun of creating a machine learning demo is to show it to other people and allow them to use it. - -To do so, we're going to upload our FoodVision Mini demo to Hugging Face. - -> **Note:** The following series of steps uses a Git (a file tracking system) workflow. For more on how Git works, I'd recommend going through the [Git and GitHub for Beginners tutorial](https://youtu.be/RGOj5yH7evk) on freeCodeCamp. - -1. [Sign up](https://huggingface.co/join) for a Hugging Face account. -2. Start a new Hugging Face Space by going to your profile and then [clicking "New Space"](https://huggingface.co/new-space). - * **Note:** A Space in Hugging Face is also known as a "code repository" (a place to store your code/files) or "repo" for short. -3. Give the Space a name, for example, mine is called `mrdbourke/foodvision_mini`, you can see it here: https://huggingface.co/spaces/mrdbourke/foodvision_mini -4. Select a license (I used [MIT](https://opensource.org/licenses/MIT)). -5. Select Gradio as the Space SDK (software development kit). - * **Note:** You can use other options such as Streamlit but since our app is built with Gradio, we'll stick with that. -6. Choose whether your Space is it's public or private (I selected public since I'd like my Space to be available to others). -7. Click "Create Space". -8. Clone the repo locally by running something like: `git clone https://huggingface.co/spaces/[YOUR_USERNAME]/[YOUR_SPACE_NAME]` in terminal or command prompt. - * **Note:** You can also add files via uploading them under the "Files and versions" tab. -9. Copy/move the contents of the downloaded `foodvision_mini` folder to the cloned repo folder. -10. To upload and track larger files (e.g. files over 10MB or in our case, our PyTorch model file) you'll need to [install Git LFS](https://git-lfs.github.com/) (which stands for "git large file storage"). -11. After you've installed Git LFS, you can activate it by running `git lfs install`. -12. In the `foodvision_mini` directory, track the files over 10MB with Git LFS with `git lfs track "*.file_extension"`. - * Track EffNetB2 PyTorch model file with `git lfs track "09_pretrained_effnetb2_feature_extractor_pizza_steak_sushi_20_percent.pth"`. -13. Track `.gitattributes` (automatically created when cloning from HuggingFace, this file will help ensure our larger files are tracked with Git LFS). You can see an example `.gitattributes` file on the [FoodVision Mini Hugging Face Space](https://huggingface.co/spaces/mrdbourke/foodvision_mini/blob/main/.gitattributes). - * `git add .gitattributes` -14. Add the rest of the `foodvision_mini` app files and commit them with: - * `git add *` - * `git commit -m "first commit"` -15. Push (upload) the files to Hugging Face: - * `git push` -16. Wait 3-5 minutes for the build to happen (future builds are faster) and your app to become live! - -If everything worked, you should see a live running example of our FoodVision Mini Gradio demo like the one here: https://huggingface.co/spaces/mrdbourke/foodvision_mini - -And we can even embed our FoodVision Mini Gradio demo into our notebook as an [iframe](https://gradio.app/sharing_your_app/#embedding-with-iframes) with [`IPython.display.IFrame`](https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.IFrame) and a link to our space in the format `https://hf.space/embed/[YOUR_USERNAME]/[YOUR_SPACE_NAME]/+`. - - Click on this link to try out Foodvision App diff --git a/spaces/CikeyQI/Yunzai/Yunzai/plugins/ws-plugin/config/system/cfg_system.js b/spaces/CikeyQI/Yunzai/Yunzai/plugins/ws-plugin/config/system/cfg_system.js deleted file mode 100644 index 663c0a4afcbc980e879cb90542551c6456202f57..0000000000000000000000000000000000000000 --- a/spaces/CikeyQI/Yunzai/Yunzai/plugins/ws-plugin/config/system/cfg_system.js +++ /dev/null @@ -1,201 +0,0 @@ -export const cfgSchema = { - ws: { - title: 'ws连接设置,改动此设置会将所有已连接强制断开重连', - cfg: { - heartbeatInterval: { - title: '心跳频率', - key: '心跳', - type: 'num', - def: 5, - input: (n) => { - if (n >= 0) { - return n * 1 - } else { - return 5 - } - }, - desc: '单位:秒,0为关闭心跳', - fileName: 'ws-config' - }, - messagePostFormat: { - title: '上报数据类型', - key: '上报', - type: 'num', - def: 2, - input: (n) => Math.min(2, Math.max(n * 1 || 0, 1)), - desc: '上报数据类型: 1:string 2:array', - fileName: 'ws-config' - } - } - }, - msg: { - title: '发送消息相关设置', - cfg: { - disconnectToMaster: { - title: '断连通知', - key: '断连通知', - def: false, - desc: '断开连接时是否通知主人', - fileName: 'msg-config' - }, - reconnectToMaster: { - title: '重连通知', - key: '重连通知', - def: false, - desc: '重新连接成功时是否通知主人', - fileName: 'msg-config' - }, - firstconnectToMaster: { - title: '首连通知', - key: '首连通知', - def: false, - desc: '首次连接时是否通知主人成功还是失败', - fileName: 'msg-config' - }, - howToMaster: { - title: '通知哪个主人', - key: '主人', - type: 'num', - input: (n) => { - if (n >= 0) { - return n * 1 - } else { - return 1 - } - }, - def: 1, - desc: `通知主人列表的第几个主人,为0时通知全部主人`, - fileName: 'msg-config' - }, - muteStop: { - title: '禁言拦截', - key: '禁言拦截', - def: false, - desc: '被禁言或者全体禁言时是否拦截消息不上报', - fileName: 'msg-config' - }, - redSendForwardMsgType: { - title: 'red转发方式', - key: 'red转发', - type: 'num', - def: 1, - desc: 'red 发送伪造转发消息方式 1:伪造转发 2:陆续发送 3:合并发送', - input: (n) => Math.min(3, Math.max(n * 1 || 0, 1)), - fileName: 'msg-config' - }, - msgStoreTime: { - title: '消息存储时间', - key: '存储', - type: 'num', - input: (n) => { - if (n >= 0) { - return n * 1 - } else { - return 600 - } - }, - def: 600, - desc: '用于撤回和回复消息,如果超过时间去获取就会获取不到,单位秒,0不存储', - fileName: 'msg-config' - } - } - }, - notice: { - title: '通知相关设置', - cfg: { - groupAdmin: { - title: '管理员变动', - key: '管理', - def: false, - desc: '群管理员变动是否上报', - fileName: 'notice-config' - }, - groupDecrease: { - title: '群成员减少', - key: '群员减少', - def: false, - desc: '群成员减少是否上报', - fileName: 'notice-config' - }, - groupIncrease: { - title: '群成员增加', - key: '群员增加', - def: false, - desc: '群成员增加是否上报', - fileName: 'notice-config' - }, - groupBan: { - title: '群禁言', - key: '禁言', - def: false, - desc: '群禁言是否上报', - fileName: 'notice-config' - }, - friendIncrease: { - title: '好友添加', - key: '好友添加', - def: false, - desc: '好友添加是否上报', - fileName: 'notice-config' - }, - groupRecall: { - title: '群消息撤回', - key: '群撤回', - def: false, - desc: '群消息撤回是否上报', - fileName: 'notice-config' - }, - friendRecall: { - title: '好友消息撤回', - key: '好友撤回', - def: false, - desc: '好友消息撤回是否上报', - fileName: 'notice-config' - }, - groupPoke: { - title: '群内戳一戳', - key: '戳一戳', - def: false, - desc: '群内戳一戳是否上报', - fileName: 'notice-config' - }, - } - }, - request: { - title: '请求相关设置', - cfg: { - friendAdd: { - title: '好友申请', - key: '好友申请', - def: false, - desc: '好友申请是否上报', - fileName: 'request-config' - }, - groupInvite: { - title: '群聊邀请', - key: '群邀请', - def: false, - desc: '群聊邀请是否上报 (邀请机器人入群)', - fileName: 'request-config' - }, - groupAdd: { - title: '群聊申请', - key: '群申请', - def: false, - desc: '群聊申请是否上报 (申请加入群聊)', - fileName: 'request-config' - }, - } - }, - setAll: { - title: '一键操作', - cfg: { - setAll: { - title: '全部设置', - key: '全部', - def: false, - desc: '一键 开启/关闭 全部设置项' - } - } - } -} diff --git a/spaces/CikeyQI/meme-api/meme_generator/memes/karyl_point/__init__.py b/spaces/CikeyQI/meme-api/meme_generator/memes/karyl_point/__init__.py deleted file mode 100644 index 5824b41f72d42ebe1bb8fb4533a68fec839ea3b7..0000000000000000000000000000000000000000 --- a/spaces/CikeyQI/meme-api/meme_generator/memes/karyl_point/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -from pathlib import Path -from typing import List - -from pil_utils import BuildImage - -from meme_generator import add_meme - -img_dir = Path(__file__).parent / "images" - - -def karyl_point(images: List[BuildImage], texts, args): - img = images[0].convert("RGBA").rotate(7.5, expand=True).resize((225, 225)) - frame = BuildImage.open(img_dir / "0.png") - frame.paste(img, (87, 790), alpha=True) - return frame.save_png() - - -add_meme("karyl_point", karyl_point, min_images=1, max_images=1, keywords=["凯露指"]) diff --git a/spaces/CofAI/chat.v1/README.md b/spaces/CofAI/chat.v1/README.md deleted file mode 100644 index ca01a0a7f60ee4faca24f65de98d20d1385602a4..0000000000000000000000000000000000000000 --- a/spaces/CofAI/chat.v1/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Chat.CofAI -emoji: 🗨☕💬 -colorFrom: indigo -colorTo: green -sdk: docker -pinned: false -duplicated_from: null ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/CofAI/chat/g4f/Provider/Providers/Aichat.py b/spaces/CofAI/chat/g4f/Provider/Providers/Aichat.py deleted file mode 100644 index d78375ce7e62b634c82e163c693a5557b8e2f860..0000000000000000000000000000000000000000 --- a/spaces/CofAI/chat/g4f/Provider/Providers/Aichat.py +++ /dev/null @@ -1,35 +0,0 @@ -import requests -import os -import json -from ...typing import sha256, Dict, get_type_hints - -url = 'https://hteyun.com' -model = ['gpt-3.5-turbo', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613', 'gpt-3.5-turbo-0613'] -supports_stream = True -needs_auth = False - -def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs): - headers = { - 'Content-Type': 'application/json', - } - data = { - 'model': model, - 'temperature': 0.7, - 'presence_penalty': 0, - 'messages': messages, - } - response = requests.post(url + '/api/chat-stream', - json=data, stream=True) - - if stream: - for chunk in response.iter_content(chunk_size=None): - chunk = chunk.decode('utf-8') - if chunk.strip(): - message = json.loads(chunk)['choices'][0]['message']['content'] - yield message - else: - message = response.json()['choices'][0]['message']['content'] - yield message - -params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \ - '(%s)' % ', '.join([f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]]) \ No newline at end of file diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fsspec/implementations/dbfs.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fsspec/implementations/dbfs.py deleted file mode 100644 index 9f5b330cab9e751142794253d1072bab48b8bc29..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fsspec/implementations/dbfs.py +++ /dev/null @@ -1,457 +0,0 @@ -import base64 -import urllib - -import requests - -from fsspec import AbstractFileSystem -from fsspec.spec import AbstractBufferedFile - - -class DatabricksException(Exception): - """ - Helper class for exceptions raised in this module. - """ - - def __init__(self, error_code, message): - """Create a new DatabricksException""" - super().__init__(message) - - self.error_code = error_code - self.message = message - - -class DatabricksFileSystem(AbstractFileSystem): - """ - Get access to the Databricks filesystem implementation over HTTP. - Can be used inside and outside of a databricks cluster. - """ - - def __init__(self, instance, token, **kwargs): - """ - Create a new DatabricksFileSystem. - - Parameters - ---------- - instance: str - The instance URL of the databricks cluster. - For example for an Azure databricks cluster, this - has the form adb-..azuredatabricks.net. - token: str - Your personal token. Find out more - here: https://docs.databricks.com/dev-tools/api/latest/authentication.html - """ - self.instance = instance - self.token = token - - self.session = requests.Session() - self.session.headers.update({"Authorization": f"Bearer {self.token}"}) - - super().__init__(**kwargs) - - def ls(self, path, detail=True): - """ - List the contents of the given path. - - Parameters - ---------- - path: str - Absolute path - detail: bool - Return not only the list of filenames, - but also additional information on file sizes - and types. - """ - out = self._ls_from_cache(path) - if not out: - try: - r = self._send_to_api( - method="get", endpoint="list", json={"path": path} - ) - except DatabricksException as e: - if e.error_code == "RESOURCE_DOES_NOT_EXIST": - raise FileNotFoundError(e.message) - - raise e - files = r["files"] - out = [ - { - "name": o["path"], - "type": "directory" if o["is_dir"] else "file", - "size": o["file_size"], - } - for o in files - ] - self.dircache[path] = out - - if detail: - return out - return [o["name"] for o in out] - - def makedirs(self, path, exist_ok=True): - """ - Create a given absolute path and all of its parents. - - Parameters - ---------- - path: str - Absolute path to create - exist_ok: bool - If false, checks if the folder - exists before creating it (and raises an - Exception if this is the case) - """ - if not exist_ok: - try: - # If the following succeeds, the path is already present - self._send_to_api( - method="get", endpoint="get-status", json={"path": path} - ) - raise FileExistsError(f"Path {path} already exists") - except DatabricksException as e: - if e.error_code == "RESOURCE_DOES_NOT_EXIST": - pass - - try: - self._send_to_api(method="post", endpoint="mkdirs", json={"path": path}) - except DatabricksException as e: - if e.error_code == "RESOURCE_ALREADY_EXISTS": - raise FileExistsError(e.message) - - raise e - self.invalidate_cache(self._parent(path)) - - def mkdir(self, path, create_parents=True, **kwargs): - """ - Create a given absolute path and all of its parents. - - Parameters - ---------- - path: str - Absolute path to create - create_parents: bool - Whether to create all parents or not. - "False" is not implemented so far. - """ - if not create_parents: - raise NotImplementedError - - self.mkdirs(path, **kwargs) - - def rm(self, path, recursive=False): - """ - Remove the file or folder at the given absolute path. - - Parameters - ---------- - path: str - Absolute path what to remove - recursive: bool - Recursively delete all files in a folder. - """ - try: - self._send_to_api( - method="post", - endpoint="delete", - json={"path": path, "recursive": recursive}, - ) - except DatabricksException as e: - # This is not really an exception, it just means - # not everything was deleted so far - if e.error_code == "PARTIAL_DELETE": - self.rm(path=path, recursive=recursive) - elif e.error_code == "IO_ERROR": - # Using the same exception as the os module would use here - raise OSError(e.message) - - raise e - self.invalidate_cache(self._parent(path)) - - def mv(self, source_path, destination_path, recursive=False, maxdepth=None): - """ - Move a source to a destination path. - - A note from the original [databricks API manual] - (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move). - - When moving a large number of files the API call will time out after - approximately 60s, potentially resulting in partially moved data. - Therefore, for operations that move more than 10k files, we strongly - discourage using the DBFS REST API. - - Parameters - ---------- - source_path: str - From where to move (absolute path) - destination_path: str - To where to move (absolute path) - recursive: bool - Not implemented to far. - maxdepth: - Not implemented to far. - """ - if recursive: - raise NotImplementedError - if maxdepth: - raise NotImplementedError - - try: - self._send_to_api( - method="post", - endpoint="move", - json={"source_path": source_path, "destination_path": destination_path}, - ) - except DatabricksException as e: - if e.error_code == "RESOURCE_DOES_NOT_EXIST": - raise FileNotFoundError(e.message) - elif e.error_code == "RESOURCE_ALREADY_EXISTS": - raise FileExistsError(e.message) - - raise e - self.invalidate_cache(self._parent(source_path)) - self.invalidate_cache(self._parent(destination_path)) - - def _open(self, path, mode="rb", block_size="default", **kwargs): - """ - Overwrite the base class method to make sure to create a DBFile. - All arguments are copied from the base method. - - Only the default blocksize is allowed. - """ - return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs) - - def _send_to_api(self, method, endpoint, json): - """ - Send the given json to the DBFS API - using a get or post request (specified by the argument `method`). - - Parameters - ---------- - method: str - Which http method to use for communication; "get" or "post". - endpoint: str - Where to send the request to (last part of the API URL) - json: dict - Dictionary of information to send - """ - if method == "post": - session_call = self.session.post - elif method == "get": - session_call = self.session.get - else: - raise ValueError(f"Do not understand method {method}") - - url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint) - - r = session_call(url, json=json) - - # The DBFS API will return a json, also in case of an exception. - # We want to preserve this information as good as possible. - try: - r.raise_for_status() - except requests.HTTPError as e: - # try to extract json error message - # if that fails, fall back to the original exception - try: - exception_json = e.response.json() - except Exception: - raise e - - raise DatabricksException(**exception_json) - - return r.json() - - def _create_handle(self, path, overwrite=True): - """ - Internal function to create a handle, which can be used to - write blocks of a file to DBFS. - A handle has a unique identifier which needs to be passed - whenever written during this transaction. - The handle is active for 10 minutes - after that a new - write transaction needs to be created. - Make sure to close the handle after you are finished. - - Parameters - ---------- - path: str - Absolute path for this file. - overwrite: bool - If a file already exist at this location, either overwrite - it or raise an exception. - """ - try: - r = self._send_to_api( - method="post", - endpoint="create", - json={"path": path, "overwrite": overwrite}, - ) - return r["handle"] - except DatabricksException as e: - if e.error_code == "RESOURCE_ALREADY_EXISTS": - raise FileExistsError(e.message) - - raise e - - def _close_handle(self, handle): - """ - Close a handle, which was opened by :func:`_create_handle`. - - Parameters - ---------- - handle: str - Which handle to close. - """ - try: - self._send_to_api(method="post", endpoint="close", json={"handle": handle}) - except DatabricksException as e: - if e.error_code == "RESOURCE_DOES_NOT_EXIST": - raise FileNotFoundError(e.message) - - raise e - - def _add_data(self, handle, data): - """ - Upload data to an already opened file handle - (opened by :func:`_create_handle`). - The maximal allowed data size is 1MB after - conversion to base64. - Remember to close the handle when you are finished. - - Parameters - ---------- - handle: str - Which handle to upload data to. - data: bytes - Block of data to add to the handle. - """ - data = base64.b64encode(data).decode() - try: - self._send_to_api( - method="post", - endpoint="add-block", - json={"handle": handle, "data": data}, - ) - except DatabricksException as e: - if e.error_code == "RESOURCE_DOES_NOT_EXIST": - raise FileNotFoundError(e.message) - elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED": - raise ValueError(e.message) - - raise e - - def _get_data(self, path, start, end): - """ - Download data in bytes from a given absolute path in a block - from [start, start+length]. - The maximum number of allowed bytes to read is 1MB. - - Parameters - ---------- - path: str - Absolute path to download data from - start: int - Start position of the block - end: int - End position of the block - """ - try: - r = self._send_to_api( - method="get", - endpoint="read", - json={"path": path, "offset": start, "length": end - start}, - ) - return base64.b64decode(r["data"]) - except DatabricksException as e: - if e.error_code == "RESOURCE_DOES_NOT_EXIST": - raise FileNotFoundError(e.message) - elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]: - raise ValueError(e.message) - - raise e - - def invalidate_cache(self, path=None): - if path is None: - self.dircache.clear() - else: - self.dircache.pop(path, None) - super().invalidate_cache(path) - - -class DatabricksFile(AbstractBufferedFile): - """ - Helper class for files referenced in the DatabricksFileSystem. - """ - - DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size - - def __init__( - self, - fs, - path, - mode="rb", - block_size="default", - autocommit=True, - cache_type="readahead", - cache_options=None, - **kwargs, - ): - """ - Create a new instance of the DatabricksFile. - - The blocksize needs to be the default one. - """ - if block_size is None or block_size == "default": - block_size = self.DEFAULT_BLOCK_SIZE - - assert ( - block_size == self.DEFAULT_BLOCK_SIZE - ), f"Only the default block size is allowed, not {block_size}" - - super().__init__( - fs, - path, - mode=mode, - block_size=block_size, - autocommit=autocommit, - cache_type=cache_type, - cache_options=cache_options or {}, - **kwargs, - ) - - def _initiate_upload(self): - """Internal function to start a file upload""" - self.handle = self.fs._create_handle(self.path) - - def _upload_chunk(self, final=False): - """Internal function to add a chunk of data to a started upload""" - self.buffer.seek(0) - data = self.buffer.getvalue() - - data_chunks = [ - data[start:end] for start, end in self._to_sized_blocks(len(data)) - ] - - for data_chunk in data_chunks: - self.fs._add_data(handle=self.handle, data=data_chunk) - - if final: - self.fs._close_handle(handle=self.handle) - return True - - def _fetch_range(self, start, end): - """Internal function to download a block of data""" - return_buffer = b"" - length = end - start - for chunk_start, chunk_end in self._to_sized_blocks(length, start): - return_buffer += self.fs._get_data( - path=self.path, start=chunk_start, end=chunk_end - ) - - return return_buffer - - def _to_sized_blocks(self, length, start=0): - """Helper function to split a range from 0 to total_length into bloksizes""" - end = start + length - for data_chunk in range(start, end, self.blocksize): - data_start = data_chunk - data_end = min(end, data_chunk + self.blocksize) - yield data_start, data_end diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/components/slider.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/components/slider.py deleted file mode 100644 index c589eb675d09dc0521c100488799aa96af8b06ca..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/components/slider.py +++ /dev/null @@ -1,210 +0,0 @@ -"""gr.Slider() component.""" - -from __future__ import annotations - -import math -import random -from typing import Any, Callable, Literal - -import numpy as np -from gradio_client.documentation import document, set_documentation_group -from gradio_client.serializing import NumberSerializable - -from gradio.components.base import FormComponent, IOComponent, _Keywords -from gradio.deprecation import warn_style_method_deprecation -from gradio.events import Changeable, Inputable, Releaseable -from gradio.interpretation import NeighborInterpretable - -set_documentation_group("component") - - -@document() -class Slider( - FormComponent, - Changeable, - Inputable, - Releaseable, - IOComponent, - NumberSerializable, - NeighborInterpretable, -): - """ - Creates a slider that ranges from `minimum` to `maximum` with a step size of `step`. - Preprocessing: passes slider value as a {float} into the function. - Postprocessing: expects an {int} or {float} returned from function and sets slider value to it as long as it is within range. - Examples-format: A {float} or {int} representing the slider's value. - - Demos: sentence_builder, slider_release, generate_tone, titanic_survival, interface_random_slider, blocks_random_slider - Guides: create-your-own-friends-with-a-gan - """ - - def __init__( - self, - minimum: float = 0, - maximum: float = 100, - value: float | Callable | None = None, - *, - step: float | None = None, - label: str | None = None, - info: str | None = None, - every: float | None = None, - show_label: bool | None = None, - container: bool = True, - scale: int | None = None, - min_width: int = 160, - interactive: bool | None = None, - visible: bool = True, - elem_id: str | None = None, - elem_classes: list[str] | str | None = None, - randomize: bool = False, - **kwargs, - ): - """ - Parameters: - minimum: minimum value for slider. - maximum: maximum value for slider. - value: default value. If callable, the function will be called whenever the app loads to set the initial value of the component. Ignored if randomized=True. - step: increment between slider values. - label: component name in interface. - info: additional component description. - every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. - show_label: if True, will display label. - container: If True, will place the component in a container - providing some extra padding around the border. - scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. - min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. - interactive: if True, slider will be adjustable; if False, adjusting will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. - visible: If False, component will be hidden. - elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. - elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. - randomize: If True, the value of the slider when the app loads is taken uniformly at random from the range given by the minimum and maximum. - """ - self.minimum = minimum - self.maximum = maximum - if step is None: - difference = maximum - minimum - power = math.floor(math.log10(difference) - 2) - self.step = 10**power - else: - self.step = step - if randomize: - value = self.get_random_value - IOComponent.__init__( - self, - label=label, - info=info, - every=every, - show_label=show_label, - container=container, - scale=scale, - min_width=min_width, - interactive=interactive, - visible=visible, - elem_id=elem_id, - elem_classes=elem_classes, - value=value, - **kwargs, - ) - NeighborInterpretable.__init__(self) - - def api_info(self) -> dict[str, dict | bool]: - return { - "info": { - "type": "number", - "description": f"numeric value between {self.minimum} and {self.maximum}", - }, - "serialized_info": False, - } - - def example_inputs(self) -> dict[str, Any]: - return { - "raw": self.minimum, - "serialized": self.minimum, - } - - def get_config(self): - return { - "minimum": self.minimum, - "maximum": self.maximum, - "step": self.step, - "value": self.value, - **IOComponent.get_config(self), - } - - def get_random_value(self): - n_steps = int((self.maximum - self.minimum) / self.step) - step = random.randint(0, n_steps) - value = self.minimum + step * self.step - # Round to number of decimals in step so that UI doesn't display long decimals - n_decimals = max(str(self.step)[::-1].find("."), 0) - if n_decimals: - value = round(value, n_decimals) - return value - - @staticmethod - def update( - value: float | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, - minimum: float | None = None, - maximum: float | None = None, - step: float | None = None, - label: str | None = None, - info: str | None = None, - show_label: bool | None = None, - container: bool | None = None, - scale: int | None = None, - min_width: int | None = None, - interactive: bool | None = None, - visible: bool | None = None, - ): - return { - "minimum": minimum, - "maximum": maximum, - "step": step, - "label": label, - "info": info, - "show_label": show_label, - "container": container, - "scale": scale, - "min_width": min_width, - "interactive": interactive, - "visible": visible, - "value": value, - "__type__": "update", - } - - def postprocess(self, y: float | None) -> float | None: - """ - Any postprocessing needed to be performed on function output. - Parameters: - y: numeric output - Returns: - numeric output or minimum number if None - """ - return self.minimum if y is None else y - - def set_interpret_parameters(self, steps: int = 8) -> Slider: - """ - Calculates interpretation scores of numeric values ranging between the minimum and maximum values of the slider. - Parameters: - steps: Number of neighboring values to measure between the minimum and maximum values of the slider range. - """ - self.interpretation_steps = steps - return self - - def get_interpretation_neighbors(self, x) -> tuple[object, dict]: - return ( - np.linspace(self.minimum, self.maximum, self.interpretation_steps).tolist(), - {}, - ) - - def style( - self, - *, - container: bool | None = None, - ): - """ - This method is deprecated. Please set these arguments in the constructor instead. - """ - warn_style_method_deprecation() - if container is not None: - self.container = container - return self diff --git a/spaces/Datasculptor/3D-Room-Layout-Estimation_LGT-Net/utils/writer.py b/spaces/Datasculptor/3D-Room-Layout-Estimation_LGT-Net/utils/writer.py deleted file mode 100644 index bfa99ff33a75588b02163201e7a478f5b5223b3a..0000000000000000000000000000000000000000 --- a/spaces/Datasculptor/3D-Room-Layout-Estimation_LGT-Net/utils/writer.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -@Date: 2021/11/06 -@description: -""" -import cv2 -import numpy as np - - -def xyz2json(xyz, ratio, camera_height=1.6): - xyz = xyz * camera_height - ceiling_height = camera_height * ratio - layout_height = camera_height + ceiling_height - data = { - 'cameraHeight': camera_height, - 'layoutHeight': layout_height, - 'cameraCeilingHeight': ceiling_height, - 'layoutObj2ds': { - 'num': 0, - 'obj2ds': [] - }, - 'layoutPoints': { - 'num': xyz.shape[0], - 'points': [] - }, - 'layoutWalls': { - 'num': xyz.shape[0], - 'walls': [] - } - } - - xyz = np.concatenate([xyz, xyz[0:1, :]], axis=0) - R_180 = cv2.Rodrigues(np.array([0, -1 * np.pi, 0], np.float32))[0] - for i in range(xyz.shape[0] - 1): - a = np.dot(R_180, xyz[i, :]) - a[0] *= -1 - b = np.dot(R_180, xyz[i + 1, :]) - b[0] *= -1 - c = a.copy() - c[1] = 0 - normal = np.cross(a - b, a - c) - normal /= np.linalg.norm(normal) - d = -np.sum(normal * a) - plane = np.asarray([normal[0], normal[1], normal[2], d]) - - data['layoutPoints']['points'].append({'xyz': a.tolist(), 'id': i}) - - next_i = 0 if i + 1 >= (xyz.shape[0] - 1) else i + 1 - tmp = { - 'normal': normal.tolist(), - 'planeEquation': plane.tolist(), - 'pointsIdx': [i, next_i] - } - data['layoutWalls']['walls'].append(tmp) - - return data - diff --git a/spaces/DeclK/pose/tools/inferencer.py b/spaces/DeclK/pose/tools/inferencer.py deleted file mode 100644 index fb8680516b73378d66f887c184d42d5397b403b8..0000000000000000000000000000000000000000 --- a/spaces/DeclK/pose/tools/inferencer.py +++ /dev/null @@ -1,160 +0,0 @@ -import numpy as np -import mmcv -from pathlib import Path -from collections import namedtuple -import cv2 as cv -from tqdm import tqdm -from mmengine.registry import init_default_scope -from mmengine.visualization import Visualizer -from mmpose.apis import inference_topdown, init_model -from mmdet.apis import inference_detector, init_detector -from .utils import filter_by_catgory, filter_by_score, Timer -from .apis import build_onnx_model_and_task_processor, inference_onnx_model - - -class PoseInferencer: - def __init__(self, - det_cfg, - pose_cfg, - device='cpu') -> None: - # init - self.det_model_cfg = det_cfg.model_cfg - self.det_model_ckpt = det_cfg.model_ckpt - self.pose_model_cfg = pose_cfg.model_cfg - self.pose_model_ckpt = pose_cfg.model_ckpt - - self.detector = init_detector(self.det_model_cfg, - self.det_model_ckpt, - device=device) - self.pose_model = init_model(self.pose_model_cfg, - self.pose_model_ckpt, - device=device) - # use this count to tell the progress - self.video_count = 0 - - def process_one_image(self, img): - init_default_scope('mmdet') - det_result = inference_detector(self.detector, img) - det_inst = det_result.pred_instances.cpu().numpy() - bboxes, scores, labels = (det_inst.bboxes, - det_inst.scores, - det_inst.labels) - bboxes, scores, labels = filter_by_score(bboxes, scores, - labels, 0.5) - bboxes, scores, labels = filter_by_catgory(bboxes, scores, labels, - ['person']) - # inference with pose model - init_default_scope('mmpose') - pose_result = inference_topdown(self.pose_model, img, bboxes) - if len(pose_result) == 0: - # no detection place holder - keypoints = np.zeros((1, 17, 2)) - pts_scores = np.zeros((1, 17)) - bboxes = np.zeros((1, 4)) - scores = np.zeros((1, )) - labels = np.zeros((1, )) - else: - keypoints = np.concatenate([r.pred_instances.keypoints - for r in pose_result]) - pts_scores = np.concatenate([r.pred_instances.keypoint_scores - for r in pose_result]) - - DetInst = namedtuple('DetInst', ['bboxes', 'scores', 'labels']) - PoseInst = namedtuple('PoseInst', ['keypoints', 'pts_scores']) - return DetInst(bboxes, scores, labels), PoseInst(keypoints, pts_scores) - - def inference_video(self, video_path): - """ Inference a video with detector and pose model - Return: - all_pose: a list of PoseInst, check the namedtuple definition - all_det: a list of DetInst - """ - video_reader = mmcv.VideoReader(video_path) - all_pose, all_det = [], [] - - for frame in tqdm(video_reader): - # inference with detector - det, pose = self.process_one_image(frame) - all_pose.append(pose) - all_det.append(det) - - return all_det, all_pose - -class PoseInferencerV2: - """ V2 Use onnx for detection model, still use pytorch for pose model. - """ - def __init__(self, - det_cfg, - pose_cfg, - device='cpu') -> None: - # init - self.det_deploy_cfg = det_cfg.deploy_cfg - self.det_model_cfg = det_cfg.model_cfg - self.det_backend_files = det_cfg.backend_files - - self.pose_model_cfg = pose_cfg.model_cfg - self.pose_model_ckpt = pose_cfg.model_ckpt - - self.detector, self.task_processor = \ - build_onnx_model_and_task_processor(self.det_model_cfg, - self.det_deploy_cfg, - self.det_backend_files, - device) - self.pose_model = init_model(self.pose_model_cfg, - self.pose_model_ckpt, - device) - # use this count to tell the progress - self.video_count = 0 - - def process_one_image(self, img): - init_default_scope('mmdet') - det_result = inference_onnx_model(self.detector, - self.task_processor, - self.det_deploy_cfg, - img) - det_inst = det_result[0].pred_instances.cpu().numpy() - bboxes, scores, labels = (det_inst.bboxes, - det_inst.scores, - det_inst.labels) - bboxes, scores, labels = filter_by_score(bboxes, scores, - labels, 0.5) - bboxes, scores, labels = filter_by_catgory(bboxes, scores, labels, - ['person']) - # inference with pose model - init_default_scope('mmpose') - pose_result = inference_topdown(self.pose_model, img, bboxes) - if len(pose_result) == 0: - # no detection place holder - keypoints = np.zeros((1, 17, 2)) - pts_scores = np.zeros((1, 17)) - bboxes = np.zeros((1, 4)) - scores = np.zeros((1, )) - labels = np.zeros((1, )) - else: - keypoints = np.concatenate([r.pred_instances.keypoints - for r in pose_result]) - pts_scores = np.concatenate([r.pred_instances.keypoint_scores - for r in pose_result]) - - DetInst = namedtuple('DetInst', ['bboxes', 'scores', 'labels']) - PoseInst = namedtuple('PoseInst', ['keypoints', 'pts_scores']) - return DetInst(bboxes, scores, labels), PoseInst(keypoints, pts_scores) - - def inference_video(self, video_path): - """ Inference a video with detector and pose model - Return: - all_pose: a list of PoseInst, check the namedtuple definition - all_det: a list of DetInst - """ - video_reader = mmcv.VideoReader(video_path) - all_pose, all_det = [], [] - - count = self.video_count + 1 - for frame in tqdm(video_reader, desc=f'Inference video {count}'): - # inference with detector - det, pose = self.process_one_image(frame) - all_pose.append(pose) - all_det.append(det) - self.video_count += 1 - - return all_det, all_pose \ No newline at end of file diff --git a/spaces/DeepLabCut/MegaDetector_DeepLabCut/fonts/read.md b/spaces/DeepLabCut/MegaDetector_DeepLabCut/fonts/read.md deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Demosthene-OR/avr23-cds-translation/app.py b/spaces/Demosthene-OR/avr23-cds-translation/app.py deleted file mode 100644 index f798806e6ddb06329d4b58b6a4b2df21efb52f72..0000000000000000000000000000000000000000 --- a/spaces/Demosthene-OR/avr23-cds-translation/app.py +++ /dev/null @@ -1,80 +0,0 @@ -import streamlit as st -import os.path -from collections import OrderedDict -from streamlit_option_menu import option_menu -# Define TITLE, TEAM_MEMBERS and PROMOTION values, in config.py. -import config -from tabs.custom_vectorizer import custom_tokenizer, custom_preprocessor - -# Initialize a session state variable that tracks the sidebar state (either 'expanded' or 'collapsed'). -if 'sidebar_state' not in st.session_state: - st.session_state.sidebar_state = 'expanded' -else: - st.session_state.sidebar_state = 'auto' - -st.set_page_config ( - page_title=config.TITLE, - page_icon= "assets/faviconV2.png", - initial_sidebar_state=st.session_state.sidebar_state -) - -# Define the root folders depending on local/cloud run -thisfile = os.path.abspath(__file__) -if ('/' in thisfile): - os.chdir(os.path.dirname(thisfile)) - -# Tabs in the ./tabs folder, imported here. -from tabs import intro, exploration_tab, data_viz_tab, id_lang_tab, modelisation_dict_tab, modelisation_seq2seq_tab, game_tab - - -with open("style.css", "r") as f: - style = f.read() - -st.markdown(f"", unsafe_allow_html=True) - - -# Add tab in this ordered dict by -# passing the name in the sidebar as key and the imported tab -# as value as follow : -TABS = OrderedDict( - [ - (intro.sidebar_name, intro), - (exploration_tab.sidebar_name, exploration_tab), - (data_viz_tab.sidebar_name, data_viz_tab), - (id_lang_tab.sidebar_name, id_lang_tab), - (modelisation_dict_tab.sidebar_name, modelisation_dict_tab), - (modelisation_seq2seq_tab.sidebar_name, modelisation_seq2seq_tab), - (game_tab.sidebar_name, game_tab ), - ] -) - - -def run(): - - st.sidebar.image( - "assets/logo-datascientest.png", - width=200, - ) - with st.sidebar: - tab_name = option_menu(None, list(TABS.keys()), - # icons=['house', 'bi-binoculars', 'bi bi-graph-up', 'bi-chat-right-text','bi-book', 'bi-body-text'], menu_icon="cast", default_index=0, - icons=['house', 'binoculars', 'graph-up', 'search','book', 'chat-right-text', 'controller'], menu_icon="cast", default_index=0, - styles={"container": {"padding": "0!important","background-color": "#10b8dd", "border-radius": "0!important"}, - "nav-link": {"font-size": "1rem", "text-align": "left", "margin":"0em", "padding": "0em", - "padding-left": "0.2em", "--hover-color": "#eee", "font-weight": "400", - "font-family": "Source Sans Pro, sans-serif"} - }) - # tab_name = st.sidebar.radio("", list(TABS.keys()), 0) - st.sidebar.markdown("---") - st.sidebar.markdown(f"## {config.PROMOTION}") - - st.sidebar.markdown("### Team members:") - for member in config.TEAM_MEMBERS: - st.sidebar.markdown(member.sidebar_markdown(), unsafe_allow_html=True) - - tab = TABS[tab_name] - tab.run() - - -if __name__ == "__main__": - run() diff --git a/spaces/Detomo/ai-avatar-backend/app.js b/spaces/Detomo/ai-avatar-backend/app.js deleted file mode 100644 index c51a4be9f968b566b47584e61bf5def16655e710..0000000000000000000000000000000000000000 --- a/spaces/Detomo/ai-avatar-backend/app.js +++ /dev/null @@ -1,45 +0,0 @@ -var createError = require('http-errors'); -var express = require('express'); -var path = require('path'); -var cookieParser = require('cookie-parser'); -var logger = require('morgan'); -var cors = require('cors'); - -var indexRouter = require('./routes/index'); - -var app = express(); - - -// view engine setup -app.set('views', path.join(__dirname, 'views')); -app.set('view engine', 'pug'); - -var corsOptions = { - origin: '*' -}; -app.use(cors(corsOptions)); -app.use(logger('dev')); -app.use(express.json()); -app.use(express.urlencoded({ extended: false })); -app.use(cookieParser()); -app.use(express.static(path.join(__dirname, 'public'))); - -app.use('/', indexRouter); - -// catch 404 and forward to error handler -app.use(function(req, res, next) { - next(createError(404)); -}); - -// error handler -app.use(function(err, req, res, next) { - // set locals, only providing error in development - res.locals.message = err.message; - res.locals.error = req.app.get('env') === 'development' ? err : {}; - - // render the error page - res.status(err.status || 500); - res.render('error'); -}); - -module.exports = app; diff --git a/spaces/Dorado607/ChuanhuChatGPT/modules/models/StableLM.py b/spaces/Dorado607/ChuanhuChatGPT/modules/models/StableLM.py deleted file mode 100644 index f4affc3699e335f1e42bf5fc8c93e92a41d027fe..0000000000000000000000000000000000000000 --- a/spaces/Dorado607/ChuanhuChatGPT/modules/models/StableLM.py +++ /dev/null @@ -1,93 +0,0 @@ -import torch -from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer -import time -import numpy as np -from torch.nn import functional as F -import os -from .base_model import BaseLLMModel -from threading import Thread - -STABLELM_MODEL = None -STABLELM_TOKENIZER = None - - -class StopOnTokens(StoppingCriteria): - def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: - stop_ids = [50278, 50279, 50277, 1, 0] - for stop_id in stop_ids: - if input_ids[0][-1] == stop_id: - return True - return False - - -class StableLM_Client(BaseLLMModel): - def __init__(self, model_name, user_name="") -> None: - super().__init__(model_name=model_name, user=user_name) - global STABLELM_MODEL, STABLELM_TOKENIZER - print(f"Starting to load StableLM to memory") - if model_name == "StableLM": - model_name = "stabilityai/stablelm-tuned-alpha-7b" - else: - model_name = f"models/{model_name}" - if STABLELM_MODEL is None: - STABLELM_MODEL = AutoModelForCausalLM.from_pretrained( - model_name, torch_dtype=torch.float16).cuda() - if STABLELM_TOKENIZER is None: - STABLELM_TOKENIZER = AutoTokenizer.from_pretrained(model_name) - self.generator = pipeline( - 'text-generation', model=STABLELM_MODEL, tokenizer=STABLELM_TOKENIZER, device=0) - print(f"Sucessfully loaded StableLM to the memory") - self.system_prompt = """StableAssistant -- StableAssistant is A helpful and harmless Open Source AI Language Model developed by Stability and CarperAI. -- StableAssistant is excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user. -- StableAssistant is more than just an information source, StableAssistant is also able to write poetry, short stories, and make jokes. -- StableAssistant will refuse to participate in anything that could harm a human.""" - self.max_generation_token = 1024 - self.top_p = 0.95 - self.temperature = 1.0 - - def _get_stablelm_style_input(self): - history = self.history + [{"role": "assistant", "content": ""}] - print(history) - messages = self.system_prompt + \ - "".join(["".join(["<|USER|>"+history[i]["content"], "<|ASSISTANT|>"+history[i + 1]["content"]]) - for i in range(0, len(history), 2)]) - return messages - - def _generate(self, text, bad_text=None): - stop = StopOnTokens() - result = self.generator(text, max_new_tokens=self.max_generation_token, num_return_sequences=1, num_beams=1, do_sample=True, - temperature=self.temperature, top_p=self.top_p, top_k=1000, stopping_criteria=StoppingCriteriaList([stop])) - return result[0]["generated_text"].replace(text, "") - - def get_answer_at_once(self): - messages = self._get_stablelm_style_input() - return self._generate(messages), len(messages) - - def get_answer_stream_iter(self): - stop = StopOnTokens() - messages = self._get_stablelm_style_input() - - # model_inputs = tok([messages], return_tensors="pt")['input_ids'].cuda()[:, :4096-1024] - model_inputs = STABLELM_TOKENIZER( - [messages], return_tensors="pt").to("cuda") - streamer = TextIteratorStreamer( - STABLELM_TOKENIZER, timeout=10., skip_prompt=True, skip_special_tokens=True) - generate_kwargs = dict( - model_inputs, - streamer=streamer, - max_new_tokens=self.max_generation_token, - do_sample=True, - top_p=self.top_p, - top_k=1000, - temperature=self.temperature, - num_beams=1, - stopping_criteria=StoppingCriteriaList([stop]) - ) - t = Thread(target=STABLELM_MODEL.generate, kwargs=generate_kwargs) - t.start() - - partial_text = "" - for new_text in streamer: - partial_text += new_text - yield partial_text diff --git a/spaces/EPFL-VILAB/MultiMAE/mask2former/modeling/backbone/__init__.py b/spaces/EPFL-VILAB/MultiMAE/mask2former/modeling/backbone/__init__.py deleted file mode 100644 index 9020c2df23e2af280b7bb168b996ae9eaf312eb8..0000000000000000000000000000000000000000 --- a/spaces/EPFL-VILAB/MultiMAE/mask2former/modeling/backbone/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. diff --git a/spaces/Epoching/3D_Photo_Inpainting/networks.py b/spaces/Epoching/3D_Photo_Inpainting/networks.py deleted file mode 100644 index 4ec0c423a480543893459a78025c129ef4857e87..0000000000000000000000000000000000000000 --- a/spaces/Epoching/3D_Photo_Inpainting/networks.py +++ /dev/null @@ -1,501 +0,0 @@ -import torch -import torch.nn as nn -import numpy as np -import matplotlib.pyplot as plt -import torch.nn.functional as F - - -class BaseNetwork(nn.Module): - def __init__(self): - super(BaseNetwork, self).__init__() - - def init_weights(self, init_type='normal', gain=0.02): - ''' - initialize network's weights - init_type: normal | xavier | kaiming | orthogonal - https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/9451e70673400885567d08a9e97ade2524c700d0/models/networks.py#L39 - ''' - - def init_func(m): - classname = m.__class__.__name__ - if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1): - if init_type == 'normal': - nn.init.normal_(m.weight.data, 0.0, gain) - elif init_type == 'xavier': - nn.init.xavier_normal_(m.weight.data, gain=gain) - elif init_type == 'kaiming': - nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') - elif init_type == 'orthogonal': - nn.init.orthogonal_(m.weight.data, gain=gain) - - if hasattr(m, 'bias') and m.bias is not None: - nn.init.constant_(m.bias.data, 0.0) - - elif classname.find('BatchNorm2d') != -1: - nn.init.normal_(m.weight.data, 1.0, gain) - nn.init.constant_(m.bias.data, 0.0) - - self.apply(init_func) - -def weights_init(init_type='gaussian'): - def init_fun(m): - classname = m.__class__.__name__ - if (classname.find('Conv') == 0 or classname.find( - 'Linear') == 0) and hasattr(m, 'weight'): - if init_type == 'gaussian': - nn.init.normal_(m.weight, 0.0, 0.02) - elif init_type == 'xavier': - nn.init.xavier_normal_(m.weight, gain=math.sqrt(2)) - elif init_type == 'kaiming': - nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in') - elif init_type == 'orthogonal': - nn.init.orthogonal_(m.weight, gain=math.sqrt(2)) - elif init_type == 'default': - pass - else: - assert 0, "Unsupported initialization: {}".format(init_type) - if hasattr(m, 'bias') and m.bias is not None: - nn.init.constant_(m.bias, 0.0) - - return init_fun - -class PartialConv(nn.Module): - def __init__(self, in_channels, out_channels, kernel_size, stride=1, - padding=0, dilation=1, groups=1, bias=True): - super().__init__() - self.input_conv = nn.Conv2d(in_channels, out_channels, kernel_size, - stride, padding, dilation, groups, bias) - self.mask_conv = nn.Conv2d(in_channels, out_channels, kernel_size, - stride, padding, dilation, groups, False) - self.input_conv.apply(weights_init('kaiming')) - self.slide_winsize = in_channels * kernel_size * kernel_size - - torch.nn.init.constant_(self.mask_conv.weight, 1.0) - - # mask is not updated - for param in self.mask_conv.parameters(): - param.requires_grad = False - - def forward(self, input, mask): - # http://masc.cs.gmu.edu/wiki/partialconv - # C(X) = W^T * X + b, C(0) = b, D(M) = 1 * M + 0 = sum(M) - # W^T* (M .* X) / sum(M) + b = [C(M .* X) – C(0)] / D(M) + C(0) - output = self.input_conv(input * mask) - if self.input_conv.bias is not None: - output_bias = self.input_conv.bias.view(1, -1, 1, 1).expand_as( - output) - else: - output_bias = torch.zeros_like(output) - - with torch.no_grad(): - output_mask = self.mask_conv(mask) - - no_update_holes = output_mask == 0 - - mask_sum = output_mask.masked_fill_(no_update_holes, 1.0) - - output_pre = ((output - output_bias) * self.slide_winsize) / mask_sum + output_bias - output = output_pre.masked_fill_(no_update_holes, 0.0) - - new_mask = torch.ones_like(output) - new_mask = new_mask.masked_fill_(no_update_holes, 0.0) - - return output, new_mask - - -class PCBActiv(nn.Module): - def __init__(self, in_ch, out_ch, bn=True, sample='none-3', activ='relu', - conv_bias=False): - super().__init__() - if sample == 'down-5': - self.conv = PartialConv(in_ch, out_ch, 5, 2, 2, bias=conv_bias) - elif sample == 'down-7': - self.conv = PartialConv(in_ch, out_ch, 7, 2, 3, bias=conv_bias) - elif sample == 'down-3': - self.conv = PartialConv(in_ch, out_ch, 3, 2, 1, bias=conv_bias) - else: - self.conv = PartialConv(in_ch, out_ch, 3, 1, 1, bias=conv_bias) - - if bn: - self.bn = nn.BatchNorm2d(out_ch) - if activ == 'relu': - self.activation = nn.ReLU() - elif activ == 'leaky': - self.activation = nn.LeakyReLU(negative_slope=0.2) - - def forward(self, input, input_mask): - h, h_mask = self.conv(input, input_mask) - if hasattr(self, 'bn'): - h = self.bn(h) - if hasattr(self, 'activation'): - h = self.activation(h) - return h, h_mask - -class Inpaint_Depth_Net(nn.Module): - def __init__(self, layer_size=7, upsampling_mode='nearest'): - super().__init__() - in_channels = 4 - out_channels = 1 - self.freeze_enc_bn = False - self.upsampling_mode = upsampling_mode - self.layer_size = layer_size - self.enc_1 = PCBActiv(in_channels, 64, bn=False, sample='down-7', conv_bias=True) - self.enc_2 = PCBActiv(64, 128, sample='down-5', conv_bias=True) - self.enc_3 = PCBActiv(128, 256, sample='down-5') - self.enc_4 = PCBActiv(256, 512, sample='down-3') - for i in range(4, self.layer_size): - name = 'enc_{:d}'.format(i + 1) - setattr(self, name, PCBActiv(512, 512, sample='down-3')) - - for i in range(4, self.layer_size): - name = 'dec_{:d}'.format(i + 1) - setattr(self, name, PCBActiv(512 + 512, 512, activ='leaky')) - self.dec_4 = PCBActiv(512 + 256, 256, activ='leaky') - self.dec_3 = PCBActiv(256 + 128, 128, activ='leaky') - self.dec_2 = PCBActiv(128 + 64, 64, activ='leaky') - self.dec_1 = PCBActiv(64 + in_channels, out_channels, - bn=False, activ=None, conv_bias=True) - def add_border(self, input, mask_flag, PCONV=True): - with torch.no_grad(): - h = input.shape[-2] - w = input.shape[-1] - require_len_unit = 2 ** self.layer_size - residual_h = int(np.ceil(h / float(require_len_unit)) * require_len_unit - h) # + 2*require_len_unit - residual_w = int(np.ceil(w / float(require_len_unit)) * require_len_unit - w) # + 2*require_len_unit - enlarge_input = torch.zeros((input.shape[0], input.shape[1], h + residual_h, w + residual_w)).to(input.device) - if mask_flag: - if PCONV is False: - enlarge_input += 1.0 - enlarge_input = enlarge_input.clamp(0.0, 1.0) - else: - enlarge_input[:, 2, ...] = 0.0 - anchor_h = residual_h//2 - anchor_w = residual_w//2 - enlarge_input[..., anchor_h:anchor_h+h, anchor_w:anchor_w+w] = input - - return enlarge_input, [anchor_h, anchor_h+h, anchor_w, anchor_w+w] - - def forward_3P(self, mask, context, depth, edge, unit_length=128, cuda=None): - with torch.no_grad(): - input = torch.cat((depth, edge, context, mask), dim=1) - n, c, h, w = input.shape - residual_h = int(np.ceil(h / float(unit_length)) * unit_length - h) - residual_w = int(np.ceil(w / float(unit_length)) * unit_length - w) - anchor_h = residual_h//2 - anchor_w = residual_w//2 - enlarge_input = torch.zeros((n, c, h + residual_h, w + residual_w)).to(cuda) - enlarge_input[..., anchor_h:anchor_h+h, anchor_w:anchor_w+w] = input - # enlarge_input[:, 3] = 1. - enlarge_input[:, 3] - depth_output = self.forward(enlarge_input) - depth_output = depth_output[..., anchor_h:anchor_h+h, anchor_w:anchor_w+w] - # import pdb; pdb.set_trace() - - return depth_output - - def forward(self, input_feat, refine_border=False, sample=False, PCONV=True): - input = input_feat - input_mask = (input_feat[:, -2:-1] + input_feat[:, -1:]).clamp(0, 1).repeat(1, input.shape[1], 1, 1) - - vis_input = input.cpu().data.numpy() - vis_input_mask = input_mask.cpu().data.numpy() - H, W = input.shape[-2:] - if refine_border is True: - input, anchor = self.add_border(input, mask_flag=False) - input_mask, anchor = self.add_border(input_mask, mask_flag=True, PCONV=PCONV) - h_dict = {} # for the output of enc_N - h_mask_dict = {} # for the output of enc_N - h_dict['h_0'], h_mask_dict['h_0'] = input, input_mask - - h_key_prev = 'h_0' - for i in range(1, self.layer_size + 1): - l_key = 'enc_{:d}'.format(i) - h_key = 'h_{:d}'.format(i) - h_dict[h_key], h_mask_dict[h_key] = getattr(self, l_key)( - h_dict[h_key_prev], h_mask_dict[h_key_prev]) - h_key_prev = h_key - - h_key = 'h_{:d}'.format(self.layer_size) - h, h_mask = h_dict[h_key], h_mask_dict[h_key] - - for i in range(self.layer_size, 0, -1): - enc_h_key = 'h_{:d}'.format(i - 1) - dec_l_key = 'dec_{:d}'.format(i) - - h = F.interpolate(h, scale_factor=2, mode=self.upsampling_mode) - h_mask = F.interpolate(h_mask, scale_factor=2, mode='nearest') - - h = torch.cat([h, h_dict[enc_h_key]], dim=1) - h_mask = torch.cat([h_mask, h_mask_dict[enc_h_key]], dim=1) - h, h_mask = getattr(self, dec_l_key)(h, h_mask) - output = h - if refine_border is True: - h_mask = h_mask[..., anchor[0]:anchor[1], anchor[2]:anchor[3]] - output = output[..., anchor[0]:anchor[1], anchor[2]:anchor[3]] - - return output - -class Inpaint_Edge_Net(BaseNetwork): - def __init__(self, residual_blocks=8, init_weights=True): - super(Inpaint_Edge_Net, self).__init__() - in_channels = 7 - out_channels = 1 - self.encoder = [] - # 0 - self.encoder_0 = nn.Sequential( - nn.ReflectionPad2d(3), - spectral_norm(nn.Conv2d(in_channels=in_channels, out_channels=64, kernel_size=7, padding=0), True), - nn.InstanceNorm2d(64, track_running_stats=False), - nn.ReLU(True)) - # 1 - self.encoder_1 = nn.Sequential( - spectral_norm(nn.Conv2d(in_channels=64, out_channels=128, kernel_size=4, stride=2, padding=1), True), - nn.InstanceNorm2d(128, track_running_stats=False), - nn.ReLU(True)) - # 2 - self.encoder_2 = nn.Sequential( - spectral_norm(nn.Conv2d(in_channels=128, out_channels=256, kernel_size=4, stride=2, padding=1), True), - nn.InstanceNorm2d(256, track_running_stats=False), - nn.ReLU(True)) - # 3 - blocks = [] - for _ in range(residual_blocks): - block = ResnetBlock(256, 2) - blocks.append(block) - - self.middle = nn.Sequential(*blocks) - # + 3 - self.decoder_0 = nn.Sequential( - spectral_norm(nn.ConvTranspose2d(in_channels=256+256, out_channels=128, kernel_size=4, stride=2, padding=1), True), - nn.InstanceNorm2d(128, track_running_stats=False), - nn.ReLU(True)) - # + 2 - self.decoder_1 = nn.Sequential( - spectral_norm(nn.ConvTranspose2d(in_channels=128+128, out_channels=64, kernel_size=4, stride=2, padding=1), True), - nn.InstanceNorm2d(64, track_running_stats=False), - nn.ReLU(True)) - # + 1 - self.decoder_2 = nn.Sequential( - nn.ReflectionPad2d(3), - nn.Conv2d(in_channels=64+64, out_channels=out_channels, kernel_size=7, padding=0), - ) - - if init_weights: - self.init_weights() - - def add_border(self, input, channel_pad_1=None): - h = input.shape[-2] - w = input.shape[-1] - require_len_unit = 16 - residual_h = int(np.ceil(h / float(require_len_unit)) * require_len_unit - h) # + 2*require_len_unit - residual_w = int(np.ceil(w / float(require_len_unit)) * require_len_unit - w) # + 2*require_len_unit - enlarge_input = torch.zeros((input.shape[0], input.shape[1], h + residual_h, w + residual_w)).to(input.device) - if channel_pad_1 is not None: - for channel in channel_pad_1: - enlarge_input[:, channel] = 1 - anchor_h = residual_h//2 - anchor_w = residual_w//2 - enlarge_input[..., anchor_h:anchor_h+h, anchor_w:anchor_w+w] = input - - return enlarge_input, [anchor_h, anchor_h+h, anchor_w, anchor_w+w] - - def forward_3P(self, mask, context, rgb, disp, edge, unit_length=128, cuda=None): - with torch.no_grad(): - input = torch.cat((rgb, disp/disp.max(), edge, context, mask), dim=1) - n, c, h, w = input.shape - residual_h = int(np.ceil(h / float(unit_length)) * unit_length - h) - residual_w = int(np.ceil(w / float(unit_length)) * unit_length - w) - anchor_h = residual_h//2 - anchor_w = residual_w//2 - enlarge_input = torch.zeros((n, c, h + residual_h, w + residual_w)).to(cuda) - enlarge_input[..., anchor_h:anchor_h+h, anchor_w:anchor_w+w] = input - edge_output = self.forward(enlarge_input) - edge_output = edge_output[..., anchor_h:anchor_h+h, anchor_w:anchor_w+w] - - return edge_output - - def forward(self, x, refine_border=False): - if refine_border: - x, anchor = self.add_border(x, [5]) - x1 = self.encoder_0(x) - x2 = self.encoder_1(x1) - x3 = self.encoder_2(x2) - x4 = self.middle(x3) - x5 = self.decoder_0(torch.cat((x4, x3), dim=1)) - x6 = self.decoder_1(torch.cat((x5, x2), dim=1)) - x7 = self.decoder_2(torch.cat((x6, x1), dim=1)) - x = torch.sigmoid(x7) - if refine_border: - x = x[..., anchor[0]:anchor[1], anchor[2]:anchor[3]] - - return x - -class Inpaint_Color_Net(nn.Module): - def __init__(self, layer_size=7, upsampling_mode='nearest', add_hole_mask=False, add_two_layer=False, add_border=False): - super().__init__() - self.freeze_enc_bn = False - self.upsampling_mode = upsampling_mode - self.layer_size = layer_size - in_channels = 6 - self.enc_1 = PCBActiv(in_channels, 64, bn=False, sample='down-7') - self.enc_2 = PCBActiv(64, 128, sample='down-5') - self.enc_3 = PCBActiv(128, 256, sample='down-5') - self.enc_4 = PCBActiv(256, 512, sample='down-3') - self.enc_5 = PCBActiv(512, 512, sample='down-3') - self.enc_6 = PCBActiv(512, 512, sample='down-3') - self.enc_7 = PCBActiv(512, 512, sample='down-3') - - self.dec_7 = PCBActiv(512+512, 512, activ='leaky') - self.dec_6 = PCBActiv(512+512, 512, activ='leaky') - - self.dec_5A = PCBActiv(512 + 512, 512, activ='leaky') - self.dec_4A = PCBActiv(512 + 256, 256, activ='leaky') - self.dec_3A = PCBActiv(256 + 128, 128, activ='leaky') - self.dec_2A = PCBActiv(128 + 64, 64, activ='leaky') - self.dec_1A = PCBActiv(64 + in_channels, 3, bn=False, activ=None, conv_bias=True) - ''' - self.dec_5B = PCBActiv(512 + 512, 512, activ='leaky') - self.dec_4B = PCBActiv(512 + 256, 256, activ='leaky') - self.dec_3B = PCBActiv(256 + 128, 128, activ='leaky') - self.dec_2B = PCBActiv(128 + 64, 64, activ='leaky') - self.dec_1B = PCBActiv(64 + 4, 1, bn=False, activ=None, conv_bias=True) - ''' - def cat(self, A, B): - return torch.cat((A, B), dim=1) - - def upsample(self, feat, mask): - feat = F.interpolate(feat, scale_factor=2, mode=self.upsampling_mode) - mask = F.interpolate(mask, scale_factor=2, mode='nearest') - - return feat, mask - - def forward_3P(self, mask, context, rgb, edge, unit_length=128, cuda=None): - with torch.no_grad(): - input = torch.cat((rgb, edge, context, mask), dim=1) - n, c, h, w = input.shape - residual_h = int(np.ceil(h / float(unit_length)) * unit_length - h) # + 128 - residual_w = int(np.ceil(w / float(unit_length)) * unit_length - w) # + 256 - anchor_h = residual_h//2 - anchor_w = residual_w//2 - enlarge_input = torch.zeros((n, c, h + residual_h, w + residual_w)).to(cuda) - enlarge_input[..., anchor_h:anchor_h+h, anchor_w:anchor_w+w] = input - # enlarge_input[:, 3] = 1. - enlarge_input[:, 3] - enlarge_input = enlarge_input.to(cuda) - rgb_output = self.forward(enlarge_input) - rgb_output = rgb_output[..., anchor_h:anchor_h+h, anchor_w:anchor_w+w] - - return rgb_output - - def forward(self, input, add_border=False): - input_mask = (input[:, -2:-1] + input[:, -1:]).clamp(0, 1) - H, W = input.shape[-2:] - f_0, h_0 = input, input_mask.repeat((1,input.shape[1],1,1)) - f_1, h_1 = self.enc_1(f_0, h_0) - f_2, h_2 = self.enc_2(f_1, h_1) - f_3, h_3 = self.enc_3(f_2, h_2) - f_4, h_4 = self.enc_4(f_3, h_3) - f_5, h_5 = self.enc_5(f_4, h_4) - f_6, h_6 = self.enc_6(f_5, h_5) - f_7, h_7 = self.enc_7(f_6, h_6) - - o_7, k_7 = self.upsample(f_7, h_7) - o_6, k_6 = self.dec_7(self.cat(o_7, f_6), self.cat(k_7, h_6)) - o_6, k_6 = self.upsample(o_6, k_6) - o_5, k_5 = self.dec_6(self.cat(o_6, f_5), self.cat(k_6, h_5)) - o_5, k_5 = self.upsample(o_5, k_5) - o_5A, k_5A = o_5, k_5 - o_5B, k_5B = o_5, k_5 - ############### - o_4A, k_4A = self.dec_5A(self.cat(o_5A, f_4), self.cat(k_5A, h_4)) - o_4A, k_4A = self.upsample(o_4A, k_4A) - o_3A, k_3A = self.dec_4A(self.cat(o_4A, f_3), self.cat(k_4A, h_3)) - o_3A, k_3A = self.upsample(o_3A, k_3A) - o_2A, k_2A = self.dec_3A(self.cat(o_3A, f_2), self.cat(k_3A, h_2)) - o_2A, k_2A = self.upsample(o_2A, k_2A) - o_1A, k_1A = self.dec_2A(self.cat(o_2A, f_1), self.cat(k_2A, h_1)) - o_1A, k_1A = self.upsample(o_1A, k_1A) - o_0A, k_0A = self.dec_1A(self.cat(o_1A, f_0), self.cat(k_1A, h_0)) - - return torch.sigmoid(o_0A) - - def train(self, mode=True): - """ - Override the default train() to freeze the BN parameters - """ - super().train(mode) - if self.freeze_enc_bn: - for name, module in self.named_modules(): - if isinstance(module, nn.BatchNorm2d) and 'enc' in name: - module.eval() - -class Discriminator(BaseNetwork): - def __init__(self, use_sigmoid=True, use_spectral_norm=True, init_weights=True, in_channels=None): - super(Discriminator, self).__init__() - self.use_sigmoid = use_sigmoid - self.conv1 = self.features = nn.Sequential( - spectral_norm(nn.Conv2d(in_channels=in_channels, out_channels=64, kernel_size=4, stride=2, padding=1, bias=not use_spectral_norm), use_spectral_norm), - nn.LeakyReLU(0.2, inplace=True), - ) - - self.conv2 = nn.Sequential( - spectral_norm(nn.Conv2d(in_channels=64, out_channels=128, kernel_size=4, stride=2, padding=1, bias=not use_spectral_norm), use_spectral_norm), - nn.LeakyReLU(0.2, inplace=True), - ) - - self.conv3 = nn.Sequential( - spectral_norm(nn.Conv2d(in_channels=128, out_channels=256, kernel_size=4, stride=2, padding=1, bias=not use_spectral_norm), use_spectral_norm), - nn.LeakyReLU(0.2, inplace=True), - ) - - self.conv4 = nn.Sequential( - spectral_norm(nn.Conv2d(in_channels=256, out_channels=512, kernel_size=4, stride=1, padding=1, bias=not use_spectral_norm), use_spectral_norm), - nn.LeakyReLU(0.2, inplace=True), - ) - - self.conv5 = nn.Sequential( - spectral_norm(nn.Conv2d(in_channels=512, out_channels=1, kernel_size=4, stride=1, padding=1, bias=not use_spectral_norm), use_spectral_norm), - ) - - if init_weights: - self.init_weights() - - def forward(self, x): - conv1 = self.conv1(x) - conv2 = self.conv2(conv1) - conv3 = self.conv3(conv2) - conv4 = self.conv4(conv3) - conv5 = self.conv5(conv4) - - outputs = conv5 - if self.use_sigmoid: - outputs = torch.sigmoid(conv5) - - return outputs, [conv1, conv2, conv3, conv4, conv5] - -class ResnetBlock(nn.Module): - def __init__(self, dim, dilation=1): - super(ResnetBlock, self).__init__() - self.conv_block = nn.Sequential( - nn.ReflectionPad2d(dilation), - spectral_norm(nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=3, padding=0, dilation=dilation, bias=not True), True), - nn.InstanceNorm2d(dim, track_running_stats=False), - nn.LeakyReLU(negative_slope=0.2), - - nn.ReflectionPad2d(1), - spectral_norm(nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=3, padding=0, dilation=1, bias=not True), True), - nn.InstanceNorm2d(dim, track_running_stats=False), - ) - - def forward(self, x): - out = x + self.conv_block(x) - - # Remove ReLU at the end of the residual block - # http://torch.ch/blog/2016/02/04/resnets.html - - return out - - -def spectral_norm(module, mode=True): - if mode: - return nn.utils.spectral_norm(module) - - return module diff --git a/spaces/EsoCode/text-generation-webui/modules/relative_imports.py b/spaces/EsoCode/text-generation-webui/modules/relative_imports.py deleted file mode 100644 index 3c0eb56b77c6cb6b38fdbdeebabe9ad3b8d91b97..0000000000000000000000000000000000000000 --- a/spaces/EsoCode/text-generation-webui/modules/relative_imports.py +++ /dev/null @@ -1,13 +0,0 @@ -import sys -from pathlib import Path - - -class RelativeImport: - def __init__(self, path): - self.import_path = Path(path) - - def __enter__(self): - sys.path.insert(0, str(self.import_path)) - - def __exit__(self, exc_type, exc_value, traceback): - sys.path.remove(str(self.import_path)) diff --git a/spaces/Faridmaruf/rvc-genshin-v2/lib/infer_pack/models.py b/spaces/Faridmaruf/rvc-genshin-v2/lib/infer_pack/models.py deleted file mode 100644 index 3665d03bc0514a6ed07d3372ea24717dae1e0a65..0000000000000000000000000000000000000000 --- a/spaces/Faridmaruf/rvc-genshin-v2/lib/infer_pack/models.py +++ /dev/null @@ -1,1142 +0,0 @@ -import math, pdb, os -from time import time as ttime -import torch -from torch import nn -from torch.nn import functional as F -from lib.infer_pack import modules -from lib.infer_pack import attentions -from lib.infer_pack import commons -from lib.infer_pack.commons import init_weights, get_padding -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm -from lib.infer_pack.commons import init_weights -import numpy as np -from lib.infer_pack import commons - - -class TextEncoder256(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class TextEncoder768(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(768, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__( - self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0, - ): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer( - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - mean_only=True, - ) - ) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - def remove_weight_norm(self): - for i in range(self.n_flows): - self.flows[i * 2].remove_weight_norm() - - -class PosteriorEncoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN( - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -class Generator(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=0, - ): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class SineGen(torch.nn.Module): - """Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__( - self, - samp_rate, - harmonic_num=0, - sine_amp=0.1, - noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False, - ): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv - - def forward(self, f0, upp): - """sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0 = f0[:, None].transpose(1, 2) - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * ( - idx + 2 - ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化 - rand_ini = torch.rand( - f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device - ) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化 - tmp_over_one *= upp - tmp_over_one = F.interpolate( - tmp_over_one.transpose(2, 1), - scale_factor=upp, - mode="linear", - align_corners=True, - ).transpose(2, 1) - rad_values = F.interpolate( - rad_values.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose( - 2, 1 - ) ####### - tmp_over_one %= 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - sine_waves = torch.sin( - torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi - ) - sine_waves = sine_waves * self.sine_amp - uv = self._f02uv(f0) - uv = F.interpolate( - uv.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose(2, 1) - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleHnNSF(torch.nn.Module): - """SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__( - self, - sampling_rate, - harmonic_num=0, - sine_amp=0.1, - add_noise_std=0.003, - voiced_threshod=0, - is_half=True, - ): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - self.is_half = is_half - # to produce sine waveforms - self.l_sin_gen = SineGen( - sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod - ) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x, upp=None): - sine_wavs, uv, _ = self.l_sin_gen(x, upp) - if self.is_half: - sine_wavs = sine_wavs.half() - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - return sine_merge, None, None # noise, uv - - -class GeneratorNSF(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - sr, - is_half=False, - ): - super(GeneratorNSF, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates)) - self.m_source = SourceModuleHnNSF( - sampling_rate=sr, harmonic_num=0, is_half=is_half - ) - self.noise_convs = nn.ModuleList() - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - c_cur = upsample_initial_channel // (2 ** (i + 1)) - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - if i + 1 < len(upsample_rates): - stride_f0 = np.prod(upsample_rates[i + 1 :]) - self.noise_convs.append( - Conv1d( - 1, - c_cur, - kernel_size=stride_f0 * 2, - stride=stride_f0, - padding=stride_f0 // 2, - ) - ) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - self.upp = np.prod(upsample_rates) - - def forward(self, x, f0, g=None): - har_source, noi_source, uv = self.m_source(f0, self.upp) - har_source = har_source.transpose(1, 2) - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -sr2sr = { - "32k": 32000, - "40k": 40000, - "48k": 48000, -} - - -class SynthesizerTrnMs256NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - nsff0 = nsff0[:, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs768NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - nsff0 = nsff0[:, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs256NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs768NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, rate=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - if rate: - head = int(z_p.shape[2] * rate) - z_p = z_p[:, :, -head:] - x_mask = x_mask[:, :, -head:] - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec(z * x_mask, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11, 17] - # periods = [3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class MultiPeriodDiscriminatorV2(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminatorV2, self).__init__() - # periods = [2, 3, 5, 7, 11, 17] - periods = [2, 3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ] - ) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f( - Conv2d( - 1, - 32, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 32, - 128, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 128, - 512, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 512, - 1024, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 1024, - 1024, - (kernel_size, 1), - 1, - padding=(get_padding(kernel_size, 1), 0), - ) - ), - ] - ) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap diff --git a/spaces/FedeFT/Head_Pose_Estimation_and_LAEO_computation/ai/detection.py b/spaces/FedeFT/Head_Pose_Estimation_and_LAEO_computation/ai/detection.py deleted file mode 100644 index 3355f2103207dd7d04273199eb5c829b92a342cc..0000000000000000000000000000000000000000 --- a/spaces/FedeFT/Head_Pose_Estimation_and_LAEO_computation/ai/detection.py +++ /dev/null @@ -1,293 +0,0 @@ -from utils.my_utils import rescale_bb, rescale_key_points, delete_items_from_array_aux, enlarge_bb -from utils.labels import coco_category_index, face_category_index -import time -import numpy as np - - -def detect(model, image, min_score_thresh, new_old_shape): - """ - Detect objects in the image running the model - - Args: - :model (tensorflow.python.saved_model): The Tensorflow object detection model - :image (numpy.ndarray): The image that is given as input to the object detection model - :min_score_threshold (float): The minimum score for the detections (detections with a score lower than this value will be discarded) - :new_old_shape (tuple): The first element represents the right padding (applied by resize_preserving_ar() function); - the second element represents the bottom padding (applied by resize_preserving_ar() function) and - the third element is a tuple that is the shape of the image after resizing without the padding (this is useful for - the coordinates changes that we have to do) - - Returns: - :detections (dict): dictionary with detection scores, classes, centroids and bounding box coordinates ordered by score in descending order - :inference_time (float): inference time for one image expressed in seconds - """ - image = np.array(image).astype(np.uint8) - input_tensor = np.expand_dims(image, axis=0) - - start_time = time.time() - det = model(input_tensor) - end_time = time.time() - - detections = filter_detections(det, min_score_thresh, image.shape, new_old_shape) - inference_time = end_time - start_time - return detections, inference_time - - -def filter_detections(detections, min_score_thresh, shape, new_old_shape=None): - """ - Filter the detections based on a minimum threshold value and modify the bounding box coordinates if the image was resized for the detection - - Args: - :detections (dict): The dictionary that outputs the model - :min_score_thresh (float): The minimum score for the detections (detections with a score lower than this value will be discarded) - :shape (tuple): The shape of the image - :new_old_shape (tuple): The first element represents the right padding (applied by resize_preserving_ar() function); - the second element represents the bottom padding (applied by resize_preserving_ar() function) and - the third element is a tuple that is the shape of the image after resizing without the padding (this is useful for - the coordinates changes that we have to do) - (default is None) - - Returns: - :filtered_detections (dict): dictionary with detection scores, classes, centroids and bounding box coordinates ordered by score in descending order - """ - allowed_categories = ["person"] - # allowed_categories = ["Face"] # if ssd face model - - im_height, im_width, _ = shape - center_net = False - - classes = detections['detection_classes'][0].numpy().astype(np.int32) - boxes = detections['detection_boxes'][0].numpy() - scores = detections['detection_scores'][0].numpy() - key_points_score = None - key_points = None - - if 'detection_keypoint_scores' in detections: - key_points_score = detections['detection_keypoint_scores'][0].numpy() - key_points = detections['detection_keypoints'][0].numpy() - center_net = True - - sorted_index = np.argsort(scores)[::-1] - scores = scores[sorted_index] - boxes = boxes[sorted_index] - classes = classes[sorted_index] - - i = 0 - while i < 10000: - if scores[i] < min_score_thresh: # sorted - break - if coco_category_index[classes[i]]["name"] in allowed_categories: - i += 1 - else: - scores = np.delete(scores, i) - boxes = delete_items_from_array_aux(boxes, i) - classes = np.delete(classes, i) - if center_net: - key_points_score = delete_items_from_array_aux(key_points_score, i) - key_points = delete_items_from_array_aux(key_points, i) - - filtered_detections = dict() - filtered_detections['detection_classes'] = classes[:i] - - rescaled_boxes = (boxes[:i]) - - if new_old_shape: - rescale_bb(rescaled_boxes, new_old_shape, im_width, im_height) - if center_net: - rescaled_key_points = key_points[:i] - rescale_key_points(rescaled_key_points, new_old_shape, im_width, im_height) - - filtered_detections['detection_boxes'] = rescaled_boxes - filtered_detections['detection_scores'] = scores[:i] - - if center_net: - filtered_detections['detection_keypoint_scores'] = key_points_score[:i] - filtered_detections['detection_keypoints'] = rescaled_key_points - - aux_centroids = [] - for bb in boxes[:i]: # y_min, x_min, y_max, x_max - centroid_x = (bb[1] + bb[3]) / 2. - centroid_y = (bb[0] + bb[2]) / 2. - aux_centroids.append([centroid_x, centroid_y]) - - filtered_detections['detection_boxes_centroid'] = np.array(aux_centroids) - - return filtered_detections - - -# def detect_head_pose_ssd_face(image, detections, model, output_image): -# """ -# Detect objects in the image running the model -# -# Args: -# :model (tensorflow.python.saved_model): The Tensorflow object detection model -# :image (numpy.ndarray): The image that is given as input to the object detection model -# :min_score_threshold (float): The minimum score for the detections (detections with a score lower than this value will be discarded) -# :new_old_shape (tuple): The first element represents the right padding (applied by resize_preserving_ar() function); -# the second element represents the bottom padding (applied by resize_preserving_ar() function) and -# the third element is a tuple that is the shape of the image after resizing without the padding (this is useful for -# the coordinates changes that we have to do) -# -# Returns: -# :detections (dict): dictionary with detection scores, classes, centroids and bounding box coordinates ordered by score in descending order -# :inference_time (float): inference time for one image expressed in seconds -# """ -# -# im_width, im_height = image.shape[1], image.shape[0] -# classes = detections['detection_classes'] -# boxes = detections['detection_boxes'] -# -# i = 0 -# while i < len(classes): # for each bb (person) -# [y_min_perc, x_min_perc, y_max_perc, x_max_perc] = boxes[i] -# (x_min, x_max, y_min, y_max) = (int(x_min_perc * im_width), int(x_max_perc * im_width), int(y_min_perc * im_height), int(y_max_perc * im_height)) -# -# y_min_face, x_min_face, y_max_face, x_max_face = enlarge_bb(y_min, x_min, y_max, x_max, im_width, im_height) -# img_face = image[y_min_face:y_max_face, x_min_face:x_max_face] -# img_face = cv2.cvtColor(img_face, cv2.COLOR_BGR2RGB) -# -# # img_face, _ = resize_preserving_ar(img_face, (224, 224)) -# img_face = cv2.resize(img_face, (224, 224)) -# -# img_face = np.expand_dims(img_face, axis=0) -# yaw, pitch, roll = model.get_angle(img_face) -# -# cv2.rectangle(output_image, (x_min_face, y_min_face), (x_max_face, y_max_face), (0, 0, 0), 2) -# # cv2.imshow("aa", output_image) -# # cv2.waitKey(0) -# # to original image coordinates -# x_min_orig, x_max_orig, y_min_orig, y_max_orig = x_min_face, x_max_face, y_min_face, y_max_face # x_min_face + x_min, x_max_face + x_min, y_min_face + y_min, y_max_face+y_min -# draw_axis(output_image, yaw, pitch, roll, tdx=(x_min_orig + x_max_orig) / 2, tdy=(y_min_orig + y_max_orig) / 2, -# size=abs(x_max_face - x_min_face)) -# -# i += 1 -# -# return output_image -# -# -# def detect_head_pose(image, detections, model, detector, output_image): -# """ -# Detect the pose of the head given an image and the person detected -# -# Args: -# :image (numpy.ndarray): The image that is given as input -# :detections (dict): dictionary with detection scores, classes, centroids and bounding box coordinates ordered by score in descending order -# :model (src.ai.whenet.WHENet): model to detect the pose of the head -# :detector (_dlib_pybind11.cnn_face_detection_model_v1): model to detect the face -# :output_image (numpy.ndarray): The output image where the drawings of the head pose will be done -# -# Returns: -# :output_image (numpy.ndarray): The output image with the drawings of the head pose -# """ -# -# im_width, im_height = image.shape[1], image.shape[0] -# classes = detections['detection_classes'] -# boxes = detections['detection_boxes'] -# -# i = 0 -# while i < len(classes): # for each bb (person) -# [y_min_perc, x_min_perc, y_max_perc, x_max_perc] = boxes[i] -# (x_min, x_max, y_min, y_max) = (int(x_min_perc * im_width), int(x_max_perc * im_width), int(y_min_perc * im_height), int(y_max_perc * im_height)) -# -# img_person = image[y_min:y_max, x_min:x_max] -# -# # start_time = time.time() -# # img_face = img_person[:int(img_person.shape[0]/2), :] -# rect_faces = detection_dlib_cnn_face(detector, img_person) -# # # rect_faces = detection_dlib_face(detector, img_person) -# # end_time = time.time() -# # # print("Inference time dlib cnn: ", end_time - start_time) -# -# if len(rect_faces) > 0: # if the detector able to find faces -# -# x_min_face, y_min_face, x_max_face, y_max_face = rect_faces[0][0], rect_faces[0][1], rect_faces[0][2], rect_faces[0][3] # rect_faces[0][1] -# y_min_face, x_min_face, y_max_face, x_max_face = enlarge_bb(y_min_face, x_min_face, y_max_face, x_max_face, im_width, im_height) -# -# img_face = img_person[y_min_face:y_max_face, x_min_face:x_max_face] -# -# img_face = cv2.cvtColor(img_face, cv2.COLOR_BGR2RGB) -# -# # img_face, _ = resize_preserving_ar(img_face, (224, 224)) -# img_face = cv2.resize(img_face, (224, 224)) -# -# img_face = np.expand_dims(img_face, axis=0) -# # start_time = time.time() -# yaw, pitch, roll = model.get_angle(img_face) -# # end_time = time.time() -# # print("Inference time whenet: ", end_time - start_time) -# -# cv2.rectangle(output_image, (x_min_face + x_min, y_min_face + y_min), (x_max_face + x_min, y_max_face + y_min), (0, 0, 0), 2) -# # to original image coordinates -# x_min_orig, x_max_orig, y_min_orig, y_max_orig = x_min_face + x_min, x_max_face + x_min, y_min_face + y_min, y_max_face+y_min -# draw_axis(output_image, yaw, pitch, roll, tdx=(x_min_orig + x_max_orig) / 2, tdy=(y_min_orig + y_max_orig) / 2, -# size=abs(x_max_face - x_min_face)) -# # draw_axis(image, yaw, pitch, roll, tdx=(x_min_face + x_max_face) / 2, tdy=(y_min_face + y_max_face) / 2, -# # size=abs(x_max_face - x_min_face)) -# else: # otherwise -# # print("SHAPE ", img_person.shape) -# # x_min_face, y_min_face, x_max_face, y_max_face = int(img_person.shape[1]/8), 0, int(img_person.shape[1]-img_person.shape[1]/9), int(img_person.shape[0]/3) -# # img_face = img_person[y_min_face:y_max_face, x_min_face:x_max_face] -# # # img_face = resize_preserving_ar(img_face, (224, 224)) -# # img_face = cv2.resize(img_face, (224, 224)) -# # cv2.imshow("face_rsz", img_face) -# # cv2.waitKey(0) -# # img_face = np.expand_dims(img_face, axis=0) -# # # cv2.rectangle(img_face, (x_min_face, y_min_face), (x_max_face, y_max_face), (0, 0, 0), 1) -# # yaw, pitch, roll = model.get_angle(img_face) -# # print("YPR", yaw, pitch, roll) -# # draw_axis(img_person, yaw, pitch, roll, tdx=(x_min_face+x_max_face)/2, tdy=(y_min_face+y_max_face)/2, size=abs(x_max_face-x_min_face)) -# # cv2.imshow('output', img_person) -# # cv2.waitKey(0) -# i += 1 -# continue -# -# i += 1 -# -# return output_image - - -# def detect_head_pose_whenet(model, person, image): -# -# """ -# Detect the head pose using the whenet model and draw on image -# -# Args: -# :model (): Whenet model -# :person (): -# :image (numpy.ndarray): The image that is given as input -# -# Returns: -# : -# """ -# -# faces_coordinates = person.get_faces_coordinates()[-1] -# -# y_min, x_min, y_max, x_max = faces_coordinates -# -# image_face = image[y_min:y_max, x_min:x_max] -# img_face = cv2.cvtColor(image_face, cv2.COLOR_BGR2RGB) -# -# # img_face, _ = resize_preserving_ar(img_face, (224, 224)) -# img_face = cv2.resize(img_face, (224, 224)) -# -# img_face = np.expand_dims(img_face, axis=0) -# # start_time = time.time() -# yaw, pitch, roll = model.get_angle(img_face) -# -# # end_time = tiypme.time() -# # print("Inference time whenet: ", end_time - start_time) -# # cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 0, 0), 2) -# -# # to original image coordinates -# x_min_orig, x_max_orig, y_min_orig, y_max_orig = x_min, x_max, y_min, y_max -# vector_norm = draw_axis(image, yaw, pitch, roll, tdx=(x_min_orig + x_max_orig) / 2, tdy=(y_min_orig + y_max_orig) / 2, -# size=abs(x_max - x_min)) -# -# -# visualize_vector(image, [int((x_min_orig + x_max_orig) / 2), int((y_min_orig + y_max_orig) / 2)], vector_norm) -# -# person.update_poses_ypr([yaw, pitch, roll]) -# person.update_poses_vector_norm(vector_norm) - - # cv2.imshow("", image) - # cv2.waitKey(0) diff --git a/spaces/GXSA/bingo/src/pages/api/image.ts b/spaces/GXSA/bingo/src/pages/api/image.ts deleted file mode 100644 index 26fdb31076a9c71e70d1725a630844b27f5a3221..0000000000000000000000000000000000000000 --- a/spaces/GXSA/bingo/src/pages/api/image.ts +++ /dev/null @@ -1,38 +0,0 @@ -'use server' - -import { NextApiRequest, NextApiResponse } from 'next' -import { debug } from '@/lib/isomorphic' -import { createHeaders } from '@/lib/utils' -import { createImage } from '@/lib/bots/bing/utils' - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - const { prompt, id } = req.query - if (!prompt) { - return res.json({ - result: { - value: 'Image', - message: 'No Prompt' - } - }) - } - try { - const headers = createHeaders(req.cookies, 'image') - - debug('headers', headers) - const response = await createImage(String(prompt), String(id), { - ...headers, - 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32', - }) - res.writeHead(200, { - 'Content-Type': 'text/plain; charset=UTF-8', - }) - return res.end(response) - } catch (e) { - return res.json({ - result: { - value: 'Error', - message: `${e}` - } - }) - } -} diff --git a/spaces/GabeIsHaxkee/E/README.md b/spaces/GabeIsHaxkee/E/README.md deleted file mode 100644 index 5b4a36bea024ef81a72ddc6568be0e63fc1cc4c4..0000000000000000000000000000000000000000 --- a/spaces/GabeIsHaxkee/E/README.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Shiny for Python template -emoji: 🌍 -colorFrom: yellow -colorTo: indigo -sdk: docker -pinned: false -license: deepfloyd-if-license ---- - -This is a templated Space for [Shiny for Python](https://shiny.rstudio.com/py/). - - -To get started with a new app do the following: - -1) Install Shiny with `pip install shiny` -2) Create a new app with `shiny create .` -3) Then run the app with `shiny run --reload` - -To learn more about this framework please see the [Documentation](https://shiny.rstudio.com/py/docs/overview.html). diff --git a/spaces/GaenKoki/voicevox/speaker_info/35b2c544-660e-401e-b503-0e14c635303a/policy.md b/spaces/GaenKoki/voicevox/speaker_info/35b2c544-660e-401e-b503-0e14c635303a/policy.md deleted file mode 100644 index 32a15afd7544b8cfecb727231432376aa8c9917e..0000000000000000000000000000000000000000 --- a/spaces/GaenKoki/voicevox/speaker_info/35b2c544-660e-401e-b503-0e14c635303a/policy.md +++ /dev/null @@ -1,3 +0,0 @@ -dummy3 policy - -https://voicevox.hiroshiba.jp/ diff --git a/spaces/Gen-Sim/Gen-Sim/cliport/tasks/cameras.py b/spaces/Gen-Sim/Gen-Sim/cliport/tasks/cameras.py deleted file mode 100644 index 882c8b7e4e0a24925da393ac1bf4ea0381f832c4..0000000000000000000000000000000000000000 --- a/spaces/Gen-Sim/Gen-Sim/cliport/tasks/cameras.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Camera configs.""" - -import numpy as np -import pybullet as p - - -class RealSenseD415(): - """Default configuration with 3 RealSense RGB-D cameras.""" - - # Mimic RealSense D415 RGB-D camera parameters. - image_size = (480, 640) - intrinsics = (450., 0, 320., 0, 450., 240., 0, 0, 1) - - # Set default camera poses. - front_position = (1., 0, 0.75) - front_rotation = (np.pi / 4, np.pi, -np.pi / 2) - front_rotation = p.getQuaternionFromEuler(front_rotation) - left_position = (0, 0.5, 0.75) - left_rotation = (np.pi / 4.5, np.pi, np.pi / 4) - left_rotation = p.getQuaternionFromEuler(left_rotation) - right_position = (0, -0.5, 0.75) - right_rotation = (np.pi / 4.5, np.pi, 3 * np.pi / 4) - right_rotation = p.getQuaternionFromEuler(right_rotation) - - # Default camera configs. - CONFIG = [{ - 'image_size': image_size, - 'intrinsics': intrinsics, - 'position': front_position, - 'rotation': front_rotation, - 'zrange': (0.01, 10.), - 'noise': False - }, { - 'image_size': image_size, - 'intrinsics': intrinsics, - 'position': left_position, - 'rotation': left_rotation, - 'zrange': (0.01, 10.), - 'noise': False - }, { - 'image_size': image_size, - 'intrinsics': intrinsics, - 'position': right_position, - 'rotation': right_rotation, - 'zrange': (0.01, 10.), - 'noise': False - }] - - -class Oracle(): - """Top-down noiseless image used only by the oracle demonstrator.""" - - # Near-orthographic projection. - image_size = (480, 640) - intrinsics = (63e4, 0, 320., 0, 63e4, 240., 0, 0, 1) - position = (0.5, 0, 1000.) - rotation = p.getQuaternionFromEuler((0, np.pi, -np.pi / 2)) - - # Camera config. - CONFIG = [{ - 'image_size': image_size, - 'intrinsics': intrinsics, - 'position': position, - 'rotation': rotation, - 'zrange': (999.7, 1001.), - 'noise': False - }] - - -class RS200Gazebo(): - """Gazebo Camera""" - - # Near-orthographic projection. - image_size = (480, 640) - intrinsics = (554.3826904296875, 0.0, 320.0, 0.0, 554.3826904296875, 240.0, 0.0, 0.0, 1.0) - position = (0.5, 0, 1.0) - rotation = p.getQuaternionFromEuler((0, np.pi, np.pi / 2)) - - # Camera config. - CONFIG = [{ - 'image_size': image_size, - 'intrinsics': intrinsics, - 'position': position, - 'rotation': rotation, - 'zrange': (0.01, 10.), - 'noise': False - }] - - -class KinectFranka(): - """Kinect Franka Camera""" - - # Near-orthographic projection. - image_size = (424,512) - intrinsics = (365.57489013671875, 0.0, 257.5205078125, 0.0, 365.57489013671875, 205.26710510253906, 0.0, 0.0, 1.0) - position = (1.082, -0.041, 1.027) - rotation = p.getQuaternionFromEuler((-2.611, 0.010, 1.553)) - - # Camera config. - CONFIG = [{ - 'image_size': image_size, - 'intrinsics': intrinsics, - 'position': position, - 'rotation': rotation, - 'zrange': (0.01, 10.), - 'noise': False - }] \ No newline at end of file diff --git a/spaces/Gmq-x/gpt-academic/docs/README_JP.md b/spaces/Gmq-x/gpt-academic/docs/README_JP.md deleted file mode 100644 index 9fc6dbe595657894c9f6f449c50f6f681d762329..0000000000000000000000000000000000000000 --- a/spaces/Gmq-x/gpt-academic/docs/README_JP.md +++ /dev/null @@ -1,302 +0,0 @@ -> **Note** -> -> このReadmeファイルは、このプロジェクトのmarkdown翻訳プラグインによって自動的に生成されたもので、100%正確ではない可能性があります。 -> - -# ChatGPT 学術最適化 - -**このプロジェクトが好きだったら、スターをつけてください。もし、より使いやすい学術用のショートカットキーまたはファンクションプラグインを発明した場合は、issueを発行するかpull requestを作成してください。また、このプロジェクト自体によって翻訳されたREADMEは[英語説明書|](docs/README_EN.md)[日本語説明書|](docs/README_JP.md)[ロシア語説明書|](docs/README_RS.md)[フランス語説明書](docs/README_FR.md)もあります。** - -> **注意事項** -> -> 1. **赤色**のラベルが付いているファンクションプラグイン(ボタン)のみファイルを読み込めます。一部のプラグインはプラグインエリアのドロップダウンメニューにあります。新しいプラグインのPRを歓迎いたします! -> -> 2. このプロジェクトの各ファイルの機能は`self_analysis.md`(自己解析レポート)で詳しく説明されています。バージョンが追加されると、関連するファンクションプラグインをクリックして、GPTを呼び出して自己解析レポートを再生成することができます。一般的な質問は`wiki`にまとめられています。(`https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98`) - - -
- -機能 | 説明 ---- | --- -ワンクリック整形 | 論文の文法エラーを一括で正確に修正できます。 -ワンクリック日英翻訳 | 日英翻訳には、ワンクリックで対応できます。 -ワンクリックコード説明 | コードの正しい表示と説明が可能です。 -[カスタムショートカットキー](https://www.bilibili.com/video/BV14s4y1E7jN) | カスタムショートカットキーをサポートします。 -[プロキシサーバーの設定](https://www.bilibili.com/video/BV1rc411W7Dr) | プロキシサーバーの設定をサポートします。 -モジュラーデザイン | カスタム高階関数プラグインと[関数プラグイン]、プラグイン[ホット更新]のサポートが可能です。詳細は[こちら](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97) -[自己プログラム解析](https://www.bilibili.com/video/BV1cj411A7VW) | [関数プラグイン][ワンクリック理解](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)このプロジェクトのソースコード -[プログラム解析機能](https://www.bilibili.com/video/BV1cj411A7VW) | [関数プラグイン] ワンクリックで別のPython/C/C++/Java/Lua/...プロジェクトツリーを解析できます。 -論文読解 | [関数プラグイン] LaTeX論文の全文をワンクリックで解読し、要約を生成します。 -LaTeX全文翻訳、整形 | [関数プラグイン] ワンクリックでLaTeX論文を翻訳または整形できます。 -注釈生成 | [関数プラグイン] ワンクリックで関数の注釈を大量に生成できます。 -チャット分析レポート生成 | [関数プラグイン] 実行後、まとめレポートを自動生成します。 -[arxivヘルパー](https://www.bilibili.com/video/BV1LM4y1279X) | [関数プラグイン] 入力したarxivの記事URLで要約をワンクリック翻訳+PDFダウンロードができます。 -[PDF論文全文翻訳機能](https://www.bilibili.com/video/BV1KT411x7Wn) | [関数プラグイン] PDF論文タイトルと要約を抽出し、全文を翻訳します(マルチスレッド)。 -[Google Scholar Integratorヘルパー](https://www.bilibili.com/video/BV19L411U7ia) | [関数プラグイン] 任意のGoogle Scholar検索ページURLを指定すると、gptが興味深い記事を選択します。 -数式/画像/テーブル表示 | 数式のTex形式とレンダリング形式を同時に表示できます。数式、コードのハイライトをサポートしています。 -マルチスレッド関数プラグインサポート | ChatGPTをマルチスレッドで呼び出すことができ、大量のテキストやプログラムを簡単に処理できます。 -ダークグラジオ[テーマ](https://github.com/binary-husky/chatgpt_academic/issues/173)の起動 | 「/?__dark-theme=true」というURLをブラウザに追加することで、ダークテーマに切り替えることができます。 -[多数のLLMモデル](https://www.bilibili.com/video/BV1wT411p7yf)をサポート、[API2D](https://api2d.com/)インターフェースをサポート | GPT3.5、GPT4、[清華ChatGLM](https://github.com/THUDM/ChatGLM-6B)による同時サポートは、とても素晴らしいですね! -huggingface免科学上网[オンライン版](https://huggingface.co/spaces/qingxu98/gpt-academic) | huggingfaceにログイン後、[このスペース](https://huggingface.co/spaces/qingxu98/gpt-academic)をコピーしてください。 -...... | ...... - - -
- - -- 新しいインターフェース(config.pyのLAYOUTオプションを変更するだけで、「左右レイアウト」と「上下レイアウト」を切り替えることができます) -
- -
- - -- すべてのボタンは、functional.pyを読み込んで動的に生成されます。カスタム機能を自由に追加して、クリップボードを解放します -
- -
- -- 色を修正/修正 -
- -
- -- 出力に数式が含まれている場合、TeX形式とレンダリング形式の両方が表示され、コピーと読み取りが容易になります -
- -
- -- プロジェクトのコードを見るのが面倒?chatgptに整備されたプロジェクトを直接与えましょう -
- -
- -- 多数の大規模言語モデルの混合呼び出し(ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4) -
- -
- -多数の大規模言語モデルの混合呼び出し[huggingfaceテスト版](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta)(huggigface版はchatglmをサポートしていません) - - ---- - -## インストール-方法1:直接運転 (Windows、LinuxまたはMacOS) - -1. プロジェクトをダウンロードします。 -```sh -git clone https://github.com/binary-husky/chatgpt_academic.git -cd chatgpt_academic -``` - -2. API_KEYとプロキシ設定を構成する - -`config.py`で、海外のProxyとOpenAI API KEYを構成して説明します。 -``` -1.あなたが中国にいる場合、OpenAI APIをスムーズに使用するには海外プロキシを設定する必要があります。構成の詳細については、config.py(1.その中のUSE_PROXYをTrueに変更し、2.手順に従ってプロキシを変更する)を詳細に読んでください。 -2. OpenAI API KEYを構成する。OpenAIのウェブサイトでAPI KEYを取得してください。一旦API KEYを手に入れると、config.pyファイルで設定するだけです。 -3.プロキシネットワークに関連する問題(ネットワークタイムアウト、プロキシが動作しない)をhttps://github.com/binary-husky/chatgpt_academic/issues/1にまとめました。 -``` -(P.S. プログラム実行時にconfig.pyの隣にconfig_private.pyという名前のプライバシー設定ファイルを作成し、同じ名前の設定を上書きするconfig_private.pyが存在するかどうかを優先的に確認します。そのため、私たちの構成読み取りロジックを理解できる場合は、config.pyの隣にconfig_private.pyという名前の新しい設定ファイルを作成し、その中のconfig.pyから設定を移動してください。config_private.pyはgitで保守されていないため、プライバシー情報をより安全にすることができます。) - -3. 依存関係をインストールします。 -```sh -# 選択肢があります。 -python -m pip install -r requirements.txt - - -# (選択肢2) もしAnacondaを使用する場合、手順は同様です: -# (選択肢2.1) conda create -n gptac_venv python=3.11 -# (選択肢2.2) conda activate gptac_venv -# (選択肢2.3) python -m pip install -r requirements.txt - -# 注: 公式のpipソースまたはAlibabaのpipソースを使用してください。 別のpipソース(例:一部の大学のpip)は問題が発生する可能性があります。 一時的なソースの切り替え方法: -# python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ -``` - -もしあなたが清華ChatGLMをサポートする必要がある場合、さらに多くの依存関係をインストールする必要があります(Pythonに慣れない方やコンピューターの設定が十分でない方は、試みないことをお勧めします): -```sh -python -m pip install -r request_llm/requirements_chatglm.txt -``` - -4. 実行 -```sh -python main.py -``` - -5. 関数プラグインのテスト -``` -- Pythonプロジェクト分析のテスト - 入力欄に `./crazy_functions/test_project/python/dqn` と入力し、「Pythonプロジェクト全体の解析」をクリックします。 -- 自己コード解読のテスト - 「[マルチスレッドデモ] このプロジェクト自体を解析します(ソースを翻訳して解読します)」をクリックします。 -- 実験的な機能テンプレート関数のテスト(GPTが「今日の歴史」に何が起こったかを回答することが求められます)。この関数をテンプレートとして使用して、より複雑な機能を実装できます。 - 「[関数プラグインテンプレートデモ] 今日の歴史」をクリックします。 -- 関数プラグインエリアのドロップダウンメニューには他にも選択肢があります。 -``` - -## インストール方法2:Dockerを使用する(Linux) - -1. ChatGPTのみ(大多数の人にお勧めです) -``` sh -# プロジェクトのダウンロード -git clone https://github.com/binary-husky/chatgpt_academic.git -cd chatgpt_academic -# 海外プロキシとOpenAI API KEYの設定 -config.pyを任意のテキストエディタで編集する -# インストール -docker build -t gpt-academic . -# 実行 -docker run --rm -it --net=host gpt-academic - -# 関数プラグインのテスト -## 関数プラグインテンプレート関数のテスト(GPTが「今日の歴史」に何が起こったかを回答することが求められます)。この関数をテンプレートとして使用して、より複雑な機能を実装できます。 -「[関数プラグインテンプレートデモ] 今日の歴史」をクリックします。 -## Latexプロジェクトの要約を書くテスト -入力欄に./crazy_functions/test_project/latex/attentionと入力し、「テックス論文を読んで要約を書く」をクリックします。 -## Pythonプロジェクト分析のテスト -入力欄に./crazy_functions/test_project/python/dqnと入力し、[Pythonプロジェクトの全解析]をクリックします。 - -関数プラグインエリアのドロップダウンメニューには他にも選択肢があります。 -``` - -2. ChatGPT + ChatGLM(Dockerに非常に詳しい人+十分なコンピューター設定が必要) - - - -```sh -# Dockerfileの編集 -cd docs && nano Dockerfile+ChatGLM -# ビルド方法 -docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM . -# 実行方法 (1) 直接実行: -docker run --rm -it --net=host --gpus=all gpt-academic -# 実行方法 (2) コンテナに入って調整する: -docker run --rm -it --net=host --gpus=all gpt-academic bash -``` - -## インストール方法3:その他のデプロイ方法 - -1. クラウドサーバーデプロイ -[デプロイwiki-1](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97) - -2. WSL2を使用 (Windows Subsystem for Linux) -[デプロイwiki-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2) - - -## インストール-プロキシ設定 -1. 通常の方法 -[プロキシを設定する](https://github.com/binary-husky/chatgpt_academic/issues/1) - -2. 初心者向けチュートリアル -[初心者向けチュートリアル](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89) - - ---- - -## カスタムボタンの追加(学術ショートカットキー) - -`core_functional.py`を任意のテキストエディタで開き、以下のエントリーを追加し、プログラムを再起動してください。(ボタンが追加されて表示される場合、前置詞と後置詞はホット編集がサポートされているため、プログラムを再起動せずに即座に有効になります。) - -例: -``` -"超级英译中": { - # 前置詞 - あなたの要求を説明するために使用されます。翻訳、コードの説明、編集など。 - "Prefix": "以下のコンテンツを中国語に翻訳して、マークダウンテーブルを使用して専門用語を説明してください。\n\n", - - # 後置詞 - プレフィックスと共に使用すると、入力内容を引用符で囲むことができます。 - "Suffix": "", -}, -``` - -
- -
- - ---- - -## いくつかの機能の例 - -### 画像表示: - -
- -
- - -### プログラムが自己解析できる場合: - -
- -
- -
- -
- -### 他のPython/Cppプロジェクトの解析: - -
- -
- -
- -
- -### Latex論文の一括読解と要約生成 - -
- -
- -### 自動報告生成 - -
- - - -
- -### モジュール化された機能デザイン - -
- - -
- - -### ソースコードの英語翻訳 - -
- -
- -## Todo およびバージョン計画: -- version 3.2+ (todo): 関数プラグインがより多くのパラメーターインターフェースをサポートするようになります。 -- version 3.1: 複数のgptモデルを同時にクエリし、api2dをサポートし、複数のapikeyの負荷分散をサポートします。 -- version 3.0: chatglmおよび他の小型llmのサポート -- version 2.6: プラグイン構造を再構成し、相互作用性を高め、より多くのプラグインを追加しました。 -- version 2.5: 自己更新。総括的な大規模プロジェクトのソースコードをまとめた場合、テキストが長すぎる、トークンがオーバーフローする問題を解決します。 -- version 2.4: (1)PDF全文翻訳機能を追加。(2)入力エリアの位置を切り替える機能を追加。(3)垂直レイアウトオプションを追加。(4)マルチスレッド関数プラグインの最適化。 -- version 2.3: 多スレッドの相互作用性を向上させました。 -- version 2.2: 関数プラグインでホットリロードをサポート -- version 2.1: 折りたたみ式レイアウト -- version 2.0: モジュール化された関数プラグインを導入 -- version 1.0: 基本機能 - -## 参考および学習 - - -以下は中国語のマークダウンファイルです。日本語に翻訳してください。既存のマークダウンコマンドを変更しないでください: - -``` -多くの優秀なプロジェクトの設計を参考にしています。主なものは以下の通りです: - -# 参考プロジェクト1:ChuanhuChatGPTから多くのテクニックを借用 -https://github.com/GaiZhenbiao/ChuanhuChatGPT - -# 参考プロジェクト2:清華ChatGLM-6B: -https://github.com/THUDM/ChatGLM-6B -``` - diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/deeplabv3plus/deeplabv3plus_r101-d8_512x512_160k_ade20k.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/deeplabv3plus/deeplabv3plus_r101-d8_512x512_160k_ade20k.py deleted file mode 100644 index a75c9d3019b13d01c0dd13dae53bce3d15791d52..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/deeplabv3plus/deeplabv3plus_r101-d8_512x512_160k_ade20k.py +++ /dev/null @@ -1,2 +0,0 @@ -_base_ = './deeplabv3plus_r50-d8_512x512_160k_ade20k.py' -model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101)) diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/encnet/encnet_r50-d8_512x512_40k_voc12aug.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/encnet/encnet_r50-d8_512x512_40k_voc12aug.py deleted file mode 100644 index 81f3cbfbf516e833821c49deecd8f167170021f0..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/encnet/encnet_r50-d8_512x512_40k_voc12aug.py +++ /dev/null @@ -1,7 +0,0 @@ -_base_ = [ - '../_base_/models/encnet_r50-d8.py', - '../_base_/datasets/pascal_voc12_aug.py', '../_base_/default_runtime.py', - '../_base_/schedules/schedule_40k.py' -] -model = dict( - decode_head=dict(num_classes=21), auxiliary_head=dict(num_classes=21)) diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/mobilenet_v3/README.md b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/mobilenet_v3/README.md deleted file mode 100644 index a843d355b6c95946517b50b6867d53f1ffcaf869..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/mobilenet_v3/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# Searching for MobileNetV3 - -## Introduction - - - -```latex -@inproceedings{Howard_2019_ICCV, - title={Searching for MobileNetV3}, - author={Howard, Andrew and Sandler, Mark and Chu, Grace and Chen, Liang-Chieh and Chen, Bo and Tan, Mingxing and Wang, Weijun and Zhu, Yukun and Pang, Ruoming and Vasudevan, Vijay and Le, Quoc V. and Adam, Hartwig}, - booktitle={The IEEE International Conference on Computer Vision (ICCV)}, - pages={1314-1324}, - month={October}, - year={2019}, - doi={10.1109/ICCV.2019.00140}} -} -``` - -## Results and models - -### Cityscapes - -| Method | Backbone | Crop Size | Lr schd | Mem (GB) | Inf time (fps) | mIoU | mIoU(ms+flip) | config | download | -| ------ | ------------------ | --------- | ------: | -------: | -------------- | ----: | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| LRASPP | M-V3-D8 | 512x1024 | 320000 | 8.9 | 15.22 | 69.54 | 70.89 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/mobilenet_v3/lraspp_m-v3-d8_512x1024_320k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/mobilenet_v3/lraspp_m-v3-d8_512x1024_320k_cityscapes/lraspp_m-v3-d8_512x1024_320k_cityscapes_20201224_220337-cfe8fb07.pth) | [log](https://download.openmmlab.com/mmsegmentation/v0.5/mobilenet_v3/lraspp_m-v3-d8_512x1024_320k_cityscapes/lraspp_m-v3-d8_512x1024_320k_cityscapes-20201224_220337.log.json) | -| LRASPP | M-V3-D8 (scratch) | 512x1024 | 320000 | 8.9 | 14.77 | 67.87 | 69.78 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/mobilenet_v3/lraspp_m-v3-d8_scratch_512x1024_320k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/mobilenet_v3/lraspp_m-v3-d8_scratch_512x1024_320k_cityscapes/lraspp_m-v3-d8_scratch_512x1024_320k_cityscapes_20201224_220337-9f29cd72.pth) | [log](https://download.openmmlab.com/mmsegmentation/v0.5/mobilenet_v3/lraspp_m-v3-d8_scratch_512x1024_320k_cityscapes/lraspp_m-v3-d8_scratch_512x1024_320k_cityscapes-20201224_220337.log.json) | -| LRASPP | M-V3s-D8 | 512x1024 | 320000 | 5.3 | 23.64 | 64.11 | 66.42 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/mobilenet_v3/lraspp_m-v3s-d8_512x1024_320k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/mobilenet_v3/lraspp_m-v3s-d8_512x1024_320k_cityscapes/lraspp_m-v3s-d8_512x1024_320k_cityscapes_20201224_223935-61565b34.pth) | [log](https://download.openmmlab.com/mmsegmentation/v0.5/mobilenet_v3/lraspp_m-v3s-d8_512x1024_320k_cityscapes/lraspp_m-v3s-d8_512x1024_320k_cityscapes-20201224_223935.log.json) | -| LRASPP | M-V3s-D8 (scratch) | 512x1024 | 320000 | 5.3 | 24.50 | 62.74 | 65.01 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/mobilenet_v3/lraspp_m-v3s-d8_scratch_512x1024_320k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/mobilenet_v3/lraspp_m-v3s-d8_scratch_512x1024_320k_cityscapes/lraspp_m-v3s-d8_scratch_512x1024_320k_cityscapes_20201224_223935-03daeabb.pth) | [log](https://download.openmmlab.com/mmsegmentation/v0.5/mobilenet_v3/lraspp_m-v3s-d8_scratch_512x1024_320k_cityscapes/lraspp_m-v3s-d8_scratch_512x1024_320k_cityscapes-20201224_223935.log.json) | diff --git a/spaces/Grezz/generate_human_motion/pyrender/pyrender/mesh.py b/spaces/Grezz/generate_human_motion/pyrender/pyrender/mesh.py deleted file mode 100644 index 36833ea3dfa6c095a18fc745ff34cf106e83c95d..0000000000000000000000000000000000000000 --- a/spaces/Grezz/generate_human_motion/pyrender/pyrender/mesh.py +++ /dev/null @@ -1,328 +0,0 @@ -"""Meshes, conforming to the glTF 2.0 standards as specified in -https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-mesh - -Author: Matthew Matl -""" -import copy - -import numpy as np -import trimesh - -from .primitive import Primitive -from .constants import GLTF -from .material import MetallicRoughnessMaterial - - -class Mesh(object): - """A set of primitives to be rendered. - - Parameters - ---------- - name : str - The user-defined name of this object. - primitives : list of :class:`Primitive` - The primitives associated with this mesh. - weights : (k,) float - Array of weights to be applied to the Morph Targets. - is_visible : bool - If False, the mesh will not be rendered. - """ - - def __init__(self, primitives, name=None, weights=None, is_visible=True): - self.primitives = primitives - self.name = name - self.weights = weights - self.is_visible = is_visible - - self._bounds = None - - @property - def name(self): - """str : The user-defined name of this object. - """ - return self._name - - @name.setter - def name(self, value): - if value is not None: - value = str(value) - self._name = value - - @property - def primitives(self): - """list of :class:`Primitive` : The primitives associated - with this mesh. - """ - return self._primitives - - @primitives.setter - def primitives(self, value): - self._primitives = value - - @property - def weights(self): - """(k,) float : Weights to be applied to morph targets. - """ - return self._weights - - @weights.setter - def weights(self, value): - self._weights = value - - @property - def is_visible(self): - """bool : Whether the mesh is visible. - """ - return self._is_visible - - @is_visible.setter - def is_visible(self, value): - self._is_visible = value - - @property - def bounds(self): - """(2,3) float : The axis-aligned bounds of the mesh. - """ - if self._bounds is None: - bounds = np.array([[np.infty, np.infty, np.infty], - [-np.infty, -np.infty, -np.infty]]) - for p in self.primitives: - bounds[0] = np.minimum(bounds[0], p.bounds[0]) - bounds[1] = np.maximum(bounds[1], p.bounds[1]) - self._bounds = bounds - return self._bounds - - @property - def centroid(self): - """(3,) float : The centroid of the mesh's axis-aligned bounding box - (AABB). - """ - return np.mean(self.bounds, axis=0) - - @property - def extents(self): - """(3,) float : The lengths of the axes of the mesh's AABB. - """ - return np.diff(self.bounds, axis=0).reshape(-1) - - @property - def scale(self): - """(3,) float : The length of the diagonal of the mesh's AABB. - """ - return np.linalg.norm(self.extents) - - @property - def is_transparent(self): - """bool : If True, the mesh is partially-transparent. - """ - for p in self.primitives: - if p.is_transparent: - return True - return False - - @staticmethod - def from_points(points, colors=None, normals=None, - is_visible=True, poses=None): - """Create a Mesh from a set of points. - - Parameters - ---------- - points : (n,3) float - The point positions. - colors : (n,3) or (n,4) float, optional - RGB or RGBA colors for each point. - normals : (n,3) float, optionals - The normal vectors for each point. - is_visible : bool - If False, the points will not be rendered. - poses : (x,4,4) - Array of 4x4 transformation matrices for instancing this object. - - Returns - ------- - mesh : :class:`Mesh` - The created mesh. - """ - primitive = Primitive( - positions=points, - normals=normals, - color_0=colors, - mode=GLTF.POINTS, - poses=poses - ) - mesh = Mesh(primitives=[primitive], is_visible=is_visible) - return mesh - - @staticmethod - def from_trimesh(mesh, material=None, is_visible=True, - poses=None, wireframe=False, smooth=True): - """Create a Mesh from a :class:`~trimesh.base.Trimesh`. - - Parameters - ---------- - mesh : :class:`~trimesh.base.Trimesh` or list of them - A triangular mesh or a list of meshes. - material : :class:`Material` - The material of the object. Overrides any mesh material. - If not specified and the mesh has no material, a default material - will be used. - is_visible : bool - If False, the mesh will not be rendered. - poses : (n,4,4) float - Array of 4x4 transformation matrices for instancing this object. - wireframe : bool - If `True`, the mesh will be rendered as a wireframe object - smooth : bool - If `True`, the mesh will be rendered with interpolated vertex - normals. Otherwise, the mesh edges will stay sharp. - - Returns - ------- - mesh : :class:`Mesh` - The created mesh. - """ - - if isinstance(mesh, (list, tuple, set, np.ndarray)): - meshes = list(mesh) - elif isinstance(mesh, trimesh.Trimesh): - meshes = [mesh] - else: - raise TypeError('Expected a Trimesh or a list, got a {}' - .format(type(mesh))) - - primitives = [] - for m in meshes: - positions = None - normals = None - indices = None - - # Compute positions, normals, and indices - if smooth: - positions = m.vertices.copy() - normals = m.vertex_normals.copy() - indices = m.faces.copy() - else: - positions = m.vertices[m.faces].reshape((3 * len(m.faces), 3)) - normals = np.repeat(m.face_normals, 3, axis=0) - - # Compute colors, texture coords, and material properties - color_0, texcoord_0, primitive_material = Mesh._get_trimesh_props(m, smooth=smooth, material=material) - - # Override if material is given. - if material is not None: - #primitive_material = copy.copy(material) - primitive_material = copy.deepcopy(material) # TODO - - if primitive_material is None: - # Replace material with default if needed - primitive_material = MetallicRoughnessMaterial( - alphaMode='BLEND', - baseColorFactor=[0.3, 0.3, 0.3, 1.0], - metallicFactor=0.2, - roughnessFactor=0.8 - ) - - primitive_material.wireframe = wireframe - - # Create the primitive - primitives.append(Primitive( - positions=positions, - normals=normals, - texcoord_0=texcoord_0, - color_0=color_0, - indices=indices, - material=primitive_material, - mode=GLTF.TRIANGLES, - poses=poses - )) - - return Mesh(primitives=primitives, is_visible=is_visible) - - @staticmethod - def _get_trimesh_props(mesh, smooth=False, material=None): - """Gets the vertex colors, texture coordinates, and material properties - from a :class:`~trimesh.base.Trimesh`. - """ - colors = None - texcoords = None - - # If the trimesh visual is undefined, return none for both - if not mesh.visual.defined: - return colors, texcoords, material - - # Process vertex colors - if material is None: - if mesh.visual.kind == 'vertex': - vc = mesh.visual.vertex_colors.copy() - if smooth: - colors = vc - else: - colors = vc[mesh.faces].reshape( - (3 * len(mesh.faces), vc.shape[1]) - ) - material = MetallicRoughnessMaterial( - alphaMode='BLEND', - baseColorFactor=[1.0, 1.0, 1.0, 1.0], - metallicFactor=0.2, - roughnessFactor=0.8 - ) - # Process face colors - elif mesh.visual.kind == 'face': - if smooth: - raise ValueError('Cannot use face colors with a smooth mesh') - else: - colors = np.repeat(mesh.visual.face_colors, 3, axis=0) - - material = MetallicRoughnessMaterial( - alphaMode='BLEND', - baseColorFactor=[1.0, 1.0, 1.0, 1.0], - metallicFactor=0.2, - roughnessFactor=0.8 - ) - - # Process texture colors - if mesh.visual.kind == 'texture': - # Configure UV coordinates - if mesh.visual.uv is not None and len(mesh.visual.uv) != 0: - uv = mesh.visual.uv.copy() - if smooth: - texcoords = uv - else: - texcoords = uv[mesh.faces].reshape( - (3 * len(mesh.faces), uv.shape[1]) - ) - - if material is None: - # Configure mesh material - mat = mesh.visual.material - - if isinstance(mat, trimesh.visual.texture.PBRMaterial): - material = MetallicRoughnessMaterial( - normalTexture=mat.normalTexture, - occlusionTexture=mat.occlusionTexture, - emissiveTexture=mat.emissiveTexture, - emissiveFactor=mat.emissiveFactor, - alphaMode='BLEND', - baseColorFactor=mat.baseColorFactor, - baseColorTexture=mat.baseColorTexture, - metallicFactor=mat.metallicFactor, - roughnessFactor=mat.roughnessFactor, - metallicRoughnessTexture=mat.metallicRoughnessTexture, - doubleSided=mat.doubleSided, - alphaCutoff=mat.alphaCutoff - ) - elif isinstance(mat, trimesh.visual.texture.SimpleMaterial): - glossiness = mat.kwargs.get('Ns', 1.0) - if isinstance(glossiness, list): - glossiness = float(glossiness[0]) - roughness = (2 / (glossiness + 2)) ** (1.0 / 4.0) - material = MetallicRoughnessMaterial( - alphaMode='BLEND', - roughnessFactor=roughness, - baseColorFactor=mat.diffuse, - baseColorTexture=mat.image, - ) - elif isinstance(mat, MetallicRoughnessMaterial): - material = mat - - return colors, texcoords, material diff --git a/spaces/Grezz/generate_human_motion/pyrender/tests/unit/test_cameras.py b/spaces/Grezz/generate_human_motion/pyrender/tests/unit/test_cameras.py deleted file mode 100644 index 7544ad8f8e3ee55236fd2e32dbc12065153cbe5b..0000000000000000000000000000000000000000 --- a/spaces/Grezz/generate_human_motion/pyrender/tests/unit/test_cameras.py +++ /dev/null @@ -1,164 +0,0 @@ -import numpy as np -import pytest - -from pyrender import PerspectiveCamera, OrthographicCamera - - -def test_perspective_camera(): - - # Set up constants - znear = 0.05 - zfar = 100 - yfov = np.pi / 3.0 - width = 1000.0 - height = 500.0 - aspectRatio = 640.0 / 480.0 - - # Test basics - with pytest.raises(TypeError): - p = PerspectiveCamera() - - p = PerspectiveCamera(yfov=yfov) - assert p.yfov == yfov - assert p.znear == 0.05 - assert p.zfar is None - assert p.aspectRatio is None - p.name = 'asdf' - p.name = None - - with pytest.raises(ValueError): - p.yfov = 0.0 - - with pytest.raises(ValueError): - p.yfov = -1.0 - - with pytest.raises(ValueError): - p.znear = -1.0 - - p.znear = 0.0 - p.znear = 0.05 - p.zfar = 100.0 - assert p.zfar == 100.0 - - with pytest.raises(ValueError): - p.zfar = 0.03 - - with pytest.raises(ValueError): - p.zfar = 0.05 - - p.aspectRatio = 10.0 - assert p.aspectRatio == 10.0 - - with pytest.raises(ValueError): - p.aspectRatio = 0.0 - - with pytest.raises(ValueError): - p.aspectRatio = -1.0 - - # Test matrix getting/setting - - # NF - p.znear = 0.05 - p.zfar = 100 - p.aspectRatio = None - - with pytest.raises(ValueError): - p.get_projection_matrix() - - assert np.allclose( - p.get_projection_matrix(width, height), - np.array([ - [1.0 / (width / height * np.tan(yfov / 2.0)), 0.0, 0.0, 0.0], - [0.0, 1.0 / np.tan(yfov / 2.0), 0.0, 0.0], - [0.0, 0.0, (zfar + znear) / (znear - zfar), - (2 * zfar * znear) / (znear - zfar)], - [0.0, 0.0, -1.0, 0.0] - ]) - ) - - # NFA - p.aspectRatio = aspectRatio - assert np.allclose( - p.get_projection_matrix(width, height), - np.array([ - [1.0 / (aspectRatio * np.tan(yfov / 2.0)), 0.0, 0.0, 0.0], - [0.0, 1.0 / np.tan(yfov / 2.0), 0.0, 0.0], - [0.0, 0.0, (zfar + znear) / (znear - zfar), - (2 * zfar * znear) / (znear - zfar)], - [0.0, 0.0, -1.0, 0.0] - ]) - ) - assert np.allclose( - p.get_projection_matrix(), p.get_projection_matrix(width, height) - ) - - # N - p.zfar = None - p.aspectRatio = None - assert np.allclose( - p.get_projection_matrix(width, height), - np.array([ - [1.0 / (width / height * np.tan(yfov / 2.0)), 0.0, 0.0, 0.0], - [0.0, 1.0 / np.tan(yfov / 2.0), 0.0, 0.0], - [0.0, 0.0, -1.0, -2.0 * znear], - [0.0, 0.0, -1.0, 0.0] - ]) - ) - - -def test_orthographic_camera(): - xm = 1.0 - ym = 2.0 - n = 0.05 - f = 100.0 - - with pytest.raises(TypeError): - c = OrthographicCamera() - - c = OrthographicCamera(xmag=xm, ymag=ym) - - assert c.xmag == xm - assert c.ymag == ym - assert c.znear == 0.05 - assert c.zfar == 100.0 - assert c.name is None - - with pytest.raises(TypeError): - c.ymag = None - - with pytest.raises(ValueError): - c.ymag = 0.0 - - with pytest.raises(ValueError): - c.ymag = -1.0 - - with pytest.raises(TypeError): - c.xmag = None - - with pytest.raises(ValueError): - c.xmag = 0.0 - - with pytest.raises(ValueError): - c.xmag = -1.0 - - with pytest.raises(TypeError): - c.znear = None - - with pytest.raises(ValueError): - c.znear = 0.0 - - with pytest.raises(ValueError): - c.znear = -1.0 - - with pytest.raises(ValueError): - c.zfar = 0.01 - - assert np.allclose( - c.get_projection_matrix(), - np.array([ - [1.0 / xm, 0, 0, 0], - [0, 1.0 / ym, 0, 0], - [0, 0, 2.0 / (n - f), (f + n) / (n - f)], - [0, 0, 0, 1.0] - ]) - ) diff --git a/spaces/GroveStreet/GTA_SOVITS/vencoder/encoder.py b/spaces/GroveStreet/GTA_SOVITS/vencoder/encoder.py deleted file mode 100644 index 2cf5678533cf16f2e81248535d35e4c3c1c5799a..0000000000000000000000000000000000000000 --- a/spaces/GroveStreet/GTA_SOVITS/vencoder/encoder.py +++ /dev/null @@ -1,12 +0,0 @@ -class SpeechEncoder(object): - def __init__(self,vec_path = "pretrain/checkpoint_best_legacy_500.pt",device=None): - self.model = None #This is Model - self.hidden_dim = 768 - pass - - def encoder(self,wav): - ''' - input: wav:[batchsize,signal_length] - output: embedding:[batchsize,hidden_dim,wav_frame] - ''' - pass \ No newline at end of file diff --git a/spaces/HaHaBill/LandShapes-Antarctica/netdissect/upsegmodel/prroi_pool/prroi_pool.py b/spaces/HaHaBill/LandShapes-Antarctica/netdissect/upsegmodel/prroi_pool/prroi_pool.py deleted file mode 100644 index 998b2b80531058fa91ac138e79ae39c5c0174601..0000000000000000000000000000000000000000 --- a/spaces/HaHaBill/LandShapes-Antarctica/netdissect/upsegmodel/prroi_pool/prroi_pool.py +++ /dev/null @@ -1,28 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# File : prroi_pool.py -# Author : Jiayuan Mao, Tete Xiao -# Email : maojiayuan@gmail.com, jasonhsiao97@gmail.com -# Date : 07/13/2018 -# -# This file is part of PreciseRoIPooling. -# Distributed under terms of the MIT license. -# Copyright (c) 2017 Megvii Technology Limited. - -import torch.nn as nn - -from .functional import prroi_pool2d - -__all__ = ['PrRoIPool2D'] - - -class PrRoIPool2D(nn.Module): - def __init__(self, pooled_height, pooled_width, spatial_scale): - super().__init__() - - self.pooled_height = int(pooled_height) - self.pooled_width = int(pooled_width) - self.spatial_scale = float(spatial_scale) - - def forward(self, features, rois): - return prroi_pool2d(features, rois, self.pooled_height, self.pooled_width, self.spatial_scale) diff --git a/spaces/Hallucinate/demo/taming/data/conditional_builder/objects_bbox.py b/spaces/Hallucinate/demo/taming/data/conditional_builder/objects_bbox.py deleted file mode 100644 index 15881e76b7ab2a914df8f2dfe08ae4f0c6c511b5..0000000000000000000000000000000000000000 --- a/spaces/Hallucinate/demo/taming/data/conditional_builder/objects_bbox.py +++ /dev/null @@ -1,60 +0,0 @@ -from itertools import cycle -from typing import List, Tuple, Callable, Optional - -from PIL import Image as pil_image, ImageDraw as pil_img_draw, ImageFont -from more_itertools.recipes import grouper -from taming.data.image_transforms import convert_pil_to_tensor -from torch import LongTensor, Tensor - -from taming.data.helper_types import BoundingBox, Annotation -from taming.data.conditional_builder.objects_center_points import ObjectsCenterPointsConditionalBuilder -from taming.data.conditional_builder.utils import COLOR_PALETTE, WHITE, GRAY_75, BLACK, additional_parameters_string, \ - pad_list, get_plot_font_size, absolute_bbox - - -class ObjectsBoundingBoxConditionalBuilder(ObjectsCenterPointsConditionalBuilder): - @property - def object_descriptor_length(self) -> int: - return 3 - - def _make_object_descriptors(self, annotations: List[Annotation]) -> List[Tuple[int, ...]]: - object_triples = [ - (self.object_representation(ann), *self.token_pair_from_bbox(ann.bbox)) - for ann in annotations - ] - empty_triple = (self.none, self.none, self.none) - object_triples = pad_list(object_triples, empty_triple, self.no_max_objects) - return object_triples - - def inverse_build(self, conditional: LongTensor) -> Tuple[List[Tuple[int, BoundingBox]], Optional[BoundingBox]]: - conditional_list = conditional.tolist() - crop_coordinates = None - if self.encode_crop: - crop_coordinates = self.bbox_from_token_pair(conditional_list[-2], conditional_list[-1]) - conditional_list = conditional_list[:-2] - object_triples = grouper(conditional_list, 3) - assert conditional.shape[0] == self.embedding_dim - return [ - (object_triple[0], self.bbox_from_token_pair(object_triple[1], object_triple[2])) - for object_triple in object_triples if object_triple[0] != self.none - ], crop_coordinates - - def plot(self, conditional: LongTensor, label_for_category_no: Callable[[int], str], figure_size: Tuple[int, int], - line_width: int = 3, font_size: Optional[int] = None) -> Tensor: - plot = pil_image.new('RGB', figure_size, WHITE) - draw = pil_img_draw.Draw(plot) - font = ImageFont.truetype( - "/usr/share/fonts/truetype/lato/Lato-Regular.ttf", - size=get_plot_font_size(font_size, figure_size) - ) - width, height = plot.size - description, crop_coordinates = self.inverse_build(conditional) - for (representation, bbox), color in zip(description, cycle(COLOR_PALETTE)): - annotation = self.representation_to_annotation(representation) - class_label = label_for_category_no(annotation.category_no) + ' ' + additional_parameters_string(annotation) - bbox = absolute_bbox(bbox, width, height) - draw.rectangle(bbox, outline=color, width=line_width) - draw.text((bbox[0] + line_width, bbox[1] + line_width), class_label, anchor='la', fill=BLACK, font=font) - if crop_coordinates is not None: - draw.rectangle(absolute_bbox(crop_coordinates, width, height), outline=GRAY_75, width=line_width) - return convert_pil_to_tensor(plot) / 127.5 - 1. diff --git a/spaces/HaloMaster/chinesesummary/fengshen/data/megatron_dataloader/utils.py b/spaces/HaloMaster/chinesesummary/fengshen/data/megatron_dataloader/utils.py deleted file mode 100644 index 9258f4830fb22333b37603439da8f8116cd7a048..0000000000000000000000000000000000000000 --- a/spaces/HaloMaster/chinesesummary/fengshen/data/megatron_dataloader/utils.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import torch - - -def print_rank_0(message): - """If distributed is initialized, print only on rank 0.""" - if torch.distributed.is_initialized(): - if torch.distributed.get_rank() == 0: - print(message, flush=True) - else: - print(message, flush=True) diff --git a/spaces/HarryLee/eCommerceImageCaptioning/data/data_utils.py b/spaces/HarryLee/eCommerceImageCaptioning/data/data_utils.py deleted file mode 100644 index d45beb1aca2e55b1ca9b2c01ce1a869ad9a2121d..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/data/data_utils.py +++ /dev/null @@ -1,601 +0,0 @@ -# Copyright 2022 The OFA-Sys Team. -# All rights reserved. -# This source code is licensed under the Apache 2.0 license -# found in the LICENSE file in the root directory. - -try: - from collections.abc import Iterable -except ImportError: - from collections import Iterable -import contextlib -import itertools -import logging -import re -import warnings -from typing import Optional, Tuple - -import numpy as np -import torch - -from fairseq.file_io import PathManager -from fairseq import utils -import os - -logger = logging.getLogger(__name__) - - -def infer_language_pair(path): - """Infer language pair from filename: .-.(...).idx""" - src, dst = None, None - for filename in PathManager.ls(path): - parts = filename.split(".") - if len(parts) >= 3 and len(parts[1].split("-")) == 2: - return parts[1].split("-") - return src, dst - - -def collate_tokens( - values, - pad_idx, - eos_idx=None, - left_pad=False, - move_eos_to_beginning=False, - pad_to_length=None, - pad_to_multiple=1, - pad_to_bsz=None, -): - """Convert a list of 1d tensors into a padded 2d tensor.""" - size = max(v.size(0) for v in values) - size = size if pad_to_length is None else max(size, pad_to_length) - if pad_to_multiple != 1 and size % pad_to_multiple != 0: - size = int(((size - 0.1) // pad_to_multiple + 1) * pad_to_multiple) - - def copy_tensor(src, dst): - assert dst.numel() == src.numel() - if move_eos_to_beginning: - if eos_idx is None: - # if no eos_idx is specified, then use the last token in src - dst[0] = src[-1] - else: - dst[0] = eos_idx - dst[1:] = src[:-1] - else: - dst.copy_(src) - - if values[0].dim() == 1: - res = values[0].new(len(values), size).fill_(pad_idx) - elif values[0].dim() == 2: - assert move_eos_to_beginning is False - res = values[0].new(len(values), size, values[0].size(1)).fill_(pad_idx) - else: - raise NotImplementedError - - for i, v in enumerate(values): - copy_tensor(v, res[i][size - len(v) :] if left_pad else res[i][: len(v)]) - return res - - -def load_indexed_dataset( - path, dictionary=None, dataset_impl=None, combine=False, default="cached" -): - """A helper function for loading indexed datasets. - - Args: - path (str): path to indexed dataset (e.g., 'data-bin/train') - dictionary (~fairseq.data.Dictionary): data dictionary - dataset_impl (str, optional): which dataset implementation to use. If - not provided, it will be inferred automatically. For legacy indexed - data we use the 'cached' implementation by default. - combine (bool, optional): automatically load and combine multiple - datasets. For example, if *path* is 'data-bin/train', then we will - combine 'data-bin/train', 'data-bin/train1', ... and return a - single ConcatDataset instance. - """ - import fairseq.data.indexed_dataset as indexed_dataset - from fairseq.data.concat_dataset import ConcatDataset - - datasets = [] - for k in itertools.count(): - path_k = path + (str(k) if k > 0 else "") - try: - path_k = indexed_dataset.get_indexed_dataset_to_local(path_k) - except Exception as e: - if "StorageException: [404] Path not found" in str(e): - logger.warning(f"path_k: {e} not found") - else: - raise e - - dataset_impl_k = dataset_impl - if dataset_impl_k is None: - dataset_impl_k = indexed_dataset.infer_dataset_impl(path_k) - dataset = indexed_dataset.make_dataset( - path_k, - impl=dataset_impl_k or default, - fix_lua_indexing=True, - dictionary=dictionary, - ) - if dataset is None: - break - logger.info("loaded {:,} examples from: {}".format(len(dataset), path_k)) - datasets.append(dataset) - if not combine: - break - if len(datasets) == 0: - return None - elif len(datasets) == 1: - return datasets[0] - else: - return ConcatDataset(datasets) - - -@contextlib.contextmanager -def numpy_seed(seed, *addl_seeds): - """Context manager which seeds the NumPy PRNG with the specified seed and - restores the state afterward""" - if seed is None: - yield - return - if len(addl_seeds) > 0: - seed = int(hash((seed, *addl_seeds)) % 1e6) - state = np.random.get_state() - np.random.seed(seed) - try: - yield - finally: - np.random.set_state(state) - - -def collect_filtered(function, iterable, filtered): - """ - Similar to :func:`filter` but collects filtered elements in ``filtered``. - - Args: - function (callable): function that returns ``False`` for elements that - should be filtered - iterable (iterable): iterable to filter - filtered (list): list to store filtered elements - """ - for el in iterable: - if function(el): - yield el - else: - filtered.append(el) - - -def _filter_by_size_dynamic(indices, size_fn, max_positions, raise_exception=False): - def compare_leq(a, b): - return a <= b if not isinstance(a, tuple) else max(a) <= b - - def check_size(idx): - if isinstance(max_positions, float) or isinstance(max_positions, int): - return size_fn(idx) <= max_positions - elif isinstance(max_positions, dict): - idx_size = size_fn(idx) - assert isinstance(idx_size, dict) - intersect_keys = set(max_positions.keys()) & set(idx_size.keys()) - return all( - all( - a is None or b is None or a <= b - for a, b in zip(idx_size[key], max_positions[key]) - ) - for key in intersect_keys - ) - else: - # For MultiCorpusSampledDataset, will generalize it later - if not isinstance(size_fn(idx), Iterable): - return all(size_fn(idx) <= b for b in max_positions) - return all( - a is None or b is None or a <= b - for a, b in zip(size_fn(idx), max_positions) - ) - - ignored = [] - itr = collect_filtered(check_size, indices, ignored) - indices = np.fromiter(itr, dtype=np.int64, count=-1) - return indices, ignored - - -def filter_by_size(indices, dataset, max_positions, raise_exception=False): - """ - [deprecated] Filter indices based on their size. - Use `FairseqDataset::filter_indices_by_size` instead. - - Args: - indices (List[int]): ordered list of dataset indices - dataset (FairseqDataset): fairseq dataset instance - max_positions (tuple): filter elements larger than this size. - Comparisons are done component-wise. - raise_exception (bool, optional): if ``True``, raise an exception if - any elements are filtered (default: False). - """ - warnings.warn( - "data_utils.filter_by_size is deprecated. " - "Use `FairseqDataset::filter_indices_by_size` instead.", - stacklevel=2, - ) - if isinstance(max_positions, float) or isinstance(max_positions, int): - if hasattr(dataset, "sizes") and isinstance(dataset.sizes, np.ndarray): - ignored = indices[dataset.sizes[indices] > max_positions].tolist() - indices = indices[dataset.sizes[indices] <= max_positions] - elif ( - hasattr(dataset, "sizes") - and isinstance(dataset.sizes, list) - and len(dataset.sizes) == 1 - ): - ignored = indices[dataset.sizes[0][indices] > max_positions].tolist() - indices = indices[dataset.sizes[0][indices] <= max_positions] - else: - indices, ignored = _filter_by_size_dynamic( - indices, dataset.size, max_positions - ) - else: - indices, ignored = _filter_by_size_dynamic(indices, dataset.size, max_positions) - - if len(ignored) > 0 and raise_exception: - raise Exception( - ( - "Size of sample #{} is invalid (={}) since max_positions={}, " - "skip this example with --skip-invalid-size-inputs-valid-test" - ).format(ignored[0], dataset.size(ignored[0]), max_positions) - ) - if len(ignored) > 0: - logger.warning( - ( - "{} samples have invalid sizes and will be skipped, " - "max_positions={}, first few sample ids={}" - ).format(len(ignored), max_positions, ignored[:10]) - ) - return indices - - -def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes): - """Filter a list of sample indices. Remove those that are longer - than specified in max_sizes. - - Args: - indices (np.array): original array of sample indices - max_sizes (int or list[int] or tuple[int]): max sample size, - can be defined separately for src and tgt (then list or tuple) - - Returns: - np.array: filtered sample array - list: list of removed indices - """ - if max_sizes is None: - return indices, [] - if type(max_sizes) in (int, float): - max_src_size, max_tgt_size = max_sizes, max_sizes - else: - max_src_size, max_tgt_size = max_sizes - if tgt_sizes is None: - ignored = indices[src_sizes[indices] > max_src_size] - else: - ignored = indices[ - (src_sizes[indices] > max_src_size) | (tgt_sizes[indices] > max_tgt_size) - ] - if len(ignored) > 0: - if tgt_sizes is None: - indices = indices[src_sizes[indices] <= max_src_size] - else: - indices = indices[ - (src_sizes[indices] <= max_src_size) - & (tgt_sizes[indices] <= max_tgt_size) - ] - return indices, ignored.tolist() - - -def batch_by_size( - indices, - num_tokens_fn, - num_tokens_vec=None, - max_tokens=None, - max_sentences=None, - required_batch_size_multiple=1, - fixed_shapes=None, -): - """ - Yield mini-batches of indices bucketed by size. Batches may contain - sequences of different lengths. - - Args: - indices (List[int]): ordered list of dataset indices - num_tokens_fn (callable): function that returns the number of tokens at - a given index - num_tokens_vec (List[int], optional): precomputed vector of the number - of tokens for each index in indices (to enable faster batch generation) - max_tokens (int, optional): max number of tokens in each batch - (default: None). - max_sentences (int, optional): max number of sentences in each - batch (default: None). - required_batch_size_multiple (int, optional): require batch size to - be less than N or a multiple of N (default: 1). - fixed_shapes (List[Tuple[int, int]], optional): if given, batches will - only be created with the given shapes. *max_sentences* and - *required_batch_size_multiple* will be ignored (default: None). - """ - try: - from fairseq.data.data_utils_fast import ( - batch_by_size_fn, - batch_by_size_vec, - batch_fixed_shapes_fast, - ) - except ImportError: - raise ImportError( - "Please build Cython components with: " - "`python setup.py build_ext --inplace`" - ) - except ValueError: - raise ValueError( - "Please build (or rebuild) Cython components with `python setup.py build_ext --inplace`." - ) - - # added int() to avoid TypeError: an integer is required - max_tokens = ( - int(max_tokens) if max_tokens is not None else -1 - ) - max_sentences = max_sentences if max_sentences is not None else -1 - bsz_mult = required_batch_size_multiple - - if not isinstance(indices, np.ndarray): - indices = np.fromiter(indices, dtype=np.int64, count=-1) - - if num_tokens_vec is not None and not isinstance(num_tokens_vec, np.ndarray): - num_tokens_vec = np.fromiter(num_tokens_vec, dtype=np.int64, count=-1) - - if fixed_shapes is None: - if num_tokens_vec is None: - return batch_by_size_fn( - indices, - num_tokens_fn, - max_tokens, - max_sentences, - bsz_mult, - ) - else: - return batch_by_size_vec( - indices, - num_tokens_vec, - max_tokens, - max_sentences, - bsz_mult, - ) - - else: - fixed_shapes = np.array(fixed_shapes, dtype=np.int64) - sort_order = np.lexsort( - [ - fixed_shapes[:, 1].argsort(), # length - fixed_shapes[:, 0].argsort(), # bsz - ] - ) - fixed_shapes_sorted = fixed_shapes[sort_order] - return batch_fixed_shapes_fast(indices, num_tokens_fn, fixed_shapes_sorted) - - -def post_process(sentence: str, symbol: str): - if symbol == "sentencepiece": - sentence = sentence.replace(" ", "").replace("\u2581", " ").strip() - elif symbol == "wordpiece": - sentence = sentence.replace(" ", "").replace("_", " ").strip() - elif symbol == "letter": - sentence = sentence.replace(" ", "").replace("|", " ").strip() - elif symbol == "silence": - import re - sentence = sentence.replace("", "") - sentence = re.sub(' +', ' ', sentence).strip() - elif symbol == "_EOW": - sentence = sentence.replace(" ", "").replace("_EOW", " ").strip() - elif symbol in {"subword_nmt", "@@ ", "@@"}: - if symbol == "subword_nmt": - symbol = "@@ " - sentence = (sentence + " ").replace(symbol, "").rstrip() - elif symbol == "none": - pass - elif symbol is not None: - raise NotImplementedError(f"Unknown post_process option: {symbol}") - return sentence - - -def compute_mask_indices( - shape: Tuple[int, int], - padding_mask: Optional[torch.Tensor], - mask_prob: float, - mask_length: int, - mask_type: str = "static", - mask_other: float = 0.0, - min_masks: int = 0, - no_overlap: bool = False, - min_space: int = 0, -) -> np.ndarray: - """ - Computes random mask spans for a given shape - - Args: - shape: the the shape for which to compute masks. - should be of size 2 where first element is batch size and 2nd is timesteps - padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements - mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by - number of timesteps divided by length of mask span to mask approximately this percentage of all elements. - however due to overlaps, the actual number will be smaller (unless no_overlap is True) - mask_type: how to compute mask lengths - static = fixed size - uniform = sample from uniform distribution [mask_other, mask_length*2] - normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element - poisson = sample from possion distribution with lambda = mask length - min_masks: minimum number of masked spans - no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping - min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans - """ - - bsz, all_sz = shape - mask = np.full((bsz, all_sz), False) - - all_num_mask = int( - # add a random number for probabilistic rounding - mask_prob * all_sz / float(mask_length) - + np.random.rand() - ) - - all_num_mask = max(min_masks, all_num_mask) - - mask_idcs = [] - for i in range(bsz): - if padding_mask is not None: - sz = all_sz - padding_mask[i].long().sum().item() - num_mask = int( - # add a random number for probabilistic rounding - mask_prob * sz / float(mask_length) - + np.random.rand() - ) - num_mask = max(min_masks, num_mask) - else: - sz = all_sz - num_mask = all_num_mask - - if mask_type == "static": - lengths = np.full(num_mask, mask_length) - elif mask_type == "uniform": - lengths = np.random.randint(mask_other, mask_length * 2 + 1, size=num_mask) - elif mask_type == "normal": - lengths = np.random.normal(mask_length, mask_other, size=num_mask) - lengths = [max(1, int(round(x))) for x in lengths] - elif mask_type == "poisson": - lengths = np.random.poisson(mask_length, size=num_mask) - lengths = [int(round(x)) for x in lengths] - else: - raise Exception("unknown mask selection " + mask_type) - - if sum(lengths) == 0: - lengths[0] = min(mask_length, sz - 1) - - if no_overlap: - mask_idc = [] - - def arrange(s, e, length, keep_length): - span_start = np.random.randint(s, e - length) - mask_idc.extend(span_start + i for i in range(length)) - - new_parts = [] - if span_start - s - min_space >= keep_length: - new_parts.append((s, span_start - min_space + 1)) - if e - span_start - keep_length - min_space > keep_length: - new_parts.append((span_start + length + min_space, e)) - return new_parts - - parts = [(0, sz)] - min_length = min(lengths) - for length in sorted(lengths, reverse=True): - lens = np.fromiter( - (e - s if e - s >= length + min_space else 0 for s, e in parts), - np.int, - ) - l_sum = np.sum(lens) - if l_sum == 0: - break - probs = lens / np.sum(lens) - c = np.random.choice(len(parts), p=probs) - s, e = parts.pop(c) - parts.extend(arrange(s, e, length, min_length)) - mask_idc = np.asarray(mask_idc) - else: - min_len = min(lengths) - if sz - min_len <= num_mask: - min_len = sz - num_mask - 1 - - mask_idc = np.random.choice(sz - min_len, num_mask, replace=False) - - mask_idc = np.asarray( - [ - mask_idc[j] + offset - for j in range(len(mask_idc)) - for offset in range(lengths[j]) - ] - ) - - mask_idcs.append(np.unique(mask_idc[mask_idc < sz])) - - min_len = min([len(m) for m in mask_idcs]) - for i, mask_idc in enumerate(mask_idcs): - if len(mask_idc) > min_len: - mask_idc = np.random.choice(mask_idc, min_len, replace=False) - mask[i, mask_idc] = True - - return mask - - -def get_mem_usage(): - try: - import psutil - - mb = 1024 * 1024 - return f"used={psutil.virtual_memory().used / mb}Mb; avail={psutil.virtual_memory().available / mb}Mb" - except ImportError: - return "N/A" - - -# lens: torch.LongTensor -# returns: torch.BoolTensor -def lengths_to_padding_mask(lens): - bsz, max_lens = lens.size(0), torch.max(lens).item() - mask = torch.arange(max_lens).to(lens.device).view(1, max_lens) - mask = mask.expand(bsz, -1) >= lens.view(bsz, 1).expand(-1, max_lens) - return mask - - -# lens: torch.LongTensor -# returns: torch.BoolTensor -def lengths_to_mask(lens): - return ~lengths_to_padding_mask(lens) - - -def get_buckets(sizes, num_buckets): - buckets = np.unique( - np.percentile( - sizes, - np.linspace(0, 100, num_buckets + 1), - interpolation='lower', - )[1:] - ) - return buckets - - -def get_bucketed_sizes(orig_sizes, buckets): - sizes = np.copy(orig_sizes) - assert np.min(sizes) >= 0 - start_val = -1 - for end_val in buckets: - mask = (sizes > start_val) & (sizes <= end_val) - sizes[mask] = end_val - start_val = end_val - return sizes - - - -def _find_extra_valid_paths(dataset_path: str) -> set: - paths = utils.split_paths(dataset_path) - all_valid_paths = set() - for sub_dir in paths: - contents = PathManager.ls(sub_dir) - valid_paths = [c for c in contents if re.match("valid*[0-9].*", c) is not None] - all_valid_paths |= {os.path.basename(p) for p in valid_paths} - # Remove .bin, .idx etc - roots = {os.path.splitext(p)[0] for p in all_valid_paths} - return roots - - -def raise_if_valid_subsets_unintentionally_ignored(train_cfg) -> None: - """Raises if there are paths matching 'valid*[0-9].*' which are not combined or ignored.""" - if ( - train_cfg.dataset.ignore_unused_valid_subsets - or train_cfg.dataset.combine_valid_subsets - or train_cfg.dataset.disable_validation - or not hasattr(train_cfg.task, "data") - ): - return - other_paths = _find_extra_valid_paths(train_cfg.task.data) - specified_subsets = train_cfg.dataset.valid_subset.split(",") - ignored_paths = [p for p in other_paths if p not in specified_subsets] - if ignored_paths: - advice = "Set --combine-val to combine them or --ignore-unused-valid-subsets to ignore them." - msg = f"Valid paths {ignored_paths} will be ignored. {advice}" - raise ValueError(msg) diff --git a/spaces/HgMenon/Transcribe_V0.2/src/hooks/progressListener.py b/spaces/HgMenon/Transcribe_V0.2/src/hooks/progressListener.py deleted file mode 100644 index a7852a24e237ae864bbce5f37674e1f7c817a1b3..0000000000000000000000000000000000000000 --- a/spaces/HgMenon/Transcribe_V0.2/src/hooks/progressListener.py +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Union - -class ProgressListener: - def on_progress(self, current: Union[int, float], total: Union[int, float]): - self.total = total - - def on_finished(self): - pass \ No newline at end of file diff --git a/spaces/Hina4867/bingo/src/components/ui/separator.tsx b/spaces/Hina4867/bingo/src/components/ui/separator.tsx deleted file mode 100644 index 6c55e0b2ca8e2436658a06748aadbff7cd700db0..0000000000000000000000000000000000000000 --- a/spaces/Hina4867/bingo/src/components/ui/separator.tsx +++ /dev/null @@ -1,31 +0,0 @@ -'use client' - -import * as React from 'react' -import * as SeparatorPrimitive from '@radix-ui/react-separator' - -import { cn } from '@/lib/utils' - -const Separator = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->( - ( - { className, orientation = 'horizontal', decorative = true, ...props }, - ref - ) => ( - - ) -) -Separator.displayName = SeparatorPrimitive.Root.displayName - -export { Separator } diff --git a/spaces/Hunter731/Unity3D-RTS/index.html b/spaces/Hunter731/Unity3D-RTS/index.html deleted file mode 100644 index ddd2741261ccdc4f693fa5b1d38942cfbab6362d..0000000000000000000000000000000000000000 --- a/spaces/Hunter731/Unity3D-RTS/index.html +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - Unity WebGL Player | RTS - - - - -
- -
- -
-
-
-
-
- -
- - - diff --git a/spaces/ICML2022/OFA/fairseq/CONTRIBUTING.md b/spaces/ICML2022/OFA/fairseq/CONTRIBUTING.md deleted file mode 100644 index 3930c46196b7b6082cacc76fd5808b49677ae805..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/CONTRIBUTING.md +++ /dev/null @@ -1,28 +0,0 @@ -# Contributing to Facebook AI Research Sequence-to-Sequence Toolkit (fairseq) -We want to make contributing to this project as easy and transparent as -possible. - -## Pull Requests -We actively welcome your pull requests. - -1. Fork the repo and create your branch from `main`. -2. If you've added code that should be tested, add tests. -3. If you've changed APIs, update the documentation. -4. Ensure the test suite passes. -5. Make sure your code lints. -6. If you haven't already, complete the Contributor License Agreement ("CLA"). - -## Contributor License Agreement ("CLA") -In order to accept your pull request, we need you to submit a CLA. You only need -to do this once to work on any of Facebook's open source projects. - -Complete your CLA here: - -## Issues -We use GitHub issues to track public bugs. Please ensure your description is -clear and has sufficient instructions to be able to reproduce the issue. - -## License -By contributing to Facebook AI Research Sequence-to-Sequence Toolkit (fairseq), -you agree that your contributions will be licensed under the LICENSE file in -the root directory of this source tree. diff --git a/spaces/ICML2022/OFA/fairseq/examples/multilingual/data_scripts/utils/strip_sgm.sh b/spaces/ICML2022/OFA/fairseq/examples/multilingual/data_scripts/utils/strip_sgm.sh deleted file mode 100644 index 7f4f61d7b1a46f51a1221de6b336cb70b5a0b8b3..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/multilingual/data_scripts/utils/strip_sgm.sh +++ /dev/null @@ -1 +0,0 @@ -grep "seg id" | sed 's///g' | sed 's/<\/seg>//g' diff --git a/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/data/asr_dataset.py b/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/data/asr_dataset.py deleted file mode 100644 index 63a6fcac85d73b1fce8e4d044b4209b1b67fa8ce..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/data/asr_dataset.py +++ /dev/null @@ -1,122 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import os - -import numpy as np -from fairseq.data import FairseqDataset - -from . import data_utils -from .collaters import Seq2SeqCollater - - -class AsrDataset(FairseqDataset): - """ - A dataset representing speech and corresponding transcription. - - Args: - aud_paths: (List[str]): A list of str with paths to audio files. - aud_durations_ms (List[int]): A list of int containing the durations of - audio files. - tgt (List[torch.LongTensor]): A list of LongTensors containing the indices - of target transcriptions. - tgt_dict (~fairseq.data.Dictionary): target vocabulary. - ids (List[str]): A list of utterance IDs. - speakers (List[str]): A list of speakers corresponding to utterances. - num_mel_bins (int): Number of triangular mel-frequency bins (default: 80) - frame_length (float): Frame length in milliseconds (default: 25.0) - frame_shift (float): Frame shift in milliseconds (default: 10.0) - """ - - def __init__( - self, - aud_paths, - aud_durations_ms, - tgt, - tgt_dict, - ids, - speakers, - num_mel_bins=80, - frame_length=25.0, - frame_shift=10.0, - ): - assert frame_length > 0 - assert frame_shift > 0 - assert all(x > frame_length for x in aud_durations_ms) - self.frame_sizes = [ - int(1 + (d - frame_length) / frame_shift) for d in aud_durations_ms - ] - - assert len(aud_paths) > 0 - assert len(aud_paths) == len(aud_durations_ms) - assert len(aud_paths) == len(tgt) - assert len(aud_paths) == len(ids) - assert len(aud_paths) == len(speakers) - self.aud_paths = aud_paths - self.tgt_dict = tgt_dict - self.tgt = tgt - self.ids = ids - self.speakers = speakers - self.num_mel_bins = num_mel_bins - self.frame_length = frame_length - self.frame_shift = frame_shift - - self.s2s_collater = Seq2SeqCollater( - 0, - 1, - pad_index=self.tgt_dict.pad(), - eos_index=self.tgt_dict.eos(), - move_eos_to_beginning=True, - ) - - def __getitem__(self, index): - import torchaudio - import torchaudio.compliance.kaldi as kaldi - - tgt_item = self.tgt[index] if self.tgt is not None else None - - path = self.aud_paths[index] - if not os.path.exists(path): - raise FileNotFoundError("Audio file not found: {}".format(path)) - sound, sample_rate = torchaudio.load_wav(path) - output = kaldi.fbank( - sound, - num_mel_bins=self.num_mel_bins, - frame_length=self.frame_length, - frame_shift=self.frame_shift, - ) - output_cmvn = data_utils.apply_mv_norm(output) - - return {"id": index, "data": [output_cmvn.detach(), tgt_item]} - - def __len__(self): - return len(self.aud_paths) - - def collater(self, samples): - """Merge a list of samples to form a mini-batch. - - Args: - samples (List[int]): sample indices to collate - - Returns: - dict: a mini-batch suitable for forwarding with a Model - """ - return self.s2s_collater.collate(samples) - - def num_tokens(self, index): - return self.frame_sizes[index] - - def size(self, index): - """Return an example's size as a float or tuple. This value is used when - filtering a dataset with ``--max-positions``.""" - return ( - self.frame_sizes[index], - len(self.tgt[index]) if self.tgt is not None else 0, - ) - - def ordered_indices(self): - """Return an ordered list of indices. Batches will be constructed based - on this order.""" - return np.arange(len(self)) diff --git a/spaces/Iceclear/StableSR/StableSR/ldm/modules/attention.py b/spaces/Iceclear/StableSR/StableSR/ldm/modules/attention.py deleted file mode 100644 index 89b11a9ec385e28dc2161c02faa642950df0cfac..0000000000000000000000000000000000000000 --- a/spaces/Iceclear/StableSR/StableSR/ldm/modules/attention.py +++ /dev/null @@ -1,412 +0,0 @@ -from inspect import isfunction -import math -import torch -import torch.nn.functional as F -from torch import nn, einsum -from einops import rearrange, repeat - -from ldm.modules.diffusionmodules.util import checkpoint - -try: - import xformers - import xformers.ops - XFORMERS_IS_AVAILBLE = True -except: - XFORMERS_IS_AVAILBLE = False - -# CrossAttn precision handling -import os -_ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32") - -def exists(val): - return val is not None - - -def uniq(arr): - return{el: True for el in arr}.keys() - - -def default(val, d): - if exists(val): - return val - return d() if isfunction(d) else d - - -def max_neg_value(t): - return -torch.finfo(t.dtype).max - - -def init_(tensor): - dim = tensor.shape[-1] - std = 1 / math.sqrt(dim) - tensor.uniform_(-std, std) - return tensor - - -# feedforward -class GEGLU(nn.Module): - def __init__(self, dim_in, dim_out): - super().__init__() - self.proj = nn.Linear(dim_in, dim_out * 2) - - def forward(self, x): - x, gate = self.proj(x).chunk(2, dim=-1) - return x * F.gelu(gate) - - -class FeedForward(nn.Module): - def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.): - super().__init__() - inner_dim = int(dim * mult) - dim_out = default(dim_out, dim) - project_in = nn.Sequential( - nn.Linear(dim, inner_dim), - nn.GELU() - ) if not glu else GEGLU(dim, inner_dim) - - self.net = nn.Sequential( - project_in, - nn.Dropout(dropout), - nn.Linear(inner_dim, dim_out) - ) - - def forward(self, x): - return self.net(x) - - -def zero_module(module): - """ - Zero out the parameters of a module and return it. - """ - for p in module.parameters(): - p.detach().zero_() - return module - - -def Normalize(in_channels): - return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True) - - -class LinearAttention(nn.Module): - def __init__(self, dim, heads=4, dim_head=32): - super().__init__() - self.heads = heads - hidden_dim = dim_head * heads - self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False) - self.to_out = nn.Conv2d(hidden_dim, dim, 1) - - def forward(self, x): - b, c, h, w = x.shape - qkv = self.to_qkv(x) - q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3) - k = k.softmax(dim=-1) - context = torch.einsum('bhdn,bhen->bhde', k, v) - out = torch.einsum('bhde,bhdn->bhen', context, q) - out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w) - return self.to_out(out) - - -class SpatialSelfAttention(nn.Module): - def __init__(self, in_channels): - super().__init__() - self.in_channels = in_channels - - self.norm = Normalize(in_channels) - self.q = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.k = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.v = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - self.proj_out = torch.nn.Conv2d(in_channels, - in_channels, - kernel_size=1, - stride=1, - padding=0) - - def forward(self, x): - h_ = x - h_ = self.norm(h_) - q = self.q(h_) - k = self.k(h_) - v = self.v(h_) - - # compute attention - b,c,h,w = q.shape - q = rearrange(q, 'b c h w -> b (h w) c') - k = rearrange(k, 'b c h w -> b c (h w)') - w_ = torch.einsum('bij,bjk->bik', q, k) - - w_ = w_ * (int(c)**(-0.5)) - w_ = torch.nn.functional.softmax(w_, dim=2) - - # attend to values - v = rearrange(v, 'b c h w -> b c (h w)') - w_ = rearrange(w_, 'b i j -> b j i') - h_ = torch.einsum('bij,bjk->bik', v, w_) - h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h) - h_ = self.proj_out(h_) - - return x+h_ - - -class CrossAttention(nn.Module): - def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.): - super().__init__() - inner_dim = dim_head * heads - context_dim = default(context_dim, query_dim) - - self.scale = dim_head ** -0.5 - self.heads = heads - - self.to_q = nn.Linear(query_dim, inner_dim, bias=False) - self.to_k = nn.Linear(context_dim, inner_dim, bias=False) - self.to_v = nn.Linear(context_dim, inner_dim, bias=False) - - self.to_out = nn.Sequential( - nn.Linear(inner_dim, query_dim), - nn.Dropout(dropout) - ) - - def forward(self, x, context=None, mask=None): - h = self.heads - - q = self.to_q(x) - context = default(context, x) - k = self.to_k(context) - v = self.to_v(context) - - q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v)) - - sim = einsum('b i d, b j d -> b i j', q, k) * self.scale - - if exists(mask): - mask = rearrange(mask, 'b ... -> b (...)') - max_neg_value = -torch.finfo(sim.dtype).max - mask = repeat(mask, 'b j -> (b h) () j', h=h) - sim.masked_fill_(~mask, max_neg_value) - - # attention, what we cannot get enough of - attn = sim.softmax(dim=-1) - - out = einsum('b i j, b j d -> b i d', attn, v) - out = rearrange(out, '(b h) n d -> b n (h d)', h=h) - return self.to_out(out) - -class MemoryEfficientCrossAttention(nn.Module): - # https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223 - def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0): - super().__init__() - print(f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using " - f"{heads} heads.") - inner_dim = dim_head * heads - context_dim = default(context_dim, query_dim) - - self.heads = heads - self.dim_head = dim_head - - self.to_q = nn.Linear(query_dim, inner_dim, bias=False) - self.to_k = nn.Linear(context_dim, inner_dim, bias=False) - self.to_v = nn.Linear(context_dim, inner_dim, bias=False) - - self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout)) - self.attention_op: Optional[Any] = None - - def forward(self, x, context=None, mask=None): - q = self.to_q(x) - context = default(context, x) - k = self.to_k(context) - v = self.to_v(context) - - b, _, _ = q.shape - q, k, v = map( - lambda t: t.unsqueeze(3) - .reshape(b, t.shape[1], self.heads, self.dim_head) - .permute(0, 2, 1, 3) - .reshape(b * self.heads, t.shape[1], self.dim_head) - .contiguous(), - (q, k, v), - ) - - # actually compute the attention, what we cannot get enough of - out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op) - - if exists(mask): - raise NotImplementedError - out = ( - out.unsqueeze(0) - .reshape(b, self.heads, out.shape[1], self.dim_head) - .permute(0, 2, 1, 3) - .reshape(b, out.shape[1], self.heads * self.dim_head) - ) - return self.to_out(out) - -class BasicTransformerBlock(nn.Module): - def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=False): - super().__init__() - self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout) # is a self-attention - self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) - self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim, - heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none - self.norm1 = nn.LayerNorm(dim) - self.norm2 = nn.LayerNorm(dim) - self.norm3 = nn.LayerNorm(dim) - self.checkpoint = checkpoint - - def forward(self, x, context=None): - return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint) - - def _forward(self, x, context=None): - x = self.attn1(self.norm1(x)) + x - x = self.attn2(self.norm2(x), context=context) + x - x = self.ff(self.norm3(x)) + x - return x - -class BasicTransformerBlockV2(nn.Module): - ATTENTION_MODES = { - "softmax": CrossAttention, # vanilla attention - "softmax-xformers": MemoryEfficientCrossAttention - } - def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True, - disable_self_attn=False): - super().__init__() - attn_mode = "softmax-xformers" if XFORMERS_IS_AVAILBLE else "softmax" - assert attn_mode in self.ATTENTION_MODES - attn_cls = self.ATTENTION_MODES[attn_mode] - self.disable_self_attn = disable_self_attn - self.attn1 = attn_cls(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout, - context_dim=context_dim if self.disable_self_attn else None) # is a self-attention if not self.disable_self_attn - self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) - self.attn2 = attn_cls(query_dim=dim, context_dim=context_dim, - heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none - self.norm1 = nn.LayerNorm(dim) - self.norm2 = nn.LayerNorm(dim) - self.norm3 = nn.LayerNorm(dim) - self.checkpoint = checkpoint - - def forward(self, x, context=None): - return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint) - - def _forward(self, x, context=None): - x = self.attn1(self.norm1(x), context=context if self.disable_self_attn else None) + x - x = self.attn2(self.norm2(x), context=context) + x - x = self.ff(self.norm3(x)) + x - return x - -class SpatialTransformer(nn.Module): - """ - Transformer block for image-like data. - First, project the input (aka embedding) - and reshape to b, t, d. - Then apply standard transformer action. - Finally, reshape to image - """ - def __init__(self, in_channels, n_heads, d_head, - depth=1, dropout=0., context_dim=None): - super().__init__() - self.in_channels = in_channels - inner_dim = n_heads * d_head - self.norm = Normalize(in_channels) - - self.proj_in = nn.Conv2d(in_channels, - inner_dim, - kernel_size=1, - stride=1, - padding=0) - - self.transformer_blocks = nn.ModuleList( - [BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim) - for d in range(depth)] - ) - - self.proj_out = zero_module(nn.Conv2d(inner_dim, - in_channels, - kernel_size=1, - stride=1, - padding=0)) - - def forward(self, x, context=None): - # note: if no context is given, cross-attention defaults to self-attention - b, c, h, w = x.shape - x_in = x - x = self.norm(x) - x = self.proj_in(x) - x = rearrange(x, 'b c h w -> b (h w) c') - for block in self.transformer_blocks: - x = block(x, context=context) - x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w) - x = self.proj_out(x) - return x + x_in - -class SpatialTransformerV2(nn.Module): - """ - Transformer block for image-like data. - First, project the input (aka embedding) - and reshape to b, t, d. - Then apply standard transformer action. - Finally, reshape to image - NEW: use_linear for more efficiency instead of the 1x1 convs - """ - def __init__(self, in_channels, n_heads, d_head, - depth=1, dropout=0., context_dim=None, - disable_self_attn=False, use_linear=False, - use_checkpoint=False): - super().__init__() - if exists(context_dim) and not isinstance(context_dim, list): - context_dim = [context_dim] - self.in_channels = in_channels - inner_dim = n_heads * d_head - self.norm = Normalize(in_channels) - if not use_linear: - self.proj_in = nn.Conv2d(in_channels, - inner_dim, - kernel_size=1, - stride=1, - padding=0) - else: - self.proj_in = nn.Linear(in_channels, inner_dim) - - self.transformer_blocks = nn.ModuleList( - [BasicTransformerBlockV2(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d], - disable_self_attn=disable_self_attn, checkpoint=use_checkpoint) - for d in range(depth)] - ) - if not use_linear: - self.proj_out = zero_module(nn.Conv2d(inner_dim, - in_channels, - kernel_size=1, - stride=1, - padding=0)) - else: - self.proj_out = zero_module(nn.Linear(in_channels, inner_dim)) - self.use_linear = use_linear - - def forward(self, x, context=None): - # note: if no context is given, cross-attention defaults to self-attention - if not isinstance(context, list): - context = [context] - b, c, h, w = x.shape - x_in = x - x = self.norm(x) - if not self.use_linear: - x = self.proj_in(x) - x = rearrange(x, 'b c h w -> b (h w) c').contiguous() - if self.use_linear: - x = self.proj_in(x) - for i, block in enumerate(self.transformer_blocks): - x = block(x, context=context[i]) - if self.use_linear: - x = self.proj_out(x) - x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w).contiguous() - if not self.use_linear: - x = self.proj_out(x) - return x + x_in diff --git a/spaces/Iceclear/StableSR/StableSR/ldm/modules/distributions/__init__.py b/spaces/Iceclear/StableSR/StableSR/ldm/modules/distributions/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Illumotion/Koboldcpp/examples/infill/infill.cpp b/spaces/Illumotion/Koboldcpp/examples/infill/infill.cpp deleted file mode 100644 index 9ec75ce425b2a6c771e115c27f780c96f17f6ce2..0000000000000000000000000000000000000000 --- a/spaces/Illumotion/Koboldcpp/examples/infill/infill.cpp +++ /dev/null @@ -1,769 +0,0 @@ -#include "common.h" - -#include "console.h" -#include "llama.h" -#include "build-info.h" -#include "grammar-parser.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) -#include -#include -#elif defined (_WIN32) -#define WIN32_LEAN_AND_MEAN -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#include -#endif - -#if defined(_MSC_VER) -#pragma warning(disable: 4244 4267) // possible loss of data -#endif - -static llama_context ** g_ctx; -static llama_model ** g_model; -static gpt_params * g_params; -static std::vector * g_input_tokens; -static std::ostringstream * g_output_ss; -static std::vector * g_output_tokens; -static bool is_interacting = false; - - -static void write_logfile( - const llama_context * ctx, const gpt_params & params, const llama_model * model, - const std::vector & input_tokens, const std::string & output, - const std::vector & output_tokens -) { - if (params.logdir.empty()) { - return; - } - - const std::string timestamp = get_sortable_timestamp(); - - const bool success = create_directory_with_parents(params.logdir); - if (!success) { - fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n", - __func__, params.logdir.c_str()); - return; - } - - const std::string logfile_path = params.logdir + timestamp + ".yml"; - FILE * logfile = fopen(logfile_path.c_str(), "w"); - - if (logfile == NULL) { - fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str()); - return; - } - - fprintf(logfile, "binary: infill\n"); - char model_desc[128]; - llama_model_desc(model, model_desc, sizeof(model_desc)); - dump_non_result_info_yaml(logfile, params, ctx, timestamp, input_tokens, model_desc); - - fprintf(logfile, "\n"); - fprintf(logfile, "######################\n"); - fprintf(logfile, "# Generation Results #\n"); - fprintf(logfile, "######################\n"); - fprintf(logfile, "\n"); - - dump_string_yaml_multiline(logfile, "output", output.c_str()); - dump_vector_int_yaml(logfile, "output_tokens", output_tokens); - - llama_dump_timing_info_yaml(logfile, ctx); - fclose(logfile); -} - -#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32) -static void sigint_handler(int signo) { - if (signo == SIGINT) { - if (!is_interacting) { - is_interacting = true; - } else { - console::cleanup(); - printf("\n"); - llama_print_timings(*g_ctx); - write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens); - _exit(130); - } - } -} -#endif - -int main(int argc, char ** argv) { - gpt_params params; - g_params = ¶ms; - - if (!gpt_params_parse(argc, argv, params)) { - return 1; - } - -#ifndef LOG_DISABLE_LOGS - log_set_target(log_filename_generator("infill", "log")); - LOG_TEE("Log start\n"); - log_dump_cmdline(argc, argv); -#endif // LOG_DISABLE_LOGS - - console::init(params.simple_io, params.use_color); - atexit([]() { console::cleanup(); }); - - if (params.logits_all) { - printf("\n************\n"); - printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__); - printf("************\n\n"); - - return 0; - } - - if (params.embedding) { - printf("\n************\n"); - printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__); - printf("************\n\n"); - - return 0; - } - - if (params.n_ctx != 0 && params.n_ctx < 8) { - LOG_TEE("%s: warning: minimum context size is 8, using minimum size.\n", __func__); - params.n_ctx = 8; - } - if (params.instruct) { - printf("\n************\n"); - printf("%s: please use the 'main' tool for instruct mode\n", __func__); - printf("************\n\n"); - - return 0; - } - if (!params.antiprompt.empty()) { - printf("\n************\n"); - printf("%s: please use the 'main' tool for antiprompt mode\n", __func__); - printf("************\n\n"); - - return 0; - } - if (!params.interactive_first && (params.input_prefix.empty() && params.input_suffix.empty())) { - printf("\n************\n"); - printf("%s: please use '--interactive_first' or specify '--in_prefix' and/or '--in_suffix'\n", __func__); - printf("************\n\n"); - - return 0; - } - if (params.random_prompt) { - printf("\n************\n"); - printf("%s: please use the 'main' tool for random prompt mode\n", __func__); - printf("************\n\n"); - - return 0; - } - if (!params.path_prompt_cache.empty()) { - printf("\n************\n"); - printf("%s: infill does not support prompt caching\n", __func__); - printf("************\n\n"); - - return 0; - } - - if (params.rope_freq_base != 0.0) { - LOG_TEE("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base); - } - - if (params.rope_freq_scale != 0.0) { - LOG_TEE("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale); - } - - LOG_TEE("%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT); - LOG_TEE("%s: built with %s for %s\n", __func__, BUILD_COMPILER, BUILD_TARGET); - - if (params.seed == LLAMA_DEFAULT_SEED) { - params.seed = time(NULL); - } - - LOG_TEE("%s: seed = %u\n", __func__, params.seed); - - std::mt19937 rng(params.seed); - - LOG("%s: llama backend init\n", __func__); - llama_backend_init(params.numa); - - llama_model * model; - llama_context * ctx; - llama_context * ctx_guidance = NULL; - g_model = &model; - g_ctx = &ctx; - - // load the model and apply lora adapter, if any - LOG("%s: load the model and apply lora adapter, if any\n", __func__); - std::tie(model, ctx) = llama_init_from_gpt_params(params); - if (params.cfg_scale > 1.f) { - struct llama_context_params lparams = llama_context_params_from_gpt_params(params); - ctx_guidance = llama_new_context_with_model(model, lparams); - } - - if (model == NULL) { - LOG_TEE("%s: error: unable to load model\n", __func__); - return 1; - } - - const int n_ctx_train = llama_n_ctx_train(model); - const int n_ctx = llama_n_ctx(ctx); - LOG("n_ctx: %d\n", n_ctx); - - if (n_ctx > n_ctx_train) { - LOG_TEE("%s: warning: model was trained on only %d context tokens (%d specified)\n", - __func__, n_ctx_train, n_ctx); - } - - // print system information - { - LOG_TEE("\n"); - LOG_TEE("%s\n", get_system_info(params).c_str()); - } - const bool add_bos = llama_vocab_type(model) == LLAMA_VOCAB_TYPE_SPM; - LOG("add_bos: %d\n", add_bos); - - std::vector embd_inp; - std::vector inp_pfx = ::llama_tokenize(ctx, params.input_prefix, add_bos); - std::vector inp_sfx = ::llama_tokenize(ctx, params.input_suffix, add_bos); - inp_pfx.insert(inp_pfx.begin(), llama_token_prefix(ctx)); - inp_sfx.insert(inp_sfx.begin(), llama_token_suffix(ctx)); - embd_inp = inp_pfx; - embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end()); - embd_inp.push_back(llama_token_middle(ctx)); - - LOG("prefix: \"%s\"\n", log_tostr(params.input_prefix)); - LOG("suffix: \"%s\"\n", log_tostr(params.input_suffix)); - LOG("tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp)); - - // Should not run without any tokens - if (embd_inp.empty()) { - embd_inp.push_back(llama_token_bos(ctx)); - LOG("embd_inp was considered empty and bos was added: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp)); - } - - // Tokenize negative prompt - std::vector guidance_inp; - int guidance_offset = 0; - int original_prompt_len = 0; - if (ctx_guidance) { - LOG("cfg_negative_prompt: \"%s\"\n", log_tostr(params.cfg_negative_prompt)); - - guidance_inp = ::llama_tokenize(ctx_guidance, params.cfg_negative_prompt, add_bos); - LOG("guidance_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_guidance, guidance_inp)); - - std::vector original_inp = ::llama_tokenize(ctx, params.prompt, add_bos); - LOG("original_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, original_inp)); - - original_prompt_len = original_inp.size(); - guidance_offset = (int)guidance_inp.size() - original_prompt_len; - LOG("original_prompt_len: %s", log_tostr(original_prompt_len)); - LOG("guidance_offset: %s", log_tostr(guidance_offset)); - } - - if ((int) embd_inp.size() > n_ctx - 4) { - LOG_TEE("%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4); - return 1; - } - - // number of tokens to keep when resetting context - if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) { - params.n_keep = (int)embd_inp.size(); - } - - LOG("inp_pfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_pfx)); - LOG("inp_sfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_sfx)); - - - // enable interactive mode if interactive start is specified - if (params.interactive_first) { - params.interactive = true; - } - - if (params.verbose_prompt) { - LOG_TEE("\n"); - LOG_TEE("%s: prompt: '%s'\n", __func__, params.prompt.c_str()); - LOG_TEE("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size()); - for (int i = 0; i < (int) embd_inp.size(); i++) { - LOG_TEE("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str()); - } - - if (ctx_guidance) { - LOG_TEE("\n"); - LOG_TEE("%s: negative prompt: '%s'\n", __func__, params.cfg_negative_prompt.c_str()); - LOG_TEE("%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size()); - for (int i = 0; i < (int) guidance_inp.size(); i++) { - LOG_TEE("%6d -> '%s'\n", guidance_inp[i], llama_token_to_piece(ctx, guidance_inp[i]).c_str()); - } - } - - if (params.n_keep > 0) { - LOG_TEE("%s: static prompt based on n_keep: '", __func__); - for (int i = 0; i < params.n_keep; i++) { - LOG_TEE("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str()); - } - LOG_TEE("'\n"); - } - LOG_TEE("\n"); - } - - if (params.interactive) { -#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) - struct sigaction sigint_action; - sigint_action.sa_handler = sigint_handler; - sigemptyset (&sigint_action.sa_mask); - sigint_action.sa_flags = 0; - sigaction(SIGINT, &sigint_action, NULL); -#elif defined (_WIN32) - auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL { - return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false; - }; - SetConsoleCtrlHandler(reinterpret_cast(console_ctrl_handler), true); -#endif - - LOG_TEE("%s: interactive mode on.\n", __func__); - - if (params.input_prefix_bos) { - LOG_TEE("Input prefix with BOS\n"); - } - - if (!params.input_prefix.empty()) { - LOG_TEE("Input prefix: '%s'\n", params.input_prefix.c_str()); - } - - if (!params.input_suffix.empty()) { - LOG_TEE("Input suffix: '%s'\n", params.input_suffix.c_str()); - } - } - LOG_TEE("sampling: repeat_last_n = %d, repeat_penalty = %f, presence_penalty = %f, frequency_penalty = %f, top_k = %d, tfs_z = %f, top_p = %f, typical_p = %f, temp = %f, mirostat = %d, mirostat_lr = %f, mirostat_ent = %f\n", - params.repeat_last_n, params.repeat_penalty, params.presence_penalty, params.frequency_penalty, params.top_k, params.tfs_z, params.top_p, params.typical_p, params.temp, params.mirostat, params.mirostat_eta, params.mirostat_tau); - LOG_TEE("generate: n_ctx = %d, n_batch = %d, n_predict = %d, n_keep = %d\n", n_ctx, params.n_batch, params.n_predict, params.n_keep); - LOG_TEE("\n\n"); - - struct llama_grammar * grammar = NULL; - grammar_parser::parse_state parsed_grammar; - - if (!params.grammar.empty()) { - parsed_grammar = grammar_parser::parse(params.grammar.c_str()); - // will be empty (default) if there are parse errors - if (parsed_grammar.rules.empty()) { - return 1; - } - LOG_TEE("%s: grammar:\n", __func__); - grammar_parser::print_grammar(stderr, parsed_grammar); - LOG_TEE("\n"); - - { - auto it = params.logit_bias.find(llama_token_eos(ctx)); - if (it != params.logit_bias.end() && it->second == -INFINITY) { - LOG_TEE("%s: warning: EOS token is disabled, which will cause most grammars to fail\n", __func__); - } - } - - std::vector grammar_rules(parsed_grammar.c_rules()); - grammar = llama_grammar_init( - grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root")); - } - - // TODO: replace with ring-buffer - std::vector last_tokens(n_ctx); - std::fill(last_tokens.begin(), last_tokens.end(), 0); - LOG_TEE("\n##### Infill mode #####\n\n"); - if (params.infill) { - printf("\n************\n"); - printf("no need to specify '--infill', always running infill\n"); - printf("************\n\n"); - } - if (params.interactive) { - const char *control_message; - if (params.multiline_input) { - control_message = " - To return control to LLaMa, end your input with '\\'.\n" - " - To return control without starting a new line, end your input with '/'.\n"; - } else { - control_message = " - Press Return to return control to LLaMa.\n" - " - To return control without starting a new line, end your input with '/'.\n" - " - If you want to submit another line, end your input with '\\'.\n"; - } - LOG_TEE("== Running in interactive mode. ==\n"); -#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32) - LOG_TEE( " - Press Ctrl+C to interject at any time.\n"); -#endif - LOG_TEE( "%s\n", control_message); - - is_interacting = params.interactive_first; - } - - bool input_echo = true; - - int n_past = 0; - int n_remain = params.n_predict; - int n_consumed = 0; - int n_past_guidance = 0; - - std::vector input_tokens; g_input_tokens = &input_tokens; - std::vector output_tokens; g_output_tokens = &output_tokens; - std::ostringstream output_ss; g_output_ss = &output_ss; - - // the first thing we will do is to output the prompt, so set color accordingly - console::set_display(console::prompt); - - std::vector embd; - std::vector embd_guidance; - - const int n_vocab = llama_n_vocab(model); - - std::vector candidates; - candidates.reserve(n_vocab); - - while (n_remain != 0 || params.interactive) { - // predict - if (!embd.empty()) { - // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via - // --prompt or --file which uses the same value. - int max_embd_size = n_ctx - 4; - - // Ensure the input doesn't exceed the context size by truncating embd if necessary. - if ((int) embd.size() > max_embd_size) { - const int skipped_tokens = (int) embd.size() - max_embd_size; - embd.resize(max_embd_size); - - console::set_display(console::error); - printf("<>", skipped_tokens, skipped_tokens != 1 ? "s" : ""); - console::set_display(console::reset); - fflush(stdout); - } - - // infinite text generation via context swapping - // if we run out of context: - // - take the n_keep first tokens from the original prompt (via n_past) - // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches - if (n_past + (int) embd.size() + std::max(0, guidance_offset) > n_ctx) { - if (params.n_predict == -2) { - LOG_TEE("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict); - break; - } - - const int n_left = n_past - params.n_keep - 1; - const int n_discard = n_left/2; - - LOG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n", - n_past, n_left, n_ctx, params.n_keep, n_discard); - - llama_kv_cache_seq_rm (ctx, 0, params.n_keep + 1 , params.n_keep + n_discard + 1); - llama_kv_cache_seq_shift(ctx, 0, params.n_keep + 1 + n_discard, n_past, -n_discard); - - n_past -= n_discard; - - if (ctx_guidance) { - n_past_guidance -= n_discard; - } - - LOG("after swap: n_past = %d, n_past_guidance = %d\n", n_past, n_past_guidance); - - LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd)); - - } - - // evaluate tokens in batches - // embd is typically prepared beforehand to fit within a batch, but not always - - if (ctx_guidance) { - int input_size = 0; - llama_token * input_buf = NULL; - - if (n_past_guidance < (int) guidance_inp.size()) { - // Guidance context should have the same data with these modifications: - // - // * Replace the initial prompt - // * Shift everything by guidance_offset - embd_guidance = guidance_inp; - if (embd.begin() + original_prompt_len < embd.end()) { - embd_guidance.insert( - embd_guidance.end(), - embd.begin() + original_prompt_len, - embd.end() - ); - } - - input_buf = embd_guidance.data(); - input_size = embd_guidance.size(); - - LOG("guidance context: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_guidance)); - } else { - input_buf = embd.data(); - input_size = embd.size(); - } - - for (int i = 0; i < input_size; i += params.n_batch) { - int n_eval = std::min(input_size - i, params.n_batch); - if (llama_decode(ctx_guidance, llama_batch_get_one(input_buf + i, n_eval, n_past_guidance, 0))) { - LOG_TEE("%s : failed to eval\n", __func__); - return 1; - } - - n_past_guidance += n_eval; - } - } - - for (int i = 0; i < (int) embd.size(); i += params.n_batch) { - int n_eval = (int) embd.size() - i; - if (n_eval > params.n_batch) { - n_eval = params.n_batch; - } - - LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd)); - - if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) { - LOG_TEE("%s : failed to eval\n", __func__); - return 1; - } - - n_past += n_eval; - - LOG("n_past = %d\n", n_past); - } - - } - - embd.clear(); - embd_guidance.clear(); - - if ((int) embd_inp.size() <= n_consumed && !is_interacting) { - - const llama_token id = llama_sample_token(ctx, ctx_guidance, grammar, params, last_tokens, candidates); - - last_tokens.erase(last_tokens.begin()); - last_tokens.push_back(id); - - LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, last_tokens)); - - embd.push_back(id); - - // echo this to console - input_echo = true; - - // decrement remaining sampling budget - --n_remain; - - LOG("n_remain: %d\n", n_remain); - } else { - // some user input remains from prompt or interaction, forward it to processing - LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed); - while ((int) embd_inp.size() > n_consumed) { - embd.push_back(embd_inp[n_consumed]); - last_tokens.erase(last_tokens.begin()); - last_tokens.push_back(embd_inp[n_consumed]); - ++n_consumed; - if ((int) embd.size() >= params.n_batch) { - break; - } - } - } - - // display text - if (input_echo) { - for (auto id : embd) { - const std::string token_str = llama_token_to_piece(ctx, id); - printf("%s", token_str.c_str()); - - if (embd.size() > 1) { - input_tokens.push_back(id); - } else { - output_tokens.push_back(id); - output_ss << token_str; - } - } - fflush(stdout); - } - // reset color to default if we there is no pending user input - if (input_echo && (int) embd_inp.size() == n_consumed) { - console::set_display(console::reset); - } - - // if not currently processing queued inputs; - if ((int) embd_inp.size() <= n_consumed) { - - // deal with eot token in infill mode - if ((last_tokens.back() == llama_token_eot(ctx) || is_interacting) && params.interactive){ - if(is_interacting && !params.interactive_first) { - // print an eot token - printf("%s", llama_token_to_piece(ctx, llama_token_eot(ctx)).c_str()); - } - fflush(stdout); - printf("\n"); - console::set_display(console::user_input); - std::string buffer; - std::string line; - bool another_line=true; - // set a new prefix via stdin - do { - another_line = console::readline(line, params.multiline_input); - buffer += line; - } while (another_line); - // check if we got an empty line, if so we use the old input - if(!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) { - params.input_prefix = buffer; - } - buffer.clear(); - // set a new suffix via stdin - do { - another_line = console::readline(line, params.multiline_input); - buffer += line; - } while (another_line); - // check if we got an empty line - if(!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) { - params.input_suffix = buffer; - } - buffer.clear(); - // done taking input, reset color - console::set_display(console::reset); - // tokenize new prefix and suffix - std::vector inp_pfx = ::llama_tokenize(ctx, params.input_prefix, add_bos); - std::vector inp_sfx = ::llama_tokenize(ctx, params.input_suffix, add_bos); - inp_pfx.insert(inp_pfx.begin(), llama_token_prefix(ctx)); - inp_sfx.insert(inp_sfx.begin(), llama_token_suffix(ctx)); - embd_inp = inp_pfx; - embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end()); - embd_inp.push_back(llama_token_middle(ctx)); - embd.clear(); - embd_guidance.clear(); - n_remain = params.n_predict; - n_past = 0; - n_consumed = 0; - // LOG_TEE("took new input\n"); - is_interacting = false; - } - // deal with end of text token in interactive mode - else if (last_tokens.back() == llama_token_eos(ctx)) { - LOG("found EOS token\n"); - - if (params.interactive) { - - is_interacting = true; - printf("\n"); - console::set_display(console::user_input); - fflush(stdout); - } - } - - if (n_past > 0 && is_interacting && !params.interactive) { - LOG("waiting for user input\n"); - - if (params.input_prefix_bos) { - LOG("adding input prefix BOS token\n"); - embd_inp.push_back(llama_token_bos(ctx)); - } - - std::string buffer; - if (!params.input_prefix.empty()) { - LOG("appending input prefix: '%s'\n", params.input_prefix.c_str()); - buffer += params.input_prefix; - printf("%s", buffer.c_str()); - } - - std::string line; - bool another_line = true; - do { - another_line = console::readline(line, params.multiline_input); - buffer += line; - } while (another_line); - - // done taking input, reset color - console::set_display(console::reset); - - // Add tokens to embd only if the input buffer is non-empty - // Entering a empty line lets the user pass control back - if (buffer.length() > 1) { - // append input suffix if any - if (!params.input_suffix.empty()) { - LOG("appending input suffix: '%s'\n", params.input_suffix.c_str()); - buffer += params.input_suffix; - printf("%s", params.input_suffix.c_str()); - } - - LOG("buffer: '%s'\n", buffer.c_str()); - - const size_t original_size = embd_inp.size(); - - const auto line_inp = ::llama_tokenize(ctx, buffer, false); - LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp)); - - embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end()); - - for (size_t i = original_size; i < embd_inp.size(); ++i) { - const llama_token token = embd_inp[i]; - output_tokens.push_back(token); - output_ss << llama_token_to_piece(ctx, token); - } - - n_remain -= line_inp.size(); - LOG("n_remain: %d\n", n_remain); - } else { - LOG("empty line, passing control back\n"); - } - - input_echo = false; // do not echo this again - } - - if (n_past > 0) { - if (is_interacting) { - // reset grammar state if we're restarting generation - if (grammar != NULL) { - llama_grammar_free(grammar); - - std::vector grammar_rules(parsed_grammar.c_rules()); - grammar = llama_grammar_init( - grammar_rules.data(), grammar_rules.size(), - parsed_grammar.symbol_ids.at("root")); - } - } - is_interacting = false; - } - } - - // end of text token - if (!embd.empty() && embd.back() == llama_token_eos(ctx) && !params.interactive) { - break; - } - - // In interactive mode, respect the maximum number of tokens and drop back to user input when reached. - // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size). - if (params.interactive && n_remain <= 0 && params.n_predict >= 0) { - n_remain = params.n_predict; - is_interacting = true; - } - } - if (!params.interactive && n_remain <= 0) { - printf("%s", llama_token_to_piece(ctx, llama_token_eot(ctx)).c_str()); - fflush(stdout); - } - - llama_print_timings(ctx); - write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens); - - if (ctx_guidance) { llama_free(ctx_guidance); } - llama_free(ctx); - llama_free_model(model); - - if (grammar != NULL) { - llama_grammar_free(grammar); - } - llama_backend_free(); - -#ifndef LOG_DISABLE_LOGS - LOG_TEE("Log end\n"); -#endif // LOG_DISABLE_LOGS - - return 0; -} - diff --git a/spaces/Jeff2323/ai-comic-factory/src/app/interface/display/index.tsx b/spaces/Jeff2323/ai-comic-factory/src/app/interface/display/index.tsx deleted file mode 100644 index 26ba8d02a6afd446981aeca6c1c24b267ab467f1..0000000000000000000000000000000000000000 --- a/spaces/Jeff2323/ai-comic-factory/src/app/interface/display/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { RenderedScene } from "@/types" - -export function Display ({ rendered }: { rendered: RenderedScene }) { - return ( - <> - - - ) -} \ No newline at end of file diff --git a/spaces/JohnSmith9982/ChuanhuChatGPT/readme/README_ja.md b/spaces/JohnSmith9982/ChuanhuChatGPT/readme/README_ja.md deleted file mode 100644 index 1e0771070e0c9852f02a1024c65176f5a1ac46ba..0000000000000000000000000000000000000000 --- a/spaces/JohnSmith9982/ChuanhuChatGPT/readme/README_ja.md +++ /dev/null @@ -1,139 +0,0 @@ -
- - 简体中文 | English | 日本語 -
- -

川虎 Chat 🐯 Chuanhu Chat

-
- - Logo - - -

-

ChatGPT/ChatGLM/LLaMAなどのLLMのための軽量でユーザーフレンドリーなWeb-UI

-

- - Tests Passing - - - GitHub Contributors - - - GitHub pull requests - -

- ストリーム出力/会話回数無制限/履歴保存/プリセットプロンプト/ファイルへの質問チャット
- ウェブ検索/LaTeXレンダリング/表レンダリング/コードハイライト
- オートダークモード/アダプティブ・ウェブ・インターフェイス/WeChatライク・テーマ
- マルチパラメーターチューニング/マルチAPI-Key対応/マルチユーザー対応
- GPT-4対応/LLMのローカルデプロイ可能。 -

- 動画チュートリアル - · - 2.0 イントロダクション - · - 3.0 イントロダクション & チュートリアル - || - オンライントライアル - · - ワンクリックデプロイ -

-

- Animation Demo -

-

-
- -## サポートされている大規模言語モデル - -**APIを通じてアクセス可能な大規模言語モデル**: - -- [ChatGPT](https://chat.openai.com) ([GPT-4](https://openai.com/product/gpt-4)) -- [Google PaLM](https://developers.generativeai.google/products/palm) -- [Inspur Yuan 1.0](https://air.inspur.com/home) -- [MiniMax](https://api.minimax.chat/) -- [XMChat](https://github.com/MILVLG/xmchat) - -**ローカルに展開された大規模言語モデル**: - -- [ChatGLM](https://github.com/THUDM/ChatGLM-6B) ([ChatGLM2](https://github.com/THUDM/ChatGLM2-6B)) -- [LLaMA](https://github.com/facebookresearch/llama) -- [StableLM](https://github.com/Stability-AI/StableLM) -- [MOSS](https://github.com/OpenLMLab/MOSS) - -## 使う上でのTips - -- ChatGPTをより適切に制御するために、システムプロンプトを使用できます。 -- プロンプトテンプレートを使用するには、プロンプトテンプレートコレクションを選択し、ドロップダウンメニューから特定のプロンプトを選択。回答が不十分な場合は、`🔄再生成`ボタンを使って再試行します。 -- 入力ボックスで改行するには、Shift + Enterキーを押してください。 -- 入力履歴を素早く切り替えるには、入力ボックスで キーを押す。 -- プログラムをサーバーに展開するには、`config.json` 内の `"server_name": "0.0.0.0", "server_port": <ポート番号>`を設定してください。 -- 共有リンクを取得するには、 `config.json` 内の `"share": true` を設定してください。なお、公開リンクでアクセスするためには、プログラムが実行されている必要があることに注意してください。 -- Hugging Face Spacesで使用する場合: より速く、より安全に利用するために、**Duplicate Space**を使用し、自分のスペースでプログラムを実行することをお勧めします。 - -## クイックスタート - -```shell -git clone https://github.com/GaiZhenbiao/ChuanhuChatGPT.git -cd ChuanhuChatGPT -pip install -r requirements.txt -``` - -次に `config_example.json`をコピーして `config.json`にリネームし、そのファイルにAPI-Keyなどの設定を記入する。 - -```shell -python ChuanhuChatbot.py -``` - -ブラウザのウィンドウが開き、ChatGPTとチャットできるようになります。 - -> **Note** -> -> 詳しい手順は[wikiページ](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/使用教程)をご確認ください。 - -## トラブルシューティング - -問題が発生した場合は、まずこのプロジェクトの最新の変更点を手動で引っ張ってみるのがよいでしょう。その手順は以下の通りです: - -1. ウェブページの `Download ZIP` をクリックして最新のコードアーカイブをダウンロードするか、または - ```shell - git pull https://github.com/GaiZhenbiao/ChuanhuChatGPT.git main -f - ``` -2. 新しい依存関係が導入されている可能性があるため、依存関係を再度インストールしてみてください。 - ``` - pip install -r requirements.txt - ``` - -一般的に、以下の手順でほとんどの問題を解決することができます。 - -それでも問題が解決しない場合は、こちらのページをご参照ください: [よくある質問(FAQ)](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/常见问题) - -このページでは、考えられるほぼすべての問題点と解決策を掲載しています。よくお読みください。 - -## More Information - -より詳細な情報は、[wiki](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki) をご覧ください。: - -- [How to contribute a translation](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/Localization) -- [How to make a contribution](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/贡献指南) -- [How to cite the project](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/使用许可#如何引用该项目) -- [Project changelog](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/更新日志) -- [Project license](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/使用许可) - -## Starchart - -[![Star History Chart](https://api.star-history.com/svg?repos=GaiZhenbiao/ChuanhuChatGPT&type=Date)](https://star-history.com/#GaiZhenbiao/ChuanhuChatGPT&Date) - -## Contributors - - - - - -## Sponsor - -🐯 この企画が役に立ったら、遠慮なくコーラかコーヒーでもおごってください〜。 - -Buy Me A Coffee - -image diff --git a/spaces/JosephusCheung/ACertainsStrategyTalk/13.html b/spaces/JosephusCheung/ACertainsStrategyTalk/13.html deleted file mode 100644 index d813a32a7288c553edd95333f31dacb67996454a..0000000000000000000000000000000000000000 --- a/spaces/JosephusCheung/ACertainsStrategyTalk/13.html +++ /dev/null @@ -1,107 +0,0 @@ - - - - - - - - - -
- - - - - - - - - - - - - - - -
-
- - - - -
Unsolved -Issues & Advice -There are still problems with the portrayal of details such as eyes, hands, and feet, which is -largely due to the fact that the LAION dataset used by Stable Diffusion contains a lot of -inappropriate data, such as Tom and Jerry, who are not five-fingered creatures. -In the three models I released this time, I tried to eliminate some of the negative effects -brought by the "laion-aesthetics v2 5+" used by Stable Diffusion 1.4. Can you believe that in -the "laion-aesthetics v2 5+" data, if you search for Apple iPod, you will get many meme -images of apples that can be eaten with headphones inserted, with a high aesthetics score. -This is obviously wrong; on the other hand, Stable Diffusion 1.2 is a better version. -If you want to continue training a Stable Diffusion model with anime style, please avoid -Stable Diffusion 1.4+ version as possible. When you see through its releasing history, you will -find that the subsequent versions mostly involve struggles and interests among the founding -teams, and there is no good quality assurance. It is not that the higher the version, the better. -My personal opinion is that Stable Diffusion 1.2 is the best version. -Certains Certains Certains
- - - -
- - diff --git a/spaces/KennethTM/semantic_search/app.py b/spaces/KennethTM/semantic_search/app.py deleted file mode 100644 index e2692f6b2748b1bd5dbb0f806f8f30ba8c285b09..0000000000000000000000000000000000000000 --- a/spaces/KennethTM/semantic_search/app.py +++ /dev/null @@ -1,54 +0,0 @@ -import gradio as gr -from sentence_transformers import SentenceTransformer -import psycopg2 -import os -import torch - -conn_string = os.environ.get("DATABASE_URL") - -model = SentenceTransformer("multilingual-e5-small", device="cpu") -model.eval() - -def search(query, top_k): - - with torch.no_grad(): - query_embedding = model.encode("query: " + query) - - conn = psycopg2.connect(conn_string) - cur = conn.cursor() - - query_sql = f"SELECT source_file, chunk FROM items ORDER BY embedding <=> '{str(query_embedding.tolist())}' LIMIT {int(top_k)};" - - cur.execute(query_sql) - results = cur.fetchall() - conn.close() - - results_format = "\n".join([f"{i+1}. {text} __({file})__" for i, (file, text) in enumerate(results)]) - - template = f"{results_format}" - - return(template) - -with gr.Blocks() as demo: - - gr.Markdown("# Spørgsmål og svar indenfor natur og miljø med semantisk søgning") - gr.Markdown("## Søgning") - - with gr.Row(): - textbox = gr.Textbox(placeholder="Skriv her...", lines=1, scale=9, label="Søgning") - num = gr.Number(5, label="Hits", scale=1) - btn = gr.Button("Søg!", size="sm", scale=1) - - gr.Markdown("## Resultater") - - output = gr.Markdown() - - gr.Markdown("## Om") - gr.Markdown("*Søgningen baseret på tekst i natur og miljø rapporter fra DCE (https://dce.au.dk/udgivelser/), se referencer til specifikke rapporter i parentes:\nSR = Videnskabelige rapporter, TR = Tekniske rapporter og MB = Miljøbiblioteksbøger*") - gr.Markdown("## Tech") - gr.Markdown("*PDF parsing using GROBID, preprocessing using stanza and chunkipy, SentenceTransformer embeddings (intfloat/multilingual-e5-small), PostgreSQL/pgvector database hosted at Neon Tech and Gradio frontend*") - - btn.click(search, [textbox, num], output) - textbox.submit(search, [textbox, num], output) - -demo.launch() diff --git a/spaces/Kevin676/Clone-Your-Voice/encoder/train.py b/spaces/Kevin676/Clone-Your-Voice/encoder/train.py deleted file mode 100644 index 2bed4eb2f2f3e343b382a1b9cbf78a9ffb11c002..0000000000000000000000000000000000000000 --- a/spaces/Kevin676/Clone-Your-Voice/encoder/train.py +++ /dev/null @@ -1,125 +0,0 @@ -from pathlib import Path - -import torch - -from encoder.data_objects import SpeakerVerificationDataLoader, SpeakerVerificationDataset -from encoder.model import SpeakerEncoder -from encoder.params_model import * -from encoder.visualizations import Visualizations -from utils.profiler import Profiler - - -def sync(device: torch.device): - # For correct profiling (cuda operations are async) - if device.type == "cuda": - torch.cuda.synchronize(device) - - -def train(run_id: str, clean_data_root: Path, models_dir: Path, umap_every: int, save_every: int, - backup_every: int, vis_every: int, force_restart: bool, visdom_server: str, - no_visdom: bool): - # Create a dataset and a dataloader - dataset = SpeakerVerificationDataset(clean_data_root) - loader = SpeakerVerificationDataLoader( - dataset, - speakers_per_batch, - utterances_per_speaker, - num_workers=4, - ) - - # Setup the device on which to run the forward pass and the loss. These can be different, - # because the forward pass is faster on the GPU whereas the loss is often (depending on your - # hyperparameters) faster on the CPU. - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - # FIXME: currently, the gradient is None if loss_device is cuda - loss_device = torch.device("cpu") - - # Create the model and the optimizer - model = SpeakerEncoder(device, loss_device) - optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate_init) - init_step = 1 - - # Configure file path for the model - model_dir = models_dir / run_id - model_dir.mkdir(exist_ok=True, parents=True) - state_fpath = model_dir / "encoder.pt" - - # Load any existing model - if not force_restart: - if state_fpath.exists(): - print("Found existing model \"%s\", loading it and resuming training." % run_id) - checkpoint = torch.load(state_fpath) - init_step = checkpoint["step"] - model.load_state_dict(checkpoint["model_state"]) - optimizer.load_state_dict(checkpoint["optimizer_state"]) - optimizer.param_groups[0]["lr"] = learning_rate_init - else: - print("No model \"%s\" found, starting training from scratch." % run_id) - else: - print("Starting the training from scratch.") - model.train() - - # Initialize the visualization environment - vis = Visualizations(run_id, vis_every, server=visdom_server, disabled=no_visdom) - vis.log_dataset(dataset) - vis.log_params() - device_name = str(torch.cuda.get_device_name(0) if torch.cuda.is_available() else "CPU") - vis.log_implementation({"Device": device_name}) - - # Training loop - profiler = Profiler(summarize_every=10, disabled=False) - for step, speaker_batch in enumerate(loader, init_step): - profiler.tick("Blocking, waiting for batch (threaded)") - - # Forward pass - inputs = torch.from_numpy(speaker_batch.data).to(device) - sync(device) - profiler.tick("Data to %s" % device) - embeds = model(inputs) - sync(device) - profiler.tick("Forward pass") - embeds_loss = embeds.view((speakers_per_batch, utterances_per_speaker, -1)).to(loss_device) - loss, eer = model.loss(embeds_loss) - sync(loss_device) - profiler.tick("Loss") - - # Backward pass - model.zero_grad() - loss.backward() - profiler.tick("Backward pass") - model.do_gradient_ops() - optimizer.step() - profiler.tick("Parameter update") - - # Update visualizations - # learning_rate = optimizer.param_groups[0]["lr"] - vis.update(loss.item(), eer, step) - - # Draw projections and save them to the backup folder - if umap_every != 0 and step % umap_every == 0: - print("Drawing and saving projections (step %d)" % step) - projection_fpath = model_dir / f"umap_{step:06d}.png" - embeds = embeds.detach().cpu().numpy() - vis.draw_projections(embeds, utterances_per_speaker, step, projection_fpath) - vis.save() - - # Overwrite the latest version of the model - if save_every != 0 and step % save_every == 0: - print("Saving the model (step %d)" % step) - torch.save({ - "step": step + 1, - "model_state": model.state_dict(), - "optimizer_state": optimizer.state_dict(), - }, state_fpath) - - # Make a backup - if backup_every != 0 and step % backup_every == 0: - print("Making a backup (step %d)" % step) - backup_fpath = model_dir / f"encoder_{step:06d}.bak" - torch.save({ - "step": step + 1, - "model_state": model.state_dict(), - "optimizer_state": optimizer.state_dict(), - }, backup_fpath) - - profiler.tick("Extras (visualizations, saving)") diff --git a/spaces/KevinQHLin/UniVTG/run_on_video/clip_feature_extractor.py b/spaces/KevinQHLin/UniVTG/run_on_video/clip_feature_extractor.py deleted file mode 100644 index 2852db020d8bcc74fd52cc2e0cd97d59c61b6b94..0000000000000000000000000000000000000000 --- a/spaces/KevinQHLin/UniVTG/run_on_video/clip_feature_extractor.py +++ /dev/null @@ -1,101 +0,0 @@ -import pdb -import torch as th -import math -import numpy as np -import torch -from video_loader import VideoLoader -from torch.utils.data import DataLoader -import argparse -from preprocessing import Preprocessing -import torch.nn.functional as F -from tqdm import tqdm -import os -import sys -from feature_extractor import clip -import argparse - -################################# -model_version = "ViT-B/32" -output_feat_size = 512 -clip_len = 2 -overwrite = True -num_decoding_thread = 4 -half_precision = False - -@torch.no_grad() -def extractor(vid_path, text, output_file): - dataset = VideoLoader( - vid_path, - framerate=1/clip_len, - size=224, - centercrop=True, - overwrite=overwrite, - model_version=model_version - ) - n_dataset = len(dataset) - loader = DataLoader( - dataset, - batch_size=1, - shuffle=False, - num_workers=num_decoding_thread, - sampler=sampler if n_dataset > 10 else None, - ) - preprocess = Preprocessing() - model, _ = clip.load(model_version, device="cuda", jit=False) - - encoded_texts = clip.tokenize(text).to('cuda') - text_feature = model.encode_text(encoded_texts)['last_hidden_state'] - valid_lengths = (encoded_texts != 0).sum(1).tolist()[0] - text_feature = text_feature[0, :valid_lengths].cpu().numpy() - np.savez(os.path.join(output_file, 'txt.npz'), features=text_feature) - - totatl_num_frames = 0 - with th.no_grad(): - for k, data in enumerate(tqdm(loader)): - input_file = data['input'][0] - if os.path.isfile(output_file): - # print(f'Video {input_file} already processed.') - continue - elif not os.path.isfile(input_file): - print(f'{input_file}, does not exist.\n') - elif len(data['video'].shape) > 4: - video = data['video'].squeeze(0) - if len(video.shape) == 4: - video = preprocess(video) - n_chunk = len(video) - vid_features = th.cuda.FloatTensor( - n_chunk, output_feat_size).fill_(0) - n_iter = int(math.ceil(n_chunk)) - for i in range(n_iter): - min_ind = i - max_ind = (i + 1) - video_batch = video[min_ind:max_ind].cuda() - batch_features = model.encode_image(video_batch) - vid_features[min_ind:max_ind] = batch_features - vid_features = vid_features.cpu().numpy() - if half_precision: - vid_features = vid_features.astype('float16') - totatl_num_frames += vid_features.shape[0] - # safeguard output path before saving - dirname = os.path.dirname(output_file) - if not os.path.exists(dirname): - print(f"Output directory {dirname} does not exists, creating...") - os.makedirs(dirname) - np.savez(os.path.join(output_file, 'vid.npz'), features=vid_features) - else: - print(f'{input_file}, failed at ffprobe.\n') - - print(f"Total number of frames: {totatl_num_frames}") - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description='') - parser.add_argument('--vid_path', type=str, default='/data/home/qinghonglin/dataset/charades/videos/Charades_v1_480/0A8CF.mp4') - parser.add_argument('--text', nargs='+', type=str, default='a boy is drinking.') - parser.add_argument('--save_dir', type=str, default='./tmp') - args = parser.parse_args() - - query = ' '.join(args.text) - - print(args.vid_path) - print(query) - extractor(args.vid_path, [query], args.save_dir) diff --git a/spaces/KevinQHLin/UniVTG/utils/__init__.py b/spaces/KevinQHLin/UniVTG/utils/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/KyanChen/FunSR/models/baselines/RSI_HFAS.py b/spaces/KyanChen/FunSR/models/baselines/RSI_HFAS.py deleted file mode 100644 index 26f2c36ec2507ea2e5eb27a1e05dc53a2b8dda63..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/FunSR/models/baselines/RSI_HFAS.py +++ /dev/null @@ -1,496 +0,0 @@ -import time -from collections import OrderedDict - -import torch -import torch.nn as nn -import math -import torchvision.utils as SI - -def make_model(args, parent=False): - return metafpn(args) - - -class Pos2Weight(nn.Module): - def __init__(self, inC, kernel_size=3, outC=3): - super(Pos2Weight, self).__init__() - self.inC = inC - self.kernel_size = kernel_size - self.outC = outC - self.meta_block = nn.Sequential( - nn.Linear(3, 256), - nn.ReLU(inplace=True), - nn.Linear(256, 512), - nn.ReLU(inplace=True), - nn.Linear(512, self.kernel_size * self.kernel_size * self.inC * self.outC) - ) - - def forward(self, x): - output = self.meta_block(x) - return output - - -class RDB_Conv(nn.Module): - def __init__(self, inChannels, growRate, kSize=3): - super(RDB_Conv, self).__init__() - Cin = inChannels - G = growRate - self.conv = nn.Sequential(*[ - nn.Conv2d(Cin, G, kSize, padding=(kSize - 1) // 2, stride=1), - nn.ReLU() - ]) - - def forward(self, x): - out = self.conv(x) - return out - - -class FPN(nn.Module): - def __init__(self, G0, kSize=3): - super(FPN, self).__init__() - - kSize1 = 1 - self.conv1 = RDB_Conv(G0, G0, kSize) - self.conv2 = RDB_Conv(G0, G0, kSize) - self.conv3 = RDB_Conv(G0, G0, kSize) - self.conv4 = RDB_Conv(G0, G0, kSize) - self.conv5 = RDB_Conv(G0, G0, kSize) - self.conv6 = RDB_Conv(G0, G0, kSize) - self.conv7 = RDB_Conv(G0, G0, kSize) - self.conv8 = RDB_Conv(G0, G0, kSize) - self.conv9 = RDB_Conv(G0, G0, kSize) - self.conv10 = RDB_Conv(G0, G0, kSize) - self.compress_in1 = nn.Conv2d(4 * G0, G0, kSize1, padding=(kSize1 - 1) // 2, stride=1) - self.compress_in2 = nn.Conv2d(3 * G0, G0, kSize1, padding=(kSize1 - 1) // 2, stride=1) - self.compress_in3 = nn.Conv2d(2 * G0, G0, kSize1, padding=(kSize1 - 1) // 2, stride=1) - self.compress_in4 = nn.Conv2d(2 * G0, G0, kSize1, padding=(kSize1 - 1) // 2, stride=1) - self.compress_out = nn.Conv2d(4 * G0, G0, kSize1, padding=(kSize1 - 1) // 2, stride=1) - - def forward(self, x): - x1 = self.conv1(x) - x2 = self.conv2(x1) - x3 = self.conv3(x2) - x4 = self.conv4(x3) - x11 = x + x4 - x5 = torch.cat((x1, x2, x3, x4), dim=1) - x5_res = self.compress_in1(x5) - x5 = self.conv5(x5_res) - x6 = self.conv6(x5) - x7 = self.conv7(x6) - x12 = x5_res + x7 - x8 = torch.cat((x5, x6, x7), dim=1) - x8_res = self.compress_in2(x8) - x8 = self.conv8(x8_res) - x9 = self.conv9(x8) - x13 = x8_res + x9 - x10 = torch.cat((x8, x9), dim=1) - x10_res = self.compress_in3(x10) - x10 = self.conv10(x10_res) - x14 = x10_res + x10 - output = torch.cat((x11, x12, x13, x14), dim=1) - output = self.compress_out(output) - output = output + x - return output - - -def default_conv(in_channels, out_channels, kernel_size, bias=True): - return nn.Conv2d( - in_channels, out_channels, kernel_size, - padding=(kernel_size // 2), bias=bias) - - -class MeanShift(nn.Conv2d): - def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1): - super(MeanShift, self).__init__(3, 3, kernel_size=1) - std = torch.Tensor(rgb_std) - self.weight.data = torch.eye(3).view(3, 3, 1, 1) - self.weight.data.div_(std.view(3, 1, 1, 1)) - self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) - self.bias.data.div_(std) - self.requires_grad = False - - -class BasicBlock(nn.Sequential): - def __init__( - self, in_channels, out_channels, kernel_size, stride=1, bias=False, - bn=True, act=nn.ReLU(True)): - - m = [nn.Conv2d( - in_channels, out_channels, kernel_size, - padding=(kernel_size // 2), stride=stride, bias=bias) - ] - if bn: m.append(nn.BatchNorm2d(out_channels)) - if act is not None: m.append(act) - super(BasicBlock, self).__init__(*m) - - -class ResBlock(nn.Module): - def __init__( - self, conv, n_feats, kernel_size, - bias=True, bn=False, act=nn.ReLU(True), res_scale=1): - - super(ResBlock, self).__init__() - m = [] - for i in range(2): - m.append(conv(n_feats, n_feats, kernel_size, bias=bias)) - if bn: m.append(nn.BatchNorm2d(n_feats)) - if i == 0: m.append(act) - - self.body = nn.Sequential(*m) - self.res_scale = res_scale - - def forward(self, x): - res = self.body(x).mul(self.res_scale) - res += x - - return res - - -class Upsampler(nn.Sequential): - def __init__(self, conv, scale, n_feats, bn=False, act=False, bias=True): - - m = [] - if (scale & (scale - 1)) == 0: # Is scale = 2^n? - for _ in range(int(math.log(scale, 2))): - m.append(conv(n_feats, 4 * n_feats, 3, bias)) - m.append(nn.PixelShuffle(2)) - if bn: m.append(nn.BatchNorm2d(n_feats)) - - if act == 'relu': - m.append(nn.ReLU(True)) - elif act == 'prelu': - m.append(nn.PReLU(n_feats)) - - elif scale == 3: - m.append(conv(n_feats, 9 * n_feats, 3, bias)) - m.append(nn.PixelShuffle(3)) - if bn: m.append(nn.BatchNorm2d(n_feats)) - - if act == 'relu': - m.append(nn.ReLU(True)) - elif act == 'prelu': - m.append(nn.PReLU(n_feats)) - else: - raise NotImplementedError - - super(Upsampler, self).__init__(*m) - - -class ResidualDenseBlock_8C(nn.Module): - ''' - Residual Dense Block - style: 8 convs - The core module of paper: (Residual Dense Network for Image Super-Resolution, CVPR 18) - ''' - - def __init__(self, nc, kernel_size=3, gc=32, stride=1, bias=True, pad_type='zero', norm_type=None, act_type='relu', - mode='CNA'): - super(ResidualDenseBlock_8C, self).__init__() - # gc: growth channel, i.e. intermediate channels - self.conv1 = ConvBlock(nc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=act_type, mode=mode) - self.conv2 = ConvBlock(nc + gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=act_type, mode=mode) - self.conv3 = ConvBlock(nc + 2 * gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=act_type, mode=mode) - self.conv4 = ConvBlock(nc + 3 * gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=act_type, mode=mode) - self.conv5 = ConvBlock(nc + 4 * gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=act_type, mode=mode) - self.conv6 = ConvBlock(nc + 5 * gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=act_type, mode=mode) - self.conv7 = ConvBlock(nc + 6 * gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=act_type, mode=mode) - self.conv8 = ConvBlock(nc + 7 * gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=act_type, mode=mode) - if mode == 'CNA': - last_act = None - else: - last_act = act_type - self.conv9 = ConvBlock(nc + 8 * gc, nc, 1, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, - act_type=last_act, mode=mode) - - def forward(self, x): - x1 = self.conv1(x) - x2 = self.conv2(torch.cat((x, x1), 1)) - x3 = self.conv3(torch.cat((x, x1, x2), 1)) - x4 = self.conv4(torch.cat((x, x1, x2, x3), 1)) - x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1)) - x6 = self.conv6(torch.cat((x, x1, x2, x3, x4, x5), 1)) - x7 = self.conv7(torch.cat((x, x1, x2, x3, x4, x5, x6), 1)) - x8 = self.conv8(torch.cat((x, x1, x2, x3, x4, x5, x6, x7), 1)) - x9 = self.conv9(torch.cat((x, x1, x2, x3, x4, x5, x6, x7, x8), 1)) - return x9.mul(0.2) + x - - -def ConvBlock(in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, valid_padding=True, padding=0, \ - act_type='relu', norm_type='bn', pad_type='zero', mode='CNA'): - assert (mode in ['CNA', 'NAC']), '[ERROR] Wrong mode in [%s]!' % sys.modules[__name__] - - if valid_padding: - padding = get_valid_padding(kernel_size, dilation) - else: - pass - p = pad(pad_type, padding) if pad_type and pad_type != 'zero' else None - conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, - bias=bias) - - if mode == 'CNA': - act = activation(act_type) if act_type else None - n = norm(out_channels, norm_type) if norm_type else None - return sequential(p, conv, n, act) - elif mode == 'NAC': - act = activation(act_type, inplace=False) if act_type else None - n = norm(in_channels, norm_type) if norm_type else None - return sequential(n, act, p, conv) - - -def DeconvBlock(in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, padding=0, \ - act_type='relu', norm_type='bn', pad_type='zero', mode='CNA'): - assert (mode in ['CNA', 'NAC']), '[ERROR] Wrong mode in [%s]!' % sys.modules[__name__] - - p = pad(pad_type, padding) if pad_type and pad_type != 'zero' else None - deconv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, dilation=dilation, bias=bias) - - if mode == 'CNA': - act = activation(act_type) if act_type else None - n = norm(out_channels, norm_type) if norm_type else None - return sequential(p, deconv, n, act) - elif mode == 'NAC': - act = activation(act_type, inplace=False) if act_type else None - n = norm(in_channels, norm_type) if norm_type else None - return sequential(n, act, p, deconv) - - -def get_valid_padding(kernel_size, dilation): - """ - Padding value to remain feature size. - """ - kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1) - padding = (kernel_size - 1) // 2 - return padding - - -def pad(pad_type, padding): - pad_type = pad_type.lower() - if padding == 0: - return None - - layer = None - if pad_type == 'reflect': - layer = nn.ReflectionPad2d(padding) - elif pad_type == 'replicate': - layer = nn.ReplicationPad2d(padding) - else: - raise NotImplementedError('[ERROR] Padding layer [%s] is not implemented!' % pad_type) - return layer - - -def activation(act_type='relu', inplace=True, slope=0.2, n_prelu=1): - act_type = act_type.lower() - layer = None - if act_type == 'relu': - layer = nn.ReLU(inplace) - elif act_type == 'lrelu': - layer = nn.LeakyReLU(slope, inplace) - elif act_type == 'prelu': - layer = nn.PReLU(num_parameters=n_prelu, init=slope) - else: - raise NotImplementedError('[ERROR] Activation layer [%s] is not implemented!' % act_type) - return layer - - -def norm(n_feature, norm_type='bn'): - norm_type = norm_type.lower() - layer = None - if norm_type == 'bn': - layer = nn.BatchNorm2d(n_feature) - else: - raise NotImplementedError('[ERROR] Normalization layer [%s] is not implemented!' % norm_type) - return layer - - -def sequential(*args): - if len(args) == 1: - if isinstance(args[0], OrderedDict): - raise NotImplementedError('[ERROR] %s.sequential() does not support OrderedDict' % sys.modules[__name__]) - else: - return args[0] - modules = [] - for module in args: - if isinstance(module, nn.Sequential): - for submodule in module: - modules.append(submodule) - elif isinstance(module, nn.Module): - modules.append(module) - return nn.Sequential(*modules) - -class FeedbackBlock(nn.Module): - def __init__(self, num_features, num_groups, upscale_factor, act_type, norm_type): - super(FeedbackBlock, self).__init__() - if upscale_factor == 2: - stride = 2 - padding = 2 - kernel_size = 6 - elif upscale_factor == 3: - stride = 3 - padding = 2 - kernel_size = 7 - elif upscale_factor == 4: - stride = 4 - padding = 2 - kernel_size = 8 - elif upscale_factor == 8: - stride = 8 - padding = 2 - kernel_size = 12 - - kSize = 3 - kSize1 = 1 - - self.fpn1 = FPN(num_features) - self.fpn2 = FPN(num_features) - self.fpn3 = FPN(num_features) - self.fpn4 = FPN(num_features) - self.compress_in = nn.Conv2d(2 * num_features, num_features, kSize1, padding=(kSize1 - 1) // 2, stride=1) - self.compress_out = nn.Conv2d(4 * num_features, num_features, kSize1, padding=(kSize1 - 1) // 2, stride=1) - - def forward(self, x): - if self.should_reset: - self.last_hidden = torch.zeros(x.size()).cuda() - self.last_hidden.copy_(x) - self.should_reset = False - - x = torch.cat((x, self.last_hidden), dim=1) # tense拼接 - x = self.compress_in(x) - - fpn1 = self.fpn1(x) - fpn2 = self.fpn2(fpn1) - fpn3 = self.fpn3(fpn2) - fpn4 = self.fpn4(fpn3) - output = torch.cat((fpn1, fpn2, fpn3, fpn4), dim=1) - output = self.compress_out(output) - - self.last_hidden = output - - return output - - def reset_state(self): - self.should_reset = True - - -class metafpn(nn.Module): - def __init__(self, - RDNkSize=3, - G0=64, - n_colors=3, - act_type='prelu', - norm_type=None - ): - super(metafpn, self).__init__() # 第一句话,调用父类的构造函数,这是对继承自父类的属性进行初始化。而且是用父类的初始化方法来初始化继承的属性。也就是说,子类继承了父类的所有属性和方法,父类属性自然会用父类方法来进行初始化。当然,如果初始化的逻辑与父类的不同,不使用父类的方法,自己重新初始化也是可以的。 - - kernel_size = RDNkSize - self.num_steps = 4 - self.num_features = G0 - self.scale_idx = 0 - self.scale = 1 - in_channels = n_colors - num_groups = 6 - - # RGB mean for DIV2K - # rgb_mean = (0.4488, 0.4371, 0.4040) - # rgb_std = (1.0, 1.0, 1.0) - # self.sub_mean = common.MeanShift(args.rgb_range, rgb_mean, rgb_std) - # self.add_mean = common.MeanShift(args.rgb_range, rgb_mean, rgb_std, 1) - - # LR feature extraction block - self.conv_in = ConvBlock(in_channels, 4 * self.num_features, - # 3×3Conv 一个卷积核产生一个feature map就是num_features - kernel_size=3, - act_type=act_type, norm_type=norm_type) - self.feat_in = ConvBlock(4 * self.num_features, self.num_features, - kernel_size=1, - act_type=act_type, norm_type=norm_type) - - # basic block - self.block = FeedbackBlock(self.num_features, num_groups, self.scale, act_type, norm_type) - - # reconstruction block - # uncomment for pytorch 0.4.0 - # self.upsample = nn.Upsample(scale_factor=upscale_factor, mode='bilinear') - - # self.out = DeconvBlock(num_features, num_features, - # kernel_size=kernel_size, stride=stride, padding=padding, - # act_type='prelu', norm_type=norm_type) - self.P2W = Pos2Weight(inC=self.num_features) - - def repeat_x(self, x): - scale_int = math.ceil(self.scale) - N, C, H, W = x.size() - x = x.view(N, C, H, 1, W, 1) - - x = torch.cat([x] * scale_int, 3) - x = torch.cat([x] * scale_int, 5).permute(0, 3, 5, 1, 2, 4) - - return x.contiguous().view(-1, C, H, W) - - def forward(self, x, pos_mat): - self._reset_state() - - # x = self.sub_mean(x) - scale_int = math.ceil(self.scale) - # uncomment for pytorch 0.4.0 - # inter_res = self.upsample(x) - - # comment for pytorch 0.4.0 - inter_res = nn.functional.interpolate(x, scale_factor=scale_int, mode='bilinear', align_corners=False) - - x = self.conv_in(x) - x = self.feat_in(x) - - outs = [] - for _ in range(self.num_steps): - h = self.block(x) - - #output1 = h.clone() - # for i in range(60): - # output2 = output1[:,i:i+3,:,:] - # SI.save_image(output2,"results/result"+str(i)+".png") - - # meta########################################### - local_weight = self.P2W( - pos_mat.view(pos_mat.size(1), -1)) ### (outH*outW, outC*inC*kernel_size*kernel_size) - up_x = self.repeat_x(h) ### the output is (N*r*r,inC,inH,inW) - - # N*r^2 x [inC * kH * kW] x [inH * inW] - cols = nn.functional.unfold(up_x, 3, padding=1) - scale_int = math.ceil(self.scale) - - cols = cols.contiguous().view(cols.size(0) // (scale_int ** 2), scale_int ** 2, cols.size(1), cols.size(2), - 1).permute(0, 1, 3, 4, 2).contiguous() - - local_weight = local_weight.contiguous().view(x.size(2), scale_int, x.size(3), scale_int, -1, 3).permute(1, - 3, - 0, - 2, - 4, - 5).contiguous() - local_weight = local_weight.contiguous().view(scale_int ** 2, x.size(2) * x.size(3), -1, 3) - - out = torch.matmul(cols, local_weight).permute(0, 1, 4, 2, 3) - out = out.contiguous().view(x.size(0), scale_int, scale_int, 3, x.size(2), x.size(3)).permute(0, 3, 4, 1, 5, - 2) - out = out.contiguous().view(x.size(0), 3, scale_int * x.size(2), scale_int * x.size(3)) - - h = torch.add(inter_res, out) - # h = self.add_mean(h) - - outs.append(h) - - return outs # return output of every timesteps - - def _reset_state(self): - self.block.reset_state() - - def set_scale(self, scale_idx): - self.scale_idx = scale_idx - self.scale = self.args.scale[scale_idx] \ No newline at end of file diff --git a/spaces/KyanChen/RSPrompter/mmdet/models/dense_heads/rpn_head.py b/spaces/KyanChen/RSPrompter/mmdet/models/dense_heads/rpn_head.py deleted file mode 100644 index 6b544009d2ffc4c3c9065707a0a8a72c577eb432..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmdet/models/dense_heads/rpn_head.py +++ /dev/null @@ -1,302 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import copy -from typing import List, Optional, Tuple - -import torch -import torch.nn as nn -import torch.nn.functional as F -from mmcv.cnn import ConvModule -from mmcv.ops import batched_nms -from mmengine.config import ConfigDict -from mmengine.structures import InstanceData -from torch import Tensor - -from mmdet.registry import MODELS -from mmdet.structures.bbox import (cat_boxes, empty_box_as, get_box_tensor, - get_box_wh, scale_boxes) -from mmdet.utils import InstanceList, MultiConfig, OptInstanceList -from .anchor_head import AnchorHead - - -@MODELS.register_module() -class RPNHead(AnchorHead): - """Implementation of RPN head. - - Args: - in_channels (int): Number of channels in the input feature map. - num_classes (int): Number of categories excluding the background - category. Defaults to 1. - init_cfg (:obj:`ConfigDict` or list[:obj:`ConfigDict`] or dict or \ - list[dict]): Initialization config dict. - num_convs (int): Number of convolution layers in the head. - Defaults to 1. - """ # noqa: W605 - - def __init__(self, - in_channels: int, - num_classes: int = 1, - init_cfg: MultiConfig = dict( - type='Normal', layer='Conv2d', std=0.01), - num_convs: int = 1, - **kwargs) -> None: - self.num_convs = num_convs - assert num_classes == 1 - super().__init__( - num_classes=num_classes, - in_channels=in_channels, - init_cfg=init_cfg, - **kwargs) - - def _init_layers(self) -> None: - """Initialize layers of the head.""" - if self.num_convs > 1: - rpn_convs = [] - for i in range(self.num_convs): - if i == 0: - in_channels = self.in_channels - else: - in_channels = self.feat_channels - # use ``inplace=False`` to avoid error: one of the variables - # needed for gradient computation has been modified by an - # inplace operation. - rpn_convs.append( - ConvModule( - in_channels, - self.feat_channels, - 3, - padding=1, - inplace=False)) - self.rpn_conv = nn.Sequential(*rpn_convs) - else: - self.rpn_conv = nn.Conv2d( - self.in_channels, self.feat_channels, 3, padding=1) - self.rpn_cls = nn.Conv2d(self.feat_channels, - self.num_base_priors * self.cls_out_channels, - 1) - reg_dim = self.bbox_coder.encode_size - self.rpn_reg = nn.Conv2d(self.feat_channels, - self.num_base_priors * reg_dim, 1) - - def forward_single(self, x: Tensor) -> Tuple[Tensor, Tensor]: - """Forward feature of a single scale level. - - Args: - x (Tensor): Features of a single scale level. - - Returns: - tuple: - cls_score (Tensor): Cls scores for a single scale level \ - the channels number is num_base_priors * num_classes. - bbox_pred (Tensor): Box energies / deltas for a single scale \ - level, the channels number is num_base_priors * 4. - """ - x = self.rpn_conv(x) - x = F.relu(x) - rpn_cls_score = self.rpn_cls(x) - rpn_bbox_pred = self.rpn_reg(x) - return rpn_cls_score, rpn_bbox_pred - - def loss_by_feat(self, - cls_scores: List[Tensor], - bbox_preds: List[Tensor], - batch_gt_instances: InstanceList, - batch_img_metas: List[dict], - batch_gt_instances_ignore: OptInstanceList = None) \ - -> dict: - """Calculate the loss based on the features extracted by the detection - head. - - Args: - cls_scores (list[Tensor]): Box scores for each scale level, - has shape (N, num_anchors * num_classes, H, W). - bbox_preds (list[Tensor]): Box energies / deltas for each scale - level with shape (N, num_anchors * 4, H, W). - batch_gt_instances (list[obj:InstanceData]): Batch of gt_instance. - It usually includes ``bboxes`` and ``labels`` attributes. - batch_img_metas (list[dict]): Meta information of each image, e.g., - image size, scaling factor, etc. - batch_gt_instances_ignore (list[obj:InstanceData], Optional): - Batch of gt_instances_ignore. It includes ``bboxes`` attribute - data that is ignored during training and testing. - - Returns: - dict[str, Tensor]: A dictionary of loss components. - """ - losses = super().loss_by_feat( - cls_scores, - bbox_preds, - batch_gt_instances, - batch_img_metas, - batch_gt_instances_ignore=batch_gt_instances_ignore) - return dict( - loss_rpn_cls=losses['loss_cls'], loss_rpn_bbox=losses['loss_bbox']) - - def _predict_by_feat_single(self, - cls_score_list: List[Tensor], - bbox_pred_list: List[Tensor], - score_factor_list: List[Tensor], - mlvl_priors: List[Tensor], - img_meta: dict, - cfg: ConfigDict, - rescale: bool = False, - with_nms: bool = True) -> InstanceData: - """Transform a single image's features extracted from the head into - bbox results. - - Args: - cls_score_list (list[Tensor]): Box scores from all scale - levels of a single image, each item has shape - (num_priors * num_classes, H, W). - bbox_pred_list (list[Tensor]): Box energies / deltas from - all scale levels of a single image, each item has shape - (num_priors * 4, H, W). - score_factor_list (list[Tensor]): Be compatible with - BaseDenseHead. Not used in RPNHead. - mlvl_priors (list[Tensor]): Each element in the list is - the priors of a single level in feature pyramid. In all - anchor-based methods, it has shape (num_priors, 4). In - all anchor-free methods, it has shape (num_priors, 2) - when `with_stride=True`, otherwise it still has shape - (num_priors, 4). - img_meta (dict): Image meta info. - cfg (ConfigDict, optional): Test / postprocessing configuration, - if None, test_cfg would be used. - rescale (bool): If True, return boxes in original image space. - Defaults to False. - - Returns: - :obj:`InstanceData`: Detection results of each image - after the post process. - Each item usually contains following keys. - - - scores (Tensor): Classification scores, has a shape - (num_instance, ) - - labels (Tensor): Labels of bboxes, has a shape - (num_instances, ). - - bboxes (Tensor): Has a shape (num_instances, 4), - the last dimension 4 arrange as (x1, y1, x2, y2). - """ - cfg = self.test_cfg if cfg is None else cfg - cfg = copy.deepcopy(cfg) - img_shape = img_meta['img_shape'] - nms_pre = cfg.get('nms_pre', -1) - - mlvl_bbox_preds = [] - mlvl_valid_priors = [] - mlvl_scores = [] - level_ids = [] - for level_idx, (cls_score, bbox_pred, priors) in \ - enumerate(zip(cls_score_list, bbox_pred_list, - mlvl_priors)): - assert cls_score.size()[-2:] == bbox_pred.size()[-2:] - - reg_dim = self.bbox_coder.encode_size - bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, reg_dim) - cls_score = cls_score.permute(1, 2, - 0).reshape(-1, self.cls_out_channels) - if self.use_sigmoid_cls: - scores = cls_score.sigmoid() - else: - # remind that we set FG labels to [0] since mmdet v2.0 - # BG cat_id: 1 - scores = cls_score.softmax(-1)[:, :-1] - - scores = torch.squeeze(scores) - if 0 < nms_pre < scores.shape[0]: - # sort is faster than topk - # _, topk_inds = scores.topk(cfg.nms_pre) - ranked_scores, rank_inds = scores.sort(descending=True) - topk_inds = rank_inds[:nms_pre] - scores = ranked_scores[:nms_pre] - bbox_pred = bbox_pred[topk_inds, :] - priors = priors[topk_inds] - - mlvl_bbox_preds.append(bbox_pred) - mlvl_valid_priors.append(priors) - mlvl_scores.append(scores) - - # use level id to implement the separate level nms - level_ids.append( - scores.new_full((scores.size(0), ), - level_idx, - dtype=torch.long)) - - bbox_pred = torch.cat(mlvl_bbox_preds) - priors = cat_boxes(mlvl_valid_priors) - bboxes = self.bbox_coder.decode(priors, bbox_pred, max_shape=img_shape) - - results = InstanceData() - results.bboxes = bboxes - results.scores = torch.cat(mlvl_scores) - results.level_ids = torch.cat(level_ids) - - return self._bbox_post_process( - results=results, cfg=cfg, rescale=rescale, img_meta=img_meta) - - def _bbox_post_process(self, - results: InstanceData, - cfg: ConfigDict, - rescale: bool = False, - with_nms: bool = True, - img_meta: Optional[dict] = None) -> InstanceData: - """bbox post-processing method. - - The boxes would be rescaled to the original image scale and do - the nms operation. - - Args: - results (:obj:`InstaceData`): Detection instance results, - each item has shape (num_bboxes, ). - cfg (ConfigDict): Test / postprocessing configuration. - rescale (bool): If True, return boxes in original image space. - Defaults to False. - with_nms (bool): If True, do nms before return boxes. - Default to True. - img_meta (dict, optional): Image meta info. Defaults to None. - - Returns: - :obj:`InstanceData`: Detection results of each image - after the post process. - Each item usually contains following keys. - - - scores (Tensor): Classification scores, has a shape - (num_instance, ) - - labels (Tensor): Labels of bboxes, has a shape - (num_instances, ). - - bboxes (Tensor): Has a shape (num_instances, 4), - the last dimension 4 arrange as (x1, y1, x2, y2). - """ - assert with_nms, '`with_nms` must be True in RPNHead' - if rescale: - assert img_meta.get('scale_factor') is not None - scale_factor = [1 / s for s in img_meta['scale_factor']] - results.bboxes = scale_boxes(results.bboxes, scale_factor) - - # filter small size bboxes - if cfg.get('min_bbox_size', -1) >= 0: - w, h = get_box_wh(results.bboxes) - valid_mask = (w > cfg.min_bbox_size) & (h > cfg.min_bbox_size) - if not valid_mask.all(): - results = results[valid_mask] - - if results.bboxes.numel() > 0: - bboxes = get_box_tensor(results.bboxes) - det_bboxes, keep_idxs = batched_nms(bboxes, results.scores, - results.level_ids, cfg.nms) - results = results[keep_idxs] - # some nms would reweight the score, such as softnms - results.scores = det_bboxes[:, -1] - results = results[:cfg.max_per_img] - # TODO: This would unreasonably show the 0th class label - # in visualization - results.labels = results.scores.new_zeros( - len(results), dtype=torch.long) - del results.level_ids - else: - # To avoid some potential error - results_ = InstanceData() - results_.bboxes = empty_box_as(results.bboxes) - results_.scores = results.scores.new_zeros(0) - results_.labels = results.scores.new_zeros(0) - results = results_ - return results diff --git a/spaces/KyanChen/RSPrompter/mmdet/models/detectors/fast_rcnn.py b/spaces/KyanChen/RSPrompter/mmdet/models/detectors/fast_rcnn.py deleted file mode 100644 index 5b39050fdc2989eb5c870704e1c1417987d53d46..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmdet/models/detectors/fast_rcnn.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from mmdet.registry import MODELS -from mmdet.utils import ConfigType, OptConfigType, OptMultiConfig -from .two_stage import TwoStageDetector - - -@MODELS.register_module() -class FastRCNN(TwoStageDetector): - """Implementation of `Fast R-CNN `_""" - - def __init__(self, - backbone: ConfigType, - roi_head: ConfigType, - train_cfg: ConfigType, - test_cfg: ConfigType, - neck: OptConfigType = None, - data_preprocessor: OptConfigType = None, - init_cfg: OptMultiConfig = None) -> None: - super().__init__( - backbone=backbone, - neck=neck, - roi_head=roi_head, - train_cfg=train_cfg, - test_cfg=test_cfg, - init_cfg=init_cfg, - data_preprocessor=data_preprocessor) diff --git a/spaces/LouieDellavega/dreamlike-photoreal-2.0/app.py b/spaces/LouieDellavega/dreamlike-photoreal-2.0/app.py deleted file mode 100644 index ebdb5095a0691dadeebfbd16dfdfeb5fa95a0400..0000000000000000000000000000000000000000 --- a/spaces/LouieDellavega/dreamlike-photoreal-2.0/app.py +++ /dev/null @@ -1,137 +0,0 @@ -from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler -import gradio as gr -import torch -from PIL import Image - -model_id = 'dreamlike-art/dreamlike-photoreal-2.0' -prefix = '' - -scheduler = DPMSolverMultistepScheduler.from_pretrained(model_id, subfolder="scheduler") - -pipe = StableDiffusionPipeline.from_pretrained( - model_id, - torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, - scheduler=scheduler) - -pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained( - model_id, - torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, - scheduler=scheduler) - -if torch.cuda.is_available(): - pipe = pipe.to("cuda") - pipe_i2i = pipe_i2i.to("cuda") - -def error_str(error, title="Error"): - return f"""#### {title} - {error}""" if error else "" - -def inference(prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt="", auto_prefix=False): - - generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None - prompt = f"{prefix} {prompt}" if auto_prefix else prompt - - try: - if img is not None: - return img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None - else: - return txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator), None - except Exception as e: - return None, error_str(e) - -def txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator): - - result = pipe( - prompt, - negative_prompt = neg_prompt, - num_inference_steps = int(steps), - guidance_scale = guidance, - width = width, - height = height, - generator = generator) - - return result.images[0] - -def img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator): - - ratio = min(height / img.height, width / img.width) - img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS) - result = pipe_i2i( - prompt, - negative_prompt = neg_prompt, - init_image = img, - num_inference_steps = int(steps), - strength = strength, - guidance_scale = guidance, - width = width, - height = height, - generator = generator) - - return result.images[0] - -css = """.main-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.main-div div h1{font-weight:900;margin-bottom:7px}.main-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem} -""" -with gr.Blocks(css=css) as demo: - gr.HTML( - f""" -
-
-

Dreamlike Photoreal 2.0

-
-

- Demo for Dreamlike Photoreal 2.0 Stable Diffusion model.
- {"Add the following tokens to your prompts for the model to work properly: prefix" if prefix else ""} -

- Running on {"GPU 🔥" if torch.cuda.is_available() else f"CPU 🥶. For faster inference it is recommended to upgrade to GPU in Settings"} after duplicating the space

- Duplicate Space -
- """ - ) - with gr.Row(): - - with gr.Column(scale=55): - with gr.Group(): - with gr.Row(): - prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder=f"{prefix} [your prompt]").style(container=False) - generate = gr.Button(value="Generate").style(rounded=(False, True, True, False)) - - image_out = gr.Image(height=512) - error_output = gr.Markdown() - - with gr.Column(scale=45): - with gr.Tab("Options"): - with gr.Group(): - neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image") - auto_prefix = gr.Checkbox(label="Prefix styling tokens automatically ()", value=prefix, visible=prefix) - - with gr.Row(): - guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15) - steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1) - - with gr.Row(): - width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8) - height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8) - - seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1) - - with gr.Tab("Image to image"): - with gr.Group(): - image = gr.Image(label="Image", height=256, tool="editor", type="pil") - strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5) - - auto_prefix.change(lambda x: gr.update(placeholder=f"{prefix} [your prompt]" if x else "[Your prompt]"), inputs=auto_prefix, outputs=prompt, queue=False) - - inputs = [prompt, guidance, steps, width, height, seed, image, strength, neg_prompt, auto_prefix] - outputs = [image_out, error_output] - prompt.submit(inference, inputs=inputs, outputs=outputs) - generate.click(inference, inputs=inputs, outputs=outputs) - - gr.HTML(""" -
-
-

This space was created using SD Space Creator.

-
- """) - -demo.queue(concurrency_count=1) -demo.launch() diff --git a/spaces/Luelll/ChuanhuChatGPT/modules/utils.py b/spaces/Luelll/ChuanhuChatGPT/modules/utils.py deleted file mode 100644 index a025a80d7b52f3ae788be960c17520d44bf56e49..0000000000000000000000000000000000000000 --- a/spaces/Luelll/ChuanhuChatGPT/modules/utils.py +++ /dev/null @@ -1,592 +0,0 @@ -# -*- coding:utf-8 -*- -from __future__ import annotations -from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type -import logging -import json -import os -import datetime -import hashlib -import csv -import requests -import re -import html -import sys -import subprocess - -import gradio as gr -from pypinyin import lazy_pinyin -import tiktoken -import mdtex2html -from markdown import markdown -from pygments import highlight -from pygments.lexers import get_lexer_by_name -from pygments.formatters import HtmlFormatter -import pandas as pd - -from modules.presets import * -from . import shared -from modules.config import retrieve_proxy, hide_history_when_not_logged_in - -if TYPE_CHECKING: - from typing import TypedDict - - class DataframeData(TypedDict): - headers: List[str] - data: List[List[str | int | bool]] - -def predict(current_model, *args): - iter = current_model.predict(*args) - for i in iter: - yield i - -def billing_info(current_model): - return current_model.billing_info() - -def set_key(current_model, *args): - return current_model.set_key(*args) - -def load_chat_history(current_model, *args): - return current_model.load_chat_history(*args) - -def interrupt(current_model, *args): - return current_model.interrupt(*args) - -def reset(current_model, *args): - return current_model.reset(*args) - -def retry(current_model, *args): - iter = current_model.retry(*args) - for i in iter: - yield i - -def delete_first_conversation(current_model, *args): - return current_model.delete_first_conversation(*args) - -def delete_last_conversation(current_model, *args): - return current_model.delete_last_conversation(*args) - -def set_system_prompt(current_model, *args): - return current_model.set_system_prompt(*args) - -def save_chat_history(current_model, *args): - return current_model.save_chat_history(*args) - -def export_markdown(current_model, *args): - return current_model.export_markdown(*args) - -def load_chat_history(current_model, *args): - return current_model.load_chat_history(*args) - -def upload_chat_history(current_model, *args): - return current_model.load_chat_history(*args) - -def set_token_upper_limit(current_model, *args): - return current_model.set_token_upper_limit(*args) - -def set_temperature(current_model, *args): - current_model.set_temperature(*args) - -def set_top_p(current_model, *args): - current_model.set_top_p(*args) - -def set_n_choices(current_model, *args): - current_model.set_n_choices(*args) - -def set_stop_sequence(current_model, *args): - current_model.set_stop_sequence(*args) - -def set_max_tokens(current_model, *args): - current_model.set_max_tokens(*args) - -def set_presence_penalty(current_model, *args): - current_model.set_presence_penalty(*args) - -def set_frequency_penalty(current_model, *args): - current_model.set_frequency_penalty(*args) - -def set_logit_bias(current_model, *args): - current_model.set_logit_bias(*args) - -def set_user_identifier(current_model, *args): - current_model.set_user_identifier(*args) - -def set_single_turn(current_model, *args): - current_model.set_single_turn(*args) - -def handle_file_upload(current_model, *args): - return current_model.handle_file_upload(*args) - -def like(current_model, *args): - return current_model.like(*args) - -def dislike(current_model, *args): - return current_model.dislike(*args) - - -def count_token(message): - encoding = tiktoken.get_encoding("cl100k_base") - input_str = f"role: {message['role']}, content: {message['content']}" - length = len(encoding.encode(input_str)) - return length - - -def markdown_to_html_with_syntax_highlight(md_str): - def replacer(match): - lang = match.group(1) or "text" - code = match.group(2) - - try: - lexer = get_lexer_by_name(lang, stripall=True) - except ValueError: - lexer = get_lexer_by_name("text", stripall=True) - - formatter = HtmlFormatter() - highlighted_code = highlight(code, lexer, formatter) - - return f'
{highlighted_code}
' - - code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```" - md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE) - - html_str = markdown(md_str) - return html_str - - -def normalize_markdown(md_text: str) -> str: - lines = md_text.split("\n") - normalized_lines = [] - inside_list = False - - for i, line in enumerate(lines): - if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()): - if not inside_list and i > 0 and lines[i - 1].strip() != "": - normalized_lines.append("") - inside_list = True - normalized_lines.append(line) - elif inside_list and line.strip() == "": - if i < len(lines) - 1 and not re.match( - r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip() - ): - normalized_lines.append(line) - continue - else: - inside_list = False - normalized_lines.append(line) - - return "\n".join(normalized_lines) - - -def convert_mdtext(md_text): - code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL) - inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL) - code_blocks = code_block_pattern.findall(md_text) - non_code_parts = code_block_pattern.split(md_text)[::2] - - result = [] - raw = f'
{html.escape(md_text)}
' - for non_code, code in zip(non_code_parts, code_blocks + [""]): - if non_code.strip(): - non_code = normalize_markdown(non_code) - result.append(markdown(non_code, extensions=["tables"])) - if code.strip(): - # _, code = detect_language(code) # 暂时去除代码高亮功能,因为在大段代码的情况下会出现问题 - # code = code.replace("\n\n", "\n") # 暂时去除代码中的空行,因为在大段代码的情况下会出现问题 - code = f"\n```{code}\n\n```" - code = markdown_to_html_with_syntax_highlight(code) - result.append(code) - result = "".join(result) - output = f'
{result}
' - output += raw - output += ALREADY_CONVERTED_MARK - return output - - -def convert_asis(userinput): - return ( - f'

{html.escape(userinput)}

' - + ALREADY_CONVERTED_MARK - ) - - -def detect_converted_mark(userinput): - try: - if userinput.endswith(ALREADY_CONVERTED_MARK): - return True - else: - return False - except: - return True - - -def detect_language(code): - if code.startswith("\n"): - first_line = "" - else: - first_line = code.strip().split("\n", 1)[0] - language = first_line.lower() if first_line else "" - code_without_language = code[len(first_line) :].lstrip() if first_line else code - return language, code_without_language - - -def construct_text(role, text): - return {"role": role, "content": text} - - -def construct_user(text): - return construct_text("user", text) - - -def construct_system(text): - return construct_text("system", text) - - -def construct_assistant(text): - return construct_text("assistant", text) - - -def save_file(filename, system, history, chatbot, user_name): - logging.debug(f"{user_name} 保存对话历史中……") - os.makedirs(os.path.join(HISTORY_DIR, user_name), exist_ok=True) - if filename.endswith(".json"): - json_s = {"system": system, "history": history, "chatbot": chatbot} - if "/" in filename or "\\" in filename: - history_file_path = filename - else: - history_file_path = os.path.join(HISTORY_DIR, user_name, filename) - with open(history_file_path, "w") as f: - json.dump(json_s, f) - elif filename.endswith(".md"): - md_s = f"system: \n- {system} \n" - for data in history: - md_s += f"\n{data['role']}: \n- {data['content']} \n" - with open(os.path.join(HISTORY_DIR, user_name, filename), "w", encoding="utf8") as f: - f.write(md_s) - logging.debug(f"{user_name} 保存对话历史完毕") - return os.path.join(HISTORY_DIR, user_name, filename) - - -def sorted_by_pinyin(list): - return sorted(list, key=lambda char: lazy_pinyin(char)[0][0]) - - -def get_file_names(dir, plain=False, filetypes=[".json"]): - logging.debug(f"获取文件名列表,目录为{dir},文件类型为{filetypes},是否为纯文本列表{plain}") - files = [] - try: - for type in filetypes: - files += [f for f in os.listdir(dir) if f.endswith(type)] - except FileNotFoundError: - files = [] - files = sorted_by_pinyin(files) - if files == []: - files = [""] - logging.debug(f"files are:{files}") - if plain: - return files - else: - return gr.Dropdown.update(choices=files) - - -def get_history_names(plain=False, user_name=""): - logging.debug(f"从用户 {user_name} 中获取历史记录文件名列表") - if user_name == "" and hide_history_when_not_logged_in: - return "" - else: - return get_file_names(os.path.join(HISTORY_DIR, user_name), plain) - - -def load_template(filename, mode=0): - logging.debug(f"加载模板文件{filename},模式为{mode}(0为返回字典和下拉菜单,1为返回下拉菜单,2为返回字典)") - lines = [] - if filename.endswith(".json"): - with open(os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8") as f: - lines = json.load(f) - lines = [[i["act"], i["prompt"]] for i in lines] - else: - with open( - os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8" - ) as csvfile: - reader = csv.reader(csvfile) - lines = list(reader) - lines = lines[1:] - if mode == 1: - return sorted_by_pinyin([row[0] for row in lines]) - elif mode == 2: - return {row[0]: row[1] for row in lines} - else: - choices = sorted_by_pinyin([row[0] for row in lines]) - return {row[0]: row[1] for row in lines}, gr.Dropdown.update( - choices=choices - ) - - -def get_template_names(plain=False): - logging.debug("获取模板文件名列表") - return get_file_names(TEMPLATES_DIR, plain, filetypes=[".csv", "json"]) - - -def get_template_content(templates, selection, original_system_prompt): - logging.debug(f"应用模板中,选择为{selection},原始系统提示为{original_system_prompt}") - try: - return templates[selection] - except: - return original_system_prompt - - -def reset_textbox(): - logging.debug("重置文本框") - return gr.update(value="") - - -def reset_default(): - default_host = shared.state.reset_api_host() - retrieve_proxy("") - return gr.update(value=default_host), gr.update(value=""), "API-Host 和代理已重置" - - -def change_api_host(host): - shared.state.set_api_host(host) - msg = f"API-Host更改为了{host}" - logging.info(msg) - return msg - - -def change_proxy(proxy): - retrieve_proxy(proxy) - os.environ["HTTPS_PROXY"] = proxy - msg = f"代理更改为了{proxy}" - logging.info(msg) - return msg - - -def hide_middle_chars(s): - if s is None: - return "" - if len(s) <= 8: - return s - else: - head = s[:4] - tail = s[-4:] - hidden = "*" * (len(s) - 8) - return head + hidden + tail - - -def submit_key(key): - key = key.strip() - msg = f"API密钥更改为了{hide_middle_chars(key)}" - logging.info(msg) - return key, msg - - -def replace_today(prompt): - today = datetime.datetime.today().strftime("%Y-%m-%d") - return prompt.replace("{current_date}", today) - - -def get_geoip(): - try: - with retrieve_proxy(): - response = requests.get("https://ipapi.co/json/", timeout=5) - data = response.json() - except: - data = {"error": True, "reason": "连接ipapi失败"} - if "error" in data.keys(): - logging.warning(f"无法获取IP地址信息。\n{data}") - if data["reason"] == "RateLimited": - return ( - i18n("您的IP区域:未知。") - ) - else: - return i18n("获取IP地理位置失败。原因:") + f"{data['reason']}" + i18n("。你仍然可以使用聊天功能。") - else: - country = data["country_name"] - if country == "China": - text = "**您的IP区域:中国。请立即检查代理设置,在不受支持的地区使用API可能导致账号被封禁。**" - else: - text = i18n("您的IP区域:") + f"{country}。" - logging.info(text) - return text - - -def find_n(lst, max_num): - n = len(lst) - total = sum(lst) - - if total < max_num: - return n - - for i in range(len(lst)): - if total - lst[i] < max_num: - return n - i - 1 - total = total - lst[i] - return 1 - - -def start_outputing(): - logging.debug("显示取消按钮,隐藏发送按钮") - return gr.Button.update(visible=False), gr.Button.update(visible=True) - - -def end_outputing(): - return ( - gr.Button.update(visible=True), - gr.Button.update(visible=False), - ) - - -def cancel_outputing(): - logging.info("中止输出……") - shared.state.interrupt() - - -def transfer_input(inputs): - # 一次性返回,降低延迟 - textbox = reset_textbox() - outputing = start_outputing() - return ( - inputs, - gr.update(value=""), - gr.Button.update(visible=False), - gr.Button.update(visible=True), - ) - - - -def run(command, desc=None, errdesc=None, custom_env=None, live=False): - if desc is not None: - print(desc) - if live: - result = subprocess.run(command, shell=True, env=os.environ if custom_env is None else custom_env) - if result.returncode != 0: - raise RuntimeError(f"""{errdesc or 'Error running command'}. - Command: {command} - Error code: {result.returncode}""") - - return "" - result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=os.environ if custom_env is None else custom_env) - if result.returncode != 0: - message = f"""{errdesc or 'Error running command'}. - Command: {command} - Error code: {result.returncode} - stdout: {result.stdout.decode(encoding="utf8", errors="ignore") if len(result.stdout)>0 else ''} - stderr: {result.stderr.decode(encoding="utf8", errors="ignore") if len(result.stderr)>0 else ''} - """ - raise RuntimeError(message) - return result.stdout.decode(encoding="utf8", errors="ignore") - -def versions_html(): - git = os.environ.get('GIT', "git") - python_version = ".".join([str(x) for x in sys.version_info[0:3]]) - try: - commit_hash = run(f"{git} rev-parse HEAD").strip() - except Exception: - commit_hash = "" - if commit_hash != "": - short_commit = commit_hash[0:7] - commit_info = f"{short_commit}" - else: - commit_info = "unknown \U0001F615" - return f""" - Python: {python_version} -  •  - Gradio: {gr.__version__} -  •  - ChuanhuChat: {commit_info} - """ - -def add_source_numbers(lst, source_name = "Source", use_source = True): - if use_source: - return [f'[{idx+1}]\t "{item[0]}"\n{source_name}: {item[1]}' for idx, item in enumerate(lst)] - else: - return [f'[{idx+1}]\t "{item}"' for idx, item in enumerate(lst)] - -def add_details(lst): - nodes = [] - for index, txt in enumerate(lst): - brief = txt[:25].replace("\n", "") - nodes.append( - f"
{brief}...

{txt}

" - ) - return nodes - - -def sheet_to_string(sheet, sheet_name = None): - result = [] - for index, row in sheet.iterrows(): - row_string = "" - for column in sheet.columns: - row_string += f"{column}: {row[column]}, " - row_string = row_string.rstrip(", ") - row_string += "." - result.append(row_string) - return result - -def excel_to_string(file_path): - # 读取Excel文件中的所有工作表 - excel_file = pd.read_excel(file_path, engine='openpyxl', sheet_name=None) - - # 初始化结果字符串 - result = [] - - # 遍历每一个工作表 - for sheet_name, sheet_data in excel_file.items(): - - # 处理当前工作表并添加到结果字符串 - result += sheet_to_string(sheet_data, sheet_name=sheet_name) - - - return result - -def get_last_day_of_month(any_day): - # The day 28 exists in every month. 4 days later, it's always next month - next_month = any_day.replace(day=28) + datetime.timedelta(days=4) - # subtracting the number of the current day brings us back one month - return next_month - datetime.timedelta(days=next_month.day) - -def get_model_source(model_name, alternative_source): - if model_name == "gpt2-medium": - return "https://huggingface.co/gpt2-medium" - -def refresh_ui_elements_on_load(current_model, selected_model_name, user_name): - current_model.set_user_identifier(user_name) - return toggle_like_btn_visibility(selected_model_name), *current_model.auto_load() - -def toggle_like_btn_visibility(selected_model_name): - if selected_model_name == "xmchat": - return gr.update(visible=True) - else: - return gr.update(visible=False) - -def new_auto_history_filename(dirname): - latest_file = get_latest_filepath(dirname) - if latest_file: - with open(os.path.join(dirname, latest_file), 'r') as f: - if len(f.read()) == 0: - return latest_file - now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') - return f'{now}.json' - -def get_latest_filepath(dirname): - pattern = re.compile(r'\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}') - latest_time = None - latest_file = None - for filename in os.listdir(dirname): - if os.path.isfile(os.path.join(dirname, filename)): - match = pattern.search(filename) - if match and match.group(0) == filename[:19]: - time_str = filename[:19] - filetime = datetime.datetime.strptime(time_str, '%Y-%m-%d_%H-%M-%S') - if not latest_time or filetime > latest_time: - latest_time = filetime - latest_file = filename - return latest_file - -def get_history_filepath(username): - dirname = os.path.join(HISTORY_DIR, username) - os.makedirs(dirname, exist_ok=True) - latest_file = get_latest_filepath(dirname) - if not latest_file: - latest_file = new_auto_history_filename(dirname) - - latest_file = os.path.join(dirname, latest_file) - return latest_file diff --git a/spaces/Mahiruoshi/Lovelive-Nijigasaku-Chat-iSTFT-GPT3/text/cleaners.py b/spaces/Mahiruoshi/Lovelive-Nijigasaku-Chat-iSTFT-GPT3/text/cleaners.py deleted file mode 100644 index d407014bb09ffb071fbe91a508c7dd4755f54c4b..0000000000000000000000000000000000000000 --- a/spaces/Mahiruoshi/Lovelive-Nijigasaku-Chat-iSTFT-GPT3/text/cleaners.py +++ /dev/null @@ -1,175 +0,0 @@ -import re -from text.japanese import japanese_to_romaji_with_accent, japanese_to_ipa, japanese_to_ipa2, japanese_to_ipa3 -from text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo, chinese_to_romaji, chinese_to_lazy_ipa, chinese_to_ipa, chinese_to_ipa2 -# from text.sanskrit import devanagari_to_ipa -# from text.english import english_to_lazy_ipa, english_to_ipa2, english_to_lazy_ipa2 -# from text.thai import num_to_thai, latin_to_thai -# from text.shanghainese import shanghainese_to_ipa -# from text.cantonese import cantonese_to_ipa -# from text.ngu_dialect import ngu_dialect_to_ipa - - -def japanese_cleaners(text): - text = japanese_to_romaji_with_accent(text) - if re.match('[A-Za-z]', text[-1]): - text += '.' - return text - - -def japanese_cleaners2(text): - return japanese_cleaners(text).replace('ts', 'ʦ').replace('...', '…') - - -def korean_cleaners(text): - '''Pipeline for Korean text''' - text = latin_to_hangul(text) - text = number_to_hangul(text) - text = divide_hangul(text) - if re.match('[\u3131-\u3163]', text[-1]): - text += '.' - return text - - -def chinese_cleaners(text): - '''Pipeline for Chinese text''' - text = number_to_chinese(text) - text = chinese_to_bopomofo(text) - text = latin_to_bopomofo(text) - if re.match('[ˉˊˇˋ˙]', text[-1]): - text += '。' - return text - - -def zh_ja_mixture_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_romaji(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_romaji_with_accent( - japanese_text[4:-4]).replace('ts', 'ʦ').replace('u', 'ɯ').replace('...', '…') - text = text.replace(japanese_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match('[A-Za-zɯɹəɥ→↓↑]', text[-1]): - text += '.' - return text - - -def sanskrit_cleaners(text): - text = text.replace('॥', '।').replace('ॐ', 'ओम्') - if text[-1] != '।': - text += ' ।' - return text - - -def cjks_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - sanskrit_texts = re.findall(r'\[SA\].*?\[SA\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_lazy_ipa(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa(japanese_text[4:-4]) - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_lazy_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - for sanskrit_text in sanskrit_texts: - cleaned_text = devanagari_to_ipa(sanskrit_text[4:-4]) - text = text.replace(sanskrit_text, cleaned_text+' ', 1) - for english_text in english_texts: - cleaned_text = english_to_lazy_ipa(english_text[4:-4]) - text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def cjke_cleaners(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_lazy_ipa(chinese_text[4:-4]) - cleaned_text = cleaned_text.replace( - 'ʧ', 'tʃ').replace('ʦ', 'ts').replace('ɥan', 'ɥæn') - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa(japanese_text[4:-4]) - cleaned_text = cleaned_text.replace('ʧ', 'tʃ').replace( - 'ʦ', 'ts').replace('ɥan', 'ɥæn').replace('ʥ', 'dz') - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - for english_text in english_texts: - cleaned_text = english_to_ipa2(english_text[4:-4]) - cleaned_text = cleaned_text.replace('ɑ', 'a').replace( - 'ɔ', 'o').replace('ɛ', 'e').replace('ɪ', 'i').replace('ʊ', 'u') - text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def cjke_cleaners2(text): - chinese_texts = re.findall(r'\[ZH\].*?\[ZH\]', text) - japanese_texts = re.findall(r'\[JA\].*?\[JA\]', text) - korean_texts = re.findall(r'\[KO\].*?\[KO\]', text) - english_texts = re.findall(r'\[EN\].*?\[EN\]', text) - for chinese_text in chinese_texts: - cleaned_text = chinese_to_ipa(chinese_text[4:-4]) - text = text.replace(chinese_text, cleaned_text+' ', 1) - for japanese_text in japanese_texts: - cleaned_text = japanese_to_ipa2(japanese_text[4:-4]) - text = text.replace(japanese_text, cleaned_text+' ', 1) - for korean_text in korean_texts: - cleaned_text = korean_to_ipa(korean_text[4:-4]) - text = text.replace(korean_text, cleaned_text+' ', 1) - for english_text in english_texts: - cleaned_text = english_to_ipa2(english_text[4:-4]) - text = text.replace(english_text, cleaned_text+' ', 1) - text = text[:-1] - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def thai_cleaners(text): - text = num_to_thai(text) - text = latin_to_thai(text) - return text - - -def shanghainese_cleaners(text): - text = shanghainese_to_ipa(text) - if re.match(r'[^\.,!\?\-…~]', text[-1]): - text += '.' - return text - - -def chinese_dialect_cleaners(text): - text = re.sub(r'\[MD\](.*?)\[MD\]', - lambda x: chinese_to_ipa2(x.group(1))+' ', text) - text = re.sub(r'\[TW\](.*?)\[TW\]', - lambda x: chinese_to_ipa2(x.group(1), True)+' ', text) - text = re.sub(r'\[JA\](.*?)\[JA\]', - lambda x: japanese_to_ipa3(x.group(1)).replace('Q', 'ʔ')+' ', text) - text = re.sub(r'\[SH\](.*?)\[SH\]', lambda x: shanghainese_to_ipa(x.group(1)).replace('1', '˥˧').replace('5', - '˧˧˦').replace('6', '˩˩˧').replace('7', '˥').replace('8', '˩˨').replace('ᴀ', 'ɐ').replace('ᴇ', 'e')+' ', text) - text = re.sub(r'\[GD\](.*?)\[GD\]', - lambda x: cantonese_to_ipa(x.group(1))+' ', text) - text = re.sub(r'\[EN\](.*?)\[EN\]', - lambda x: english_to_lazy_ipa2(x.group(1))+' ', text) - text = re.sub(r'\[([A-Z]{2})\](.*?)\[\1\]', lambda x: ngu_dialect_to_ipa(x.group(2), x.group( - 1)).replace('ʣ', 'dz').replace('ʥ', 'dʑ').replace('ʦ', 'ts').replace('ʨ', 'tɕ')+' ', text) - text = re.sub(r'\s+$', '', text) - text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text) - return text diff --git a/spaces/Mahiruoshi/lovelive-ShojoKageki-vits/modules.py b/spaces/Mahiruoshi/lovelive-ShojoKageki-vits/modules.py deleted file mode 100644 index 0f9286cd02b123d54f38e5c2bb144cc01056d080..0000000000000000000000000000000000000000 --- a/spaces/Mahiruoshi/lovelive-ShojoKageki-vits/modules.py +++ /dev/null @@ -1,469 +0,0 @@ -import math - -import torch -from torch import nn -from torch.nn import functional as F -from torch.nn import Conv1d -from torch.nn.utils import weight_norm, remove_weight_norm - -import commons -from commons import init_weights, get_padding -from transforms import piecewise_rational_quadratic_transform - -LRELU_SLOPE = 0.1 - - -class LayerNorm(nn.Module): - def __init__(self, channels, eps=1e-5): - super().__init__() - self.channels = channels - self.eps = eps - - self.gamma = nn.Parameter(torch.ones(channels)) - self.beta = nn.Parameter(torch.zeros(channels)) - - def forward(self, x): - x = x.transpose(1, -1) - x = F.layer_norm(x, (self.channels, ), self.gamma, self.beta, self.eps) - return x.transpose(1, -1) - - -class ConvReluNorm(nn.Module): - def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, - n_layers, p_dropout): - super().__init__() - self.in_channels = in_channels - self.hidden_channels = hidden_channels - self.out_channels = out_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.p_dropout = p_dropout - assert n_layers > 1, "Number of layers should be larger than 0." - - self.conv_layers = nn.ModuleList() - self.norm_layers = nn.ModuleList() - self.conv_layers.append( - nn.Conv1d(in_channels, - hidden_channels, - kernel_size, - padding=kernel_size // 2)) - self.norm_layers.append(LayerNorm(hidden_channels)) - self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout)) - for _ in range(n_layers - 1): - self.conv_layers.append( - nn.Conv1d(hidden_channels, - hidden_channels, - kernel_size, - padding=kernel_size // 2)) - self.norm_layers.append(LayerNorm(hidden_channels)) - self.proj = nn.Conv1d(hidden_channels, out_channels, 1) - self.proj.weight.data.zero_() - self.proj.bias.data.zero_() - - def forward(self, x, x_mask): - x_org = x - for i in range(self.n_layers): - x = self.conv_layers[i](x * x_mask) - x = self.norm_layers[i](x) - x = self.relu_drop(x) - x = x_org + self.proj(x) - return x * x_mask - - -class DDSConv(nn.Module): - """ - Dialted and Depth-Separable Convolution - """ - def __init__(self, channels, kernel_size, n_layers, p_dropout=0.): - super().__init__() - self.channels = channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.p_dropout = p_dropout - - self.drop = nn.Dropout(p_dropout) - self.convs_sep = nn.ModuleList() - self.convs_1x1 = nn.ModuleList() - self.norms_1 = nn.ModuleList() - self.norms_2 = nn.ModuleList() - for i in range(n_layers): - dilation = kernel_size**i - padding = (kernel_size * dilation - dilation) // 2 - self.convs_sep.append( - nn.Conv1d(channels, - channels, - kernel_size, - groups=channels, - dilation=dilation, - padding=padding)) - self.convs_1x1.append(nn.Conv1d(channels, channels, 1)) - self.norms_1.append(LayerNorm(channels)) - self.norms_2.append(LayerNorm(channels)) - - def forward(self, x, x_mask, g=None): - if g is not None: - x = x + g - for i in range(self.n_layers): - y = self.convs_sep[i](x * x_mask) - y = self.norms_1[i](y) - y = F.gelu(y) - y = self.convs_1x1[i](y) - y = self.norms_2[i](y) - y = F.gelu(y) - y = self.drop(y) - x = x + y - return x * x_mask - - -class WN(torch.nn.Module): - def __init__(self, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - p_dropout=0): - super(WN, self).__init__() - assert (kernel_size % 2 == 1) - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size, - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - self.p_dropout = p_dropout - - self.in_layers = torch.nn.ModuleList() - self.res_skip_layers = torch.nn.ModuleList() - self.drop = nn.Dropout(p_dropout) - - if gin_channels != 0: - cond_layer = torch.nn.Conv1d(gin_channels, - 2 * hidden_channels * n_layers, 1) - self.cond_layer = torch.nn.utils.weight_norm(cond_layer, - name='weight') - - for i in range(n_layers): - dilation = dilation_rate**i - padding = int((kernel_size * dilation - dilation) / 2) - in_layer = torch.nn.Conv1d(hidden_channels, - 2 * hidden_channels, - kernel_size, - dilation=dilation, - padding=padding) - in_layer = torch.nn.utils.weight_norm(in_layer, name='weight') - self.in_layers.append(in_layer) - - # last one is not necessary - if i < n_layers - 1: - res_skip_channels = 2 * hidden_channels - else: - res_skip_channels = hidden_channels - - res_skip_layer = torch.nn.Conv1d(hidden_channels, - res_skip_channels, 1) - res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, - name='weight') - self.res_skip_layers.append(res_skip_layer) - - def forward(self, x, x_mask, g=None, **kwargs): - output = torch.zeros_like(x) - n_channels_tensor = torch.IntTensor([self.hidden_channels]) - - if g is not None: - g = self.cond_layer(g) - - for i in range(self.n_layers): - x_in = self.in_layers[i](x) - if g is not None: - cond_offset = i * 2 * self.hidden_channels - g_l = g[:, - cond_offset:cond_offset + 2 * self.hidden_channels, :] - else: - g_l = torch.zeros_like(x_in) - - acts = commons.fused_add_tanh_sigmoid_multiply( - x_in, g_l, n_channels_tensor) - acts = self.drop(acts) - - res_skip_acts = self.res_skip_layers[i](acts) - if i < self.n_layers - 1: - res_acts = res_skip_acts[:, :self.hidden_channels, :] - x = (x + res_acts) * x_mask - output = output + res_skip_acts[:, self.hidden_channels:, :] - else: - output = output + res_skip_acts - return output * x_mask - - def remove_weight_norm(self): - if self.gin_channels != 0: - torch.nn.utils.remove_weight_norm(self.cond_layer) - for l in self.in_layers: - torch.nn.utils.remove_weight_norm(l) - for l in self.res_skip_layers: - torch.nn.utils.remove_weight_norm(l) - - -class ResBlock1(torch.nn.Module): - def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)): - super(ResBlock1, self).__init__() - self.convs1 = nn.ModuleList([ - weight_norm( - Conv1d(channels, - channels, - kernel_size, - 1, - dilation=dilation[0], - padding=get_padding(kernel_size, dilation[0]))), - weight_norm( - Conv1d(channels, - channels, - kernel_size, - 1, - dilation=dilation[1], - padding=get_padding(kernel_size, dilation[1]))), - weight_norm( - Conv1d(channels, - channels, - kernel_size, - 1, - dilation=dilation[2], - padding=get_padding(kernel_size, dilation[2]))) - ]) - self.convs1.apply(init_weights) - - self.convs2 = nn.ModuleList([ - weight_norm( - Conv1d(channels, - channels, - kernel_size, - 1, - dilation=1, - padding=get_padding(kernel_size, 1))), - weight_norm( - Conv1d(channels, - channels, - kernel_size, - 1, - dilation=1, - padding=get_padding(kernel_size, 1))), - weight_norm( - Conv1d(channels, - channels, - kernel_size, - 1, - dilation=1, - padding=get_padding(kernel_size, 1))) - ]) - self.convs2.apply(init_weights) - - def forward(self, x, x_mask=None): - for c1, c2 in zip(self.convs1, self.convs2): - xt = F.leaky_relu(x, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c1(xt) - xt = F.leaky_relu(xt, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c2(xt) - x = xt + x - if x_mask is not None: - x = x * x_mask - return x - - def remove_weight_norm(self): - for l in self.convs1: - remove_weight_norm(l) - for l in self.convs2: - remove_weight_norm(l) - - -class ResBlock2(torch.nn.Module): - def __init__(self, channels, kernel_size=3, dilation=(1, 3)): - super(ResBlock2, self).__init__() - self.convs = nn.ModuleList([ - weight_norm( - Conv1d(channels, - channels, - kernel_size, - 1, - dilation=dilation[0], - padding=get_padding(kernel_size, dilation[0]))), - weight_norm( - Conv1d(channels, - channels, - kernel_size, - 1, - dilation=dilation[1], - padding=get_padding(kernel_size, dilation[1]))) - ]) - self.convs.apply(init_weights) - - def forward(self, x, x_mask=None): - for c in self.convs: - xt = F.leaky_relu(x, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c(xt) - x = xt + x - if x_mask is not None: - x = x * x_mask - return x - - def remove_weight_norm(self): - for l in self.convs: - remove_weight_norm(l) - - -class Log(nn.Module): - def forward(self, x, x_mask, reverse=False, **kwargs): - if not reverse: - y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask - logdet = torch.sum(-y, [1, 2]) - return y, logdet - else: - x = torch.exp(x) * x_mask - return x - - -class Flip(nn.Module): - def forward(self, x, *args, reverse=False, **kwargs): - x = torch.flip(x, [1]) - if not reverse: - logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device) - return x, logdet - else: - return x - - -class ElementwiseAffine(nn.Module): - def __init__(self, channels): - super().__init__() - self.channels = channels - self.m = nn.Parameter(torch.zeros(channels, 1)) - self.logs = nn.Parameter(torch.zeros(channels, 1)) - - def forward(self, x, x_mask, reverse=False, **kwargs): - if not reverse: - y = self.m + torch.exp(self.logs) * x - y = y * x_mask - logdet = torch.sum(self.logs * x_mask, [1, 2]) - return y, logdet - else: - x = (x - self.m) * torch.exp(-self.logs) * x_mask - return x - - -class ResidualCouplingLayer(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - p_dropout=0, - gin_channels=0, - mean_only=False): - assert channels % 2 == 0, "channels should be divisible by 2" - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.half_channels = channels // 2 - self.mean_only = mean_only - - self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1) - self.enc = WN(hidden_channels, - kernel_size, - dilation_rate, - n_layers, - p_dropout=p_dropout, - gin_channels=gin_channels) - self.post = nn.Conv1d(hidden_channels, - self.half_channels * (2 - mean_only), 1) - self.post.weight.data.zero_() - self.post.bias.data.zero_() - - def forward(self, x, x_mask, g=None, reverse=False): - x0, x1 = torch.split(x, [self.half_channels] * 2, 1) - h = self.pre(x0) * x_mask - h = self.enc(h, x_mask, g=g) - stats = self.post(h) * x_mask - if not self.mean_only: - m, logs = torch.split(stats, [self.half_channels] * 2, 1) - else: - m = stats - logs = torch.zeros_like(m) - - if not reverse: - x1 = m + x1 * torch.exp(logs) * x_mask - x = torch.cat([x0, x1], 1) - logdet = torch.sum(logs, [1, 2]) - return x, logdet - else: - x1 = (x1 - m) * torch.exp(-logs) * x_mask - x = torch.cat([x0, x1], 1) - return x - - -class ConvFlow(nn.Module): - def __init__(self, - in_channels, - filter_channels, - kernel_size, - n_layers, - num_bins=10, - tail_bound=5.0): - super().__init__() - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.num_bins = num_bins - self.tail_bound = tail_bound - self.half_channels = in_channels // 2 - - self.pre = nn.Conv1d(self.half_channels, filter_channels, 1) - self.convs = DDSConv(filter_channels, - kernel_size, - n_layers, - p_dropout=0.) - self.proj = nn.Conv1d(filter_channels, - self.half_channels * (num_bins * 3 - 1), 1) - self.proj.weight.data.zero_() - self.proj.bias.data.zero_() - - def forward(self, x, x_mask, g=None, reverse=False): - x0, x1 = torch.split(x, [self.half_channels] * 2, 1) - h = self.pre(x0) - h = self.convs(h, x_mask, g=g) - h = self.proj(h) * x_mask - - b, c, t = x0.shape - h = h.reshape(b, c, -1, t).permute(0, 1, 3, - 2) # [b, cx?, t] -> [b, c, t, ?] - - unnormalized_widths = h[..., :self.num_bins] / math.sqrt( - self.filter_channels) - unnormalized_heights = h[..., - self.num_bins:2 * self.num_bins] / math.sqrt( - self.filter_channels) - unnormalized_derivatives = h[..., 2 * self.num_bins:] - - x1, logabsdet = piecewise_rational_quadratic_transform( - x1, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=reverse, - tails='linear', - tail_bound=self.tail_bound) - - x = torch.cat([x0, x1], 1) * x_mask - logdet = torch.sum(logabsdet * x_mask, [1, 2]) - if not reverse: - return x, logdet - else: - return x diff --git a/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/GroundedSAM/GroundingDINO/groundingdino/util/slio.py b/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/GroundedSAM/GroundingDINO/groundingdino/util/slio.py deleted file mode 100644 index 72c1f0f7b82cdc931d381feef64fe15815ba657e..0000000000000000000000000000000000000000 --- a/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/GroundedSAM/GroundingDINO/groundingdino/util/slio.py +++ /dev/null @@ -1,177 +0,0 @@ -# ========================================================== -# Modified from mmcv -# ========================================================== - -import json -import pickle -from abc import ABCMeta, abstractmethod -from pathlib import Path - -import yaml - -try: - from yaml import CLoader as Loader, CDumper as Dumper -except ImportError: - from yaml import Loader, Dumper - - -# =========================== -# Rigister handler -# =========================== - - -class BaseFileHandler(metaclass=ABCMeta): - @abstractmethod - def load_from_fileobj(self, file, **kwargs): - pass - - @abstractmethod - def dump_to_fileobj(self, obj, file, **kwargs): - pass - - @abstractmethod - def dump_to_str(self, obj, **kwargs): - pass - - def load_from_path(self, filepath, mode="r", **kwargs): - with open(filepath, mode) as f: - return self.load_from_fileobj(f, **kwargs) - - def dump_to_path(self, obj, filepath, mode="w", **kwargs): - with open(filepath, mode) as f: - self.dump_to_fileobj(obj, f, **kwargs) - - -class JsonHandler(BaseFileHandler): - def load_from_fileobj(self, file): - return json.load(file) - - def dump_to_fileobj(self, obj, file, **kwargs): - json.dump(obj, file, **kwargs) - - def dump_to_str(self, obj, **kwargs): - return json.dumps(obj, **kwargs) - - -class PickleHandler(BaseFileHandler): - def load_from_fileobj(self, file, **kwargs): - return pickle.load(file, **kwargs) - - def load_from_path(self, filepath, **kwargs): - return super(PickleHandler, self).load_from_path(filepath, mode="rb", **kwargs) - - def dump_to_str(self, obj, **kwargs): - kwargs.setdefault("protocol", 2) - return pickle.dumps(obj, **kwargs) - - def dump_to_fileobj(self, obj, file, **kwargs): - kwargs.setdefault("protocol", 2) - pickle.dump(obj, file, **kwargs) - - def dump_to_path(self, obj, filepath, **kwargs): - super(PickleHandler, self).dump_to_path(obj, filepath, mode="wb", **kwargs) - - -class YamlHandler(BaseFileHandler): - def load_from_fileobj(self, file, **kwargs): - kwargs.setdefault("Loader", Loader) - return yaml.load(file, **kwargs) - - def dump_to_fileobj(self, obj, file, **kwargs): - kwargs.setdefault("Dumper", Dumper) - yaml.dump(obj, file, **kwargs) - - def dump_to_str(self, obj, **kwargs): - kwargs.setdefault("Dumper", Dumper) - return yaml.dump(obj, **kwargs) - - -file_handlers = { - "json": JsonHandler(), - "yaml": YamlHandler(), - "yml": YamlHandler(), - "pickle": PickleHandler(), - "pkl": PickleHandler(), -} - -# =========================== -# load and dump -# =========================== - - -def is_str(x): - """Whether the input is an string instance. - - Note: This method is deprecated since python 2 is no longer supported. - """ - return isinstance(x, str) - - -def slload(file, file_format=None, **kwargs): - """Load data from json/yaml/pickle files. - - This method provides a unified api for loading data from serialized files. - - Args: - file (str or :obj:`Path` or file-like object): Filename or a file-like - object. - file_format (str, optional): If not specified, the file format will be - inferred from the file extension, otherwise use the specified one. - Currently supported formats include "json", "yaml/yml" and - "pickle/pkl". - - Returns: - The content from the file. - """ - if isinstance(file, Path): - file = str(file) - if file_format is None and is_str(file): - file_format = file.split(".")[-1] - if file_format not in file_handlers: - raise TypeError(f"Unsupported format: {file_format}") - - handler = file_handlers[file_format] - if is_str(file): - obj = handler.load_from_path(file, **kwargs) - elif hasattr(file, "read"): - obj = handler.load_from_fileobj(file, **kwargs) - else: - raise TypeError('"file" must be a filepath str or a file-object') - return obj - - -def sldump(obj, file=None, file_format=None, **kwargs): - """Dump data to json/yaml/pickle strings or files. - - This method provides a unified api for dumping data as strings or to files, - and also supports custom arguments for each file format. - - Args: - obj (any): The python object to be dumped. - file (str or :obj:`Path` or file-like object, optional): If not - specified, then the object is dump to a str, otherwise to a file - specified by the filename or file-like object. - file_format (str, optional): Same as :func:`load`. - - Returns: - bool: True for success, False otherwise. - """ - if isinstance(file, Path): - file = str(file) - if file_format is None: - if is_str(file): - file_format = file.split(".")[-1] - elif file is None: - raise ValueError("file_format must be specified since file is None") - if file_format not in file_handlers: - raise TypeError(f"Unsupported format: {file_format}") - - handler = file_handlers[file_format] - if file is None: - return handler.dump_to_str(obj, **kwargs) - elif is_str(file): - handler.dump_to_path(obj, file, **kwargs) - elif hasattr(file, "write"): - handler.dump_to_fileobj(obj, file, **kwargs) - else: - raise TypeError('"file" must be a filename str or a file-object') diff --git a/spaces/Mellow-ai/PhotoAI_Mellow/ldm/modules/midas/midas/base_model.py b/spaces/Mellow-ai/PhotoAI_Mellow/ldm/modules/midas/midas/base_model.py deleted file mode 100644 index 5cf430239b47ec5ec07531263f26f5c24a2311cd..0000000000000000000000000000000000000000 --- a/spaces/Mellow-ai/PhotoAI_Mellow/ldm/modules/midas/midas/base_model.py +++ /dev/null @@ -1,16 +0,0 @@ -import torch - - -class BaseModel(torch.nn.Module): - def load(self, path): - """Load model from file. - - Args: - path (str): file path - """ - parameters = torch.load(path, map_location=torch.device('cpu')) - - if "optimizer" in parameters: - parameters = parameters["model"] - - self.load_state_dict(parameters) diff --git a/spaces/Mountchicken/MAERec-Gradio/configs/textdet/dbnet/dbnet_resnet50-dcnv2_fpnc_1200e_icdar2015.py b/spaces/Mountchicken/MAERec-Gradio/configs/textdet/dbnet/dbnet_resnet50-dcnv2_fpnc_1200e_icdar2015.py deleted file mode 100644 index f961a2e70c9a17d0bfbfbc5963bd8a0da79427b1..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/configs/textdet/dbnet/dbnet_resnet50-dcnv2_fpnc_1200e_icdar2015.py +++ /dev/null @@ -1,33 +0,0 @@ -_base_ = [ - '_base_dbnet_resnet50-dcnv2_fpnc.py', - '../_base_/datasets/icdar2015.py', - '../_base_/default_runtime.py', - '../_base_/schedules/schedule_sgd_1200e.py', -] - -# TODO: Replace the link -load_from = 'https://download.openmmlab.com/mmocr/textdet/dbnet/tmp_1.0_pretrain/dbnet_r50dcnv2_fpnc_sbn_2e_synthtext_20210325-ed322016.pth' # noqa - -# dataset settings -icdar2015_textdet_train = _base_.icdar2015_textdet_train -icdar2015_textdet_train.pipeline = _base_.train_pipeline -icdar2015_textdet_test = _base_.icdar2015_textdet_test -icdar2015_textdet_test.pipeline = _base_.test_pipeline - -train_dataloader = dict( - batch_size=16, - num_workers=8, - persistent_workers=True, - sampler=dict(type='DefaultSampler', shuffle=True), - dataset=icdar2015_textdet_train) - -val_dataloader = dict( - batch_size=1, - num_workers=4, - persistent_workers=True, - sampler=dict(type='DefaultSampler', shuffle=False), - dataset=icdar2015_textdet_test) - -test_dataloader = val_dataloader - -auto_scale_lr = dict(base_batch_size=16) diff --git a/spaces/Mountchicken/MAERec-Gradio/configs/textrecog/nrtr/_base_nrtr_resnet31.py b/spaces/Mountchicken/MAERec-Gradio/configs/textrecog/nrtr/_base_nrtr_resnet31.py deleted file mode 100644 index e9367d98074141329fa1676a839c876720c231d6..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/configs/textrecog/nrtr/_base_nrtr_resnet31.py +++ /dev/null @@ -1,117 +0,0 @@ -dictionary = dict( - type='Dictionary', - dict_file='{{ fileDirname }}/../../../dicts/english_digits_symbols.txt', - with_padding=True, - with_unknown=True, - same_start_end=True, - with_start=True, - with_end=True) - -model = dict( - type='NRTR', - backbone=dict( - type='ResNet31OCR', - layers=[1, 2, 5, 3], - channels=[32, 64, 128, 256, 512, 512], - stage4_pool_cfg=dict(kernel_size=(2, 1), stride=(2, 1)), - last_stage_pool=True), - encoder=dict(type='NRTREncoder'), - decoder=dict( - type='NRTRDecoder', - module_loss=dict( - type='CEModuleLoss', ignore_first_char=True, flatten=True), - postprocessor=dict(type='AttentionPostprocessor'), - dictionary=dictionary, - max_seq_len=30, - ), - data_preprocessor=dict( - type='TextRecogDataPreprocessor', - mean=[123.675, 116.28, 103.53], - std=[58.395, 57.12, 57.375])) - -train_pipeline = [ - dict(type='LoadImageFromFile', ignore_empty=True, min_size=0), - dict(type='LoadOCRAnnotations', with_text=True), - dict( - type='RescaleToHeight', - height=32, - min_width=32, - max_width=160, - width_divisor=4), - dict(type='PadToWidth', width=160), - dict( - type='PackTextRecogInputs', - meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_ratio')) -] - -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='RescaleToHeight', - height=32, - min_width=32, - max_width=160, - width_divisor=16), - dict(type='PadToWidth', width=160), - # add loading annotation after ``Resize`` because ground truth - # does not need to do resize data transform - dict(type='LoadOCRAnnotations', with_text=True), - dict( - type='PackTextRecogInputs', - meta_keys=('img_path', 'ori_shape', 'img_shape', 'valid_ratio')) -] - -tta_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='TestTimeAug', - transforms=[ - [ - dict( - type='ConditionApply', - true_transforms=[ - dict( - type='ImgAugWrapper', - args=[dict(cls='Rot90', k=0, keep_size=False)]) - ], - condition="results['img_shape'][1] None: - if not 0. <= min_side_ratio <= 1.: - raise ValueError('`min_side_ratio` should be in range [0, 1],') - self.min_side_ratio = min_side_ratio - - def _sample_valid_start_end(self, valid_array: np.ndarray, min_len: int, - max_start_idx: int, - min_end_idx: int) -> Tuple[int, int]: - """Sample a start and end idx on a given axis that contains at least - one polygon. There should be at least one intact polygon bounded by - max_start_idx and min_end_idx. - - Args: - valid_array (ndarray): A 0-1 mask 1D array indicating valid regions - on the axis. 0 indicates text regions which are not allowed to - be sampled from. - min_len (int): Minimum distance between two start and end points. - max_start_idx (int): The maximum start index. - min_end_idx (int): The minimum end index. - - Returns: - tuple(int, int): Start and end index on a given axis, where - 0 <= start < max_start_idx and - min_end_idx <= end < len(valid_array). - """ - assert isinstance(min_len, int) - assert len(valid_array) > min_len - - start_array = valid_array.copy() - max_start_idx = min(len(start_array) - min_len, max_start_idx) - start_array[max_start_idx:] = 0 - start_array[0] = 1 - diff_array = np.hstack([0, start_array]) - np.hstack([start_array, 0]) - region_starts = np.where(diff_array < 0)[0] - region_ends = np.where(diff_array > 0)[0] - region_ind = np.random.randint(0, len(region_starts)) - start = np.random.randint(region_starts[region_ind], - region_ends[region_ind]) - - end_array = valid_array.copy() - min_end_idx = max(start + min_len, min_end_idx) - end_array[:min_end_idx] = 0 - end_array[-1] = 1 - diff_array = np.hstack([0, end_array]) - np.hstack([end_array, 0]) - region_starts = np.where(diff_array < 0)[0] - region_ends = np.where(diff_array > 0)[0] - region_ind = np.random.randint(0, len(region_starts)) - # Note that end index will never be region_ends[region_ind] - # and therefore end index is always in range [0, w+1] - end = np.random.randint(region_starts[region_ind], - region_ends[region_ind]) - return start, end - - def _sample_crop_box(self, img_size: Tuple[int, int], - results: Dict) -> np.ndarray: - """Generate crop box which only contains intact polygon instances with - the number >= 1. - - Args: - img_size (tuple(int, int)): The image size (h, w). - results (dict): The results dict. - - Returns: - ndarray: Crop area in shape (4, ). - """ - assert isinstance(img_size, tuple) - h, w = img_size[:2] - - # Crop box can be represented by any integer numbers in - # range [0, w] and [0, h] - x_valid_array = np.ones(w + 1, dtype=np.int32) - y_valid_array = np.ones(h + 1, dtype=np.int32) - - polygons = results['gt_polygons'] - - # Randomly select a polygon that must be inside - # the cropped region - kept_poly_idx = np.random.randint(0, len(polygons)) - for i, polygon in enumerate(polygons): - polygon = polygon.reshape((-1, 2)) - - clip_x = np.clip(polygon[:, 0], 0, w) - clip_y = np.clip(polygon[:, 1], 0, h) - min_x = np.floor(np.min(clip_x)).astype(np.int32) - min_y = np.floor(np.min(clip_y)).astype(np.int32) - max_x = np.ceil(np.max(clip_x)).astype(np.int32) - max_y = np.ceil(np.max(clip_y)).astype(np.int32) - - x_valid_array[min_x:max_x] = 0 - y_valid_array[min_y:max_y] = 0 - - if i == kept_poly_idx: - max_x_start = min_x - min_x_end = max_x - max_y_start = min_y - min_y_end = max_y - - min_w = int(w * self.min_side_ratio) - min_h = int(h * self.min_side_ratio) - - x1, x2 = self._sample_valid_start_end(x_valid_array, min_w, - max_x_start, min_x_end) - y1, y2 = self._sample_valid_start_end(y_valid_array, min_h, - max_y_start, min_y_end) - - return np.array([x1, y1, x2, y2]) - - def _crop_img(self, img: np.ndarray, bbox: np.ndarray) -> np.ndarray: - """Crop image given a bbox region. - Args: - img (ndarray): Image. - bbox (ndarray): Cropping region in shape (4, ) - - Returns: - ndarray: Cropped image. - """ - assert img.ndim == 3 - h, w, _ = img.shape - assert 0 <= bbox[1] < bbox[3] <= h - assert 0 <= bbox[0] < bbox[2] <= w - return img[bbox[1]:bbox[3], bbox[0]:bbox[2]] - - def transform(self, results: Dict) -> Dict: - """Applying random crop on results. - Args: - results (dict): Result dict contains the data to transform. - - Returns: - dict: The transformed data. - """ - if len(results['gt_polygons']) < 1: - return results - - crop_box = self._sample_crop_box(results['img'].shape, results) - img = self._crop_img(results['img'], crop_box) - results['img'] = img - results['img_shape'] = img.shape[:2] - crop_x = crop_box[0] - crop_y = crop_box[1] - crop_w = crop_box[2] - crop_box[0] - crop_h = crop_box[3] - crop_box[1] - - labels = results['gt_bboxes_labels'] - valid_labels = [] - ignored = results['gt_ignored'] - valid_ignored = [] - if 'gt_texts' in results: - valid_texts = [] - texts = results['gt_texts'] - - polys = results['gt_polygons'] - valid_polys = [] - for idx, poly in enumerate(polys): - poly = poly.reshape(-1, 2) - poly = (poly - (crop_x, crop_y)).flatten() - if is_poly_inside_rect(poly, [0, 0, crop_w, crop_h]): - valid_polys.append(poly) - valid_labels.append(labels[idx]) - valid_ignored.append(ignored[idx]) - if 'gt_texts' in results: - valid_texts.append(texts[idx]) - results['gt_polygons'] = valid_polys - results['gt_bboxes_labels'] = np.array(valid_labels, dtype=np.int64) - results['gt_ignored'] = np.array(valid_ignored, dtype=bool) - if 'gt_texts' in results: - results['gt_texts'] = valid_texts - valid_bboxes = [poly2bbox(poly) for poly in results['gt_polygons']] - results['gt_bboxes'] = np.array(valid_bboxes).astype( - np.float32).reshape(-1, 4) - - return results - - def __repr__(self) -> str: - repr_str = self.__class__.__name__ - repr_str += f'(min_side_ratio = {self.min_side_ratio})' - return repr_str - - -@TRANSFORMS.register_module() -class RandomRotate(BaseTransform): - """Randomly rotate the image, boxes, and polygons. For recognition task, - only the image will be rotated. If set ``use_canvas`` as True, the shape of - rotated image might be modified based on the rotated angle size, otherwise, - the image will keep the shape before rotation. - - Required Keys: - - - img - - img_shape - - gt_bboxes (optional) - - gt_polygons (optional) - - Modified Keys: - - - img - - img_shape (optional) - - gt_bboxes (optional) - - gt_polygons (optional) - - Added Keys: - - - rotated_angle - - Args: - max_angle (int): The maximum rotation angle (can be bigger than 180 or - a negative). Defaults to 10. - pad_with_fixed_color (bool): The flag for whether to pad rotated - image with fixed value. Defaults to False. - pad_value (tuple[int, int, int]): The color value for padding rotated - image. Defaults to (0, 0, 0). - use_canvas (bool): Whether to create a canvas for rotated image. - Defaults to False. If set true, the image shape may be modified. - """ - - def __init__( - self, - max_angle: int = 10, - pad_with_fixed_color: bool = False, - pad_value: Tuple[int, int, int] = (0, 0, 0), - use_canvas: bool = False, - ) -> None: - if not isinstance(max_angle, int): - raise TypeError('`max_angle` should be an integer' - f', but got {type(max_angle)} instead') - if not isinstance(pad_with_fixed_color, bool): - raise TypeError('`pad_with_fixed_color` should be a bool, ' - f'but got {type(pad_with_fixed_color)} instead') - if not isinstance(pad_value, (list, tuple)): - raise TypeError('`pad_value` should be a list or tuple, ' - f'but got {type(pad_value)} instead') - if len(pad_value) != 3: - raise ValueError('`pad_value` should contain three integers') - if not isinstance(pad_value[0], int) or not isinstance( - pad_value[1], int) or not isinstance(pad_value[2], int): - raise ValueError('`pad_value` should contain three integers') - - self.max_angle = max_angle - self.pad_with_fixed_color = pad_with_fixed_color - self.pad_value = pad_value - self.use_canvas = use_canvas - - @cache_randomness - def _sample_angle(self, max_angle: int) -> float: - """Sampling a random angle for rotation. - - Args: - max_angle (int): Maximum rotation angle - - Returns: - float: The random angle used for rotation - """ - angle = np.random.random_sample() * 2 * max_angle - max_angle - return angle - - @staticmethod - def _cal_canvas_size(ori_size: Tuple[int, int], - degree: int) -> Tuple[int, int]: - """Calculate the canvas size. - - Args: - ori_size (Tuple[int, int]): The original image size (height, width) - degree (int): The rotation angle - - Returns: - Tuple[int, int]: The size of the canvas - """ - assert isinstance(ori_size, tuple) - angle = degree * math.pi / 180.0 - h, w = ori_size[:2] - - cos = math.cos(angle) - sin = math.sin(angle) - canvas_h = int(w * math.fabs(sin) + h * math.fabs(cos)) - canvas_w = int(w * math.fabs(cos) + h * math.fabs(sin)) - - canvas_size = (canvas_h, canvas_w) - return canvas_size - - @staticmethod - def _rotate_points(center: Tuple[float, float], - points: np.array, - theta: float, - center_shift: Tuple[int, int] = (0, 0)) -> np.array: - """Rotating a set of points according to the given theta. - - Args: - center (Tuple[float, float]): The coordinate of the canvas center - points (np.array): A set of points needed to be rotated - theta (float): Rotation angle - center_shift (Tuple[int, int]): The shifting offset of the center - coordinate - - Returns: - np.array: The rotated coordinates of the input points - """ - (center_x, center_y) = center - center_y = -center_y - x, y = points[::2], points[1::2] - y = -y - - theta = theta / 180 * math.pi - cos = math.cos(theta) - sin = math.sin(theta) - - x = (x - center_x) - y = (y - center_y) - - _x = center_x + x * cos - y * sin + center_shift[0] - _y = -(center_y + x * sin + y * cos) + center_shift[1] - - points[::2], points[1::2] = _x, _y - return points - - def _rotate_img(self, results: Dict) -> Tuple[int, int]: - """Rotating the input image based on the given angle. - - Args: - results (dict): Result dict containing the data to transform. - - Returns: - Tuple[int, int]: The shifting offset of the center point. - """ - if results.get('img', None) is not None: - h = results['img'].shape[0] - w = results['img'].shape[1] - rotation_matrix = cv2.getRotationMatrix2D( - (w / 2, h / 2), results['rotated_angle'], 1) - - canvas_size = self._cal_canvas_size((h, w), - results['rotated_angle']) - center_shift = (int( - (canvas_size[1] - w) / 2), int((canvas_size[0] - h) / 2)) - rotation_matrix[0, 2] += int((canvas_size[1] - w) / 2) - rotation_matrix[1, 2] += int((canvas_size[0] - h) / 2) - if self.pad_with_fixed_color: - rotated_img = cv2.warpAffine( - results['img'], - rotation_matrix, (canvas_size[1], canvas_size[0]), - flags=cv2.INTER_NEAREST, - borderValue=self.pad_value) - else: - mask = np.zeros_like(results['img']) - (h_ind, w_ind) = (np.random.randint(0, h * 7 // 8), - np.random.randint(0, w * 7 // 8)) - img_cut = results['img'][h_ind:(h_ind + h // 9), - w_ind:(w_ind + w // 9)] - img_cut = mmcv.imresize(img_cut, - (canvas_size[1], canvas_size[0])) - mask = cv2.warpAffine( - mask, - rotation_matrix, (canvas_size[1], canvas_size[0]), - borderValue=[1, 1, 1]) - rotated_img = cv2.warpAffine( - results['img'], - rotation_matrix, (canvas_size[1], canvas_size[0]), - borderValue=[0, 0, 0]) - rotated_img = rotated_img + img_cut * mask - - results['img'] = rotated_img - else: - raise ValueError('`img` is not found in results') - - return center_shift - - def _rotate_bboxes(self, results: Dict, center_shift: Tuple[int, - int]) -> None: - """Rotating the bounding boxes based on the given angle. - - Args: - results (dict): Result dict containing the data to transform. - center_shift (Tuple[int, int]): The shifting offset of the - center point - """ - if results.get('gt_bboxes', None) is not None: - height, width = results['img_shape'] - box_list = [] - for box in results['gt_bboxes']: - rotated_box = self._rotate_points((width / 2, height / 2), - bbox2poly(box), - results['rotated_angle'], - center_shift) - rotated_box = poly2bbox(rotated_box) - box_list.append(rotated_box) - - results['gt_bboxes'] = np.array( - box_list, dtype=np.float32).reshape(-1, 4) - - def _rotate_polygons(self, results: Dict, - center_shift: Tuple[int, int]) -> None: - """Rotating the polygons based on the given angle. - - Args: - results (dict): Result dict containing the data to transform. - center_shift (Tuple[int, int]): The shifting offset of the - center point - """ - if results.get('gt_polygons', None) is not None: - height, width = results['img_shape'] - polygon_list = [] - for poly in results['gt_polygons']: - rotated_poly = self._rotate_points( - (width / 2, height / 2), poly, results['rotated_angle'], - center_shift) - polygon_list.append(rotated_poly) - results['gt_polygons'] = polygon_list - - def transform(self, results: Dict) -> Dict: - """Applying random rotate on results. - - Args: - results (Dict): Result dict containing the data to transform. - center_shift (Tuple[int, int]): The shifting offset of the - center point - - Returns: - dict: The transformed data - """ - # TODO rotate char_quads & char_rects for SegOCR - if self.use_canvas: - results['rotated_angle'] = self._sample_angle(self.max_angle) - # rotate image - center_shift = self._rotate_img(results) - # rotate gt_bboxes - self._rotate_bboxes(results, center_shift) - # rotate gt_polygons - self._rotate_polygons(results, center_shift) - - results['img_shape'] = (results['img'].shape[0], - results['img'].shape[1]) - else: - args = [ - dict( - cls='Affine', - rotate=[-self.max_angle, self.max_angle], - backend='cv2', - order=0) # order=0 -> cv2.INTER_NEAREST - ] - imgaug_transform = ImgAugWrapper(args) - results = imgaug_transform(results) - return results - - def __repr__(self) -> str: - repr_str = self.__class__.__name__ - repr_str += f'(max_angle = {self.max_angle}' - repr_str += f', pad_with_fixed_color = {self.pad_with_fixed_color}' - repr_str += f', pad_value = {self.pad_value}' - repr_str += f', use_canvas = {self.use_canvas})' - return repr_str - - -@TRANSFORMS.register_module() -class Resize(MMCV_Resize): - """Resize image & bboxes & polygons. - - This transform resizes the input image according to ``scale`` or - ``scale_factor``. Bboxes and polygons are then resized with the same - scale factor. if ``scale`` and ``scale_factor`` are both set, it will use - ``scale`` to resize. - - Required Keys: - - - img - - img_shape - - gt_bboxes - - gt_polygons - - - Modified Keys: - - - img - - img_shape - - gt_bboxes - - gt_polygons - - Added Keys: - - - scale - - scale_factor - - keep_ratio - - Args: - scale (int or tuple): Image scales for resizing. Defaults to None. - scale_factor (float or tuple[float, float]): Scale factors for - resizing. It's either a factor applicable to both dimensions or - in the form of (scale_w, scale_h). Defaults to None. - keep_ratio (bool): Whether to keep the aspect ratio when resizing the - image. Defaults to False. - clip_object_border (bool): Whether to clip the objects outside the - border of the image. Defaults to True. - backend (str): Image resize backend, choices are 'cv2' and 'pillow'. - These two backends generates slightly different results. Defaults - to 'cv2'. - interpolation (str): Interpolation method, accepted values are - "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' - backend, "nearest", "bilinear" for 'pillow' backend. Defaults - to 'bilinear'. - """ - - def _resize_img(self, results: dict) -> None: - """Resize images with ``results['scale']``. - - If no image is provided, only resize ``results['img_shape']``. - """ - if results.get('img', None) is not None: - return super()._resize_img(results) - h, w = results['img_shape'] - if self.keep_ratio: - new_w, new_h = mmcv.rescale_size((w, h), - results['scale'], - return_scale=False) - else: - new_w, new_h = results['scale'] - w_scale = new_w / w - h_scale = new_h / h - results['img_shape'] = (new_h, new_w) - results['scale'] = (new_w, new_h) - results['scale_factor'] = (w_scale, h_scale) - results['keep_ratio'] = self.keep_ratio - - def _resize_bboxes(self, results: dict) -> None: - """Resize bounding boxes.""" - super()._resize_bboxes(results) - if results.get('gt_bboxes', None) is not None: - results['gt_bboxes'] = results['gt_bboxes'].astype(np.float32) - - def _resize_polygons(self, results: dict) -> None: - """Resize polygons with ``results['scale_factor']``.""" - if results.get('gt_polygons', None) is not None: - polygons = results['gt_polygons'] - polygons_resize = [] - for idx, polygon in enumerate(polygons): - polygon = rescale_polygon(polygon, results['scale_factor']) - if self.clip_object_border: - crop_bbox = np.array([ - 0, 0, results['img_shape'][1], results['img_shape'][0] - ]) - polygon = crop_polygon(polygon, crop_bbox) - if polygon is not None: - polygons_resize.append(polygon.astype(np.float32)) - else: - polygons_resize.append( - np.zeros_like(polygons[idx], dtype=np.float32)) - results['gt_polygons'] = polygons_resize - - def transform(self, results: dict) -> dict: - """Transform function to resize images, bounding boxes and polygons. - - Args: - results (dict): Result dict from loading pipeline. - - Returns: - dict: Resized results, 'img', 'gt_bboxes', 'gt_polygons', - 'scale', 'scale_factor', 'height', 'width', and 'keep_ratio' keys - are updated in result dict. - """ - results = super().transform(results) - self._resize_polygons(results) - return results - - def __repr__(self): - repr_str = self.__class__.__name__ - repr_str += f'(scale={self.scale}, ' - repr_str += f'scale_factor={self.scale_factor}, ' - repr_str += f'keep_ratio={self.keep_ratio}, ' - repr_str += f'clip_object_border={self.clip_object_border}), ' - repr_str += f'backend={self.backend}), ' - repr_str += f'interpolation={self.interpolation})' - return repr_str - - -@TRANSFORMS.register_module() -class RemoveIgnored(BaseTransform): - """Removed ignored elements from the pipeline. - - Required Keys: - - - gt_ignored - - gt_polygons (optional) - - gt_bboxes (optional) - - gt_bboxes_labels (optional) - - gt_texts (optional) - - Modified Keys: - - - gt_ignored - - gt_polygons (optional) - - gt_bboxes (optional) - - gt_bboxes_labels (optional) - - gt_texts (optional) - """ - - def transform(self, results: Dict) -> Dict: - remove_inds = np.where(results['gt_ignored'])[0] - if len(remove_inds) == len(results['gt_ignored']): - return None - return remove_pipeline_elements(results, remove_inds) - - -@TRANSFORMS.register_module() -class FixInvalidPolygon(BaseTransform): - """Fix invalid polygons in the dataset. - - Required Keys: - - - gt_polygons - - gt_ignored (optional) - - gt_bboxes (optional) - - gt_bboxes_labels (optional) - - gt_texts (optional) - - Modified Keys: - - - gt_polygons - - gt_ignored (optional) - - gt_bboxes (optional) - - gt_bboxes_labels (optional) - - gt_texts (optional) - - Args: - mode (str): The mode of fixing invalid polygons. Options are 'fix' and - 'ignore'. - For the 'fix' mode, the transform will try to fix - the invalid polygons to a valid one by eliminating the - self-intersection or converting the bboxes to polygons. If - it can't be fixed by any means (e.g. the polygon contains less - than 3 points or it's actually a line/point), the annotation will - be removed. - For the 'ignore' mode, the invalid polygons - will be set to "ignored" during training. - Defaults to 'fix'. - min_poly_points (int): Minimum number of the coordinate points in a - polygon. Defaults to 4. - fix_from_bbox (bool): Whether to convert the bboxes to polygons when - the polygon is invalid and not directly fixable. Defaults to True. - """ - - def __init__(self, - mode: str = 'fix', - min_poly_points: int = 4, - fix_from_bbox: bool = True) -> None: - super().__init__() - self.mode = mode - assert min_poly_points >= 3, 'min_poly_points must be greater than 3.' - self.min_poly_points = min_poly_points - self.fix_from_bbox = fix_from_bbox - assert self.mode in [ - 'fix', 'ignore' - ], f"Supported modes are 'fix' and 'ignore', but got {self.mode}" - - def transform(self, results: Dict) -> Dict: - """Fix invalid polygons. - - Args: - results (dict): Result dict containing the data to transform. - - Returns: - Optional[dict]: The transformed data. If all the polygons are - unfixable, return None. - """ - if results.get('gt_polygons', None) is not None: - remove_inds = [] - for idx, polygon in enumerate(results['gt_polygons']): - if self.mode == 'ignore': - if results['gt_ignored'][idx]: - continue - if not (len(polygon) >= self.min_poly_points * 2 - and len(polygon) % 2 - == 0) or not poly2shapely(polygon).is_valid: - results['gt_ignored'][idx] = True - else: - # If "polygon" contains less than 3 points - if len(polygon) < 6: - remove_inds.append(idx) - continue - try: - shapely_polygon = poly2shapely(polygon) - if shapely_polygon.is_valid and len( - polygon) >= self.min_poly_points * 2: - continue - results['gt_polygons'][idx] = shapely2poly( - poly_make_valid(shapely_polygon)) - # If an empty polygon is generated, it's still a bad - # fix - if len(results['gt_polygons'][idx]) == 0: - raise ValueError - # It's hard to fix, e.g. the "polygon" is a line or - # a point - except Exception: - if self.fix_from_bbox and 'gt_bboxes' in results: - bbox = results['gt_bboxes'][idx] - bbox_polygon = bbox2poly(bbox) - results['gt_polygons'][idx] = bbox_polygon - shapely_polygon = poly2shapely(bbox_polygon) - if (not shapely_polygon.is_valid - or shapely_polygon.is_empty): - remove_inds.append(idx) - else: - remove_inds.append(idx) - if len(remove_inds) == len(results['gt_polygons']): - return None - results = remove_pipeline_elements(results, remove_inds) - return results - - def __repr__(self) -> str: - repr_str = self.__class__.__name__ - repr_str += f'(mode = "{self.mode}", ' - repr_str += f'min_poly_points = {self.min_poly_points}, ' - repr_str += f'fix_from_bbox = {self.fix_from_bbox})' - return repr_str diff --git a/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/backbones/mobilenet_v2.py b/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/backbones/mobilenet_v2.py deleted file mode 100644 index b0c671645f48773baa3df75a3ed868ca31c56a83..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/mmocr/models/textrecog/backbones/mobilenet_v2.py +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from typing import List - -import torch.nn as nn -from mmdet.models.backbones import MobileNetV2 as MMDet_MobileNetV2 -from torch import Tensor - -from mmocr.registry import MODELS -from mmocr.utils.typing_utils import InitConfigType - - -@MODELS.register_module() -class MobileNetV2(MMDet_MobileNetV2): - """See mmdet.models.backbones.MobileNetV2 for details. - - Args: - pooling_layers (list): List of indices of pooling layers. - init_cfg (InitConfigType, optional): Initialization config dict. - """ - # Parameters to build layers. 4 parameters are needed to construct a - # layer, from left to right: expand_ratio, channel, num_blocks, stride. - arch_settings = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 1], - [6, 64, 4, 1], [6, 96, 3, 1], [6, 160, 3, 1], - [6, 320, 1, 1]] - - def __init__(self, - pooling_layers: List = [3, 4, 5], - init_cfg: InitConfigType = None) -> None: - super().__init__(init_cfg=init_cfg) - self.pooling = nn.MaxPool2d((2, 2), (2, 1), (0, 1)) - self.pooling_layers = pooling_layers - - def forward(self, x: Tensor) -> Tensor: - """Forward function.""" - - x = self.conv1(x) - for i, layer_name in enumerate(self.layers): - layer = getattr(self, layer_name) - x = layer(x) - if i in self.pooling_layers: - x = self.pooling(x) - - return x diff --git a/spaces/Mysterykey/Mystery/Dockerfile b/spaces/Mysterykey/Mystery/Dockerfile deleted file mode 100644 index 4cb0ce42128d9a2ad33a395883f5e5455a38c707..0000000000000000000000000000000000000000 --- a/spaces/Mysterykey/Mystery/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM node:18-bullseye-slim -RUN apt-get update && \ - apt-get install -y git -RUN git clone https://gitgud.io/khanon/oai-reverse-proxy.git /app -WORKDIR /app -RUN npm install -COPY Dockerfile greeting.md* .env* ./ -RUN npm run build -EXPOSE 7860 -ENV NODE_ENV=production -CMD [ "npm", "start" ] \ No newline at end of file diff --git a/spaces/NATSpeech/PortaSpeech/modules/commons/rel_transformer.py b/spaces/NATSpeech/PortaSpeech/modules/commons/rel_transformer.py deleted file mode 100644 index 7e5b68b682be7ef0d1049015f0cd03d4e74f77d2..0000000000000000000000000000000000000000 --- a/spaces/NATSpeech/PortaSpeech/modules/commons/rel_transformer.py +++ /dev/null @@ -1,439 +0,0 @@ -import math -import torch -from torch import nn -from torch.nn import functional as F - -from modules.commons.layers import Embedding - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def shift_1d(x): - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] - return x - - -def sequence_mask(length, max_length=None): - if max_length is None: - max_length = length.max() - x = torch.arange(max_length, dtype=length.dtype, device=length.device) - return x.unsqueeze(0) < length.unsqueeze(1) - - -class Encoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., - window_size=None, block_length=None, pre_ln=False, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - self.block_length = block_length - self.pre_ln = pre_ln - - self.drop = nn.Dropout(p_dropout) - self.attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.attn_layers.append( - MultiHeadAttention(hidden_channels, hidden_channels, n_heads, window_size=window_size, - p_dropout=p_dropout, block_length=block_length)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append( - FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - if pre_ln: - self.last_ln = LayerNorm(hidden_channels) - - def forward(self, x, x_mask): - attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - for i in range(self.n_layers): - x = x * x_mask - x_ = x - if self.pre_ln: - x = self.norm_layers_1[i](x) - y = self.attn_layers[i](x, x, attn_mask) - y = self.drop(y) - x = x_ + y - if not self.pre_ln: - x = self.norm_layers_1[i](x) - - x_ = x - if self.pre_ln: - x = self.norm_layers_2[i](x) - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = x_ + y - if not self.pre_ln: - x = self.norm_layers_2[i](x) - if self.pre_ln: - x = self.last_ln(x) - x = x * x_mask - return x - - -class MultiHeadAttention(nn.Module): - def __init__(self, channels, out_channels, n_heads, window_size=None, heads_share=True, p_dropout=0., - block_length=None, proximal_bias=False, proximal_init=False): - super().__init__() - assert channels % n_heads == 0 - - self.channels = channels - self.out_channels = out_channels - self.n_heads = n_heads - self.window_size = window_size - self.heads_share = heads_share - self.block_length = block_length - self.proximal_bias = proximal_bias - self.p_dropout = p_dropout - self.attn = None - - self.k_channels = channels // n_heads - self.conv_q = nn.Conv1d(channels, channels, 1) - self.conv_k = nn.Conv1d(channels, channels, 1) - self.conv_v = nn.Conv1d(channels, channels, 1) - if window_size is not None: - n_heads_rel = 1 if heads_share else n_heads - rel_stddev = self.k_channels ** -0.5 - self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - self.conv_o = nn.Conv1d(channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - nn.init.xavier_uniform_(self.conv_q.weight) - nn.init.xavier_uniform_(self.conv_k.weight) - if proximal_init: - self.conv_k.weight.data.copy_(self.conv_q.weight.data) - self.conv_k.bias.data.copy_(self.conv_q.bias.data) - nn.init.xavier_uniform_(self.conv_v.weight) - - def forward(self, x, c, attn_mask=None): - q = self.conv_q(x) - k = self.conv_k(c) - v = self.conv_v(c) - - x, self.attn = self.attention(q, k, v, mask=attn_mask) - - x = self.conv_o(x) - return x - - def attention(self, query, key, value, mask=None): - # reshape [b, d, t] -> [b, n_h, t, d_k] - b, d, t_s, t_t = (*key.size(), query.size(2)) - query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3) - key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - - scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.k_channels) - if self.window_size is not None: - assert t_s == t_t, "Relative attention is only available for self-attention." - key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s) - rel_logits = self._matmul_with_relative_keys(query, key_relative_embeddings) - rel_logits = self._relative_position_to_absolute_position(rel_logits) - scores_local = rel_logits / math.sqrt(self.k_channels) - scores = scores + scores_local - if self.proximal_bias: - assert t_s == t_t, "Proximal bias is only available for self-attention." - scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype) - if mask is not None: - scores = scores.masked_fill(mask == 0, -1e4) - if self.block_length is not None: - block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length) - scores = scores * block_mask + -1e4 * (1 - block_mask) - p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s] - p_attn = self.drop(p_attn) - output = torch.matmul(p_attn, value) - if self.window_size is not None: - relative_weights = self._absolute_position_to_relative_position(p_attn) - value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s) - output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings) - output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t] - return output, p_attn - - def _matmul_with_relative_values(self, x, y): - """ - x: [b, h, l, m] - y: [h or 1, m, d] - ret: [b, h, l, d] - """ - ret = torch.matmul(x, y.unsqueeze(0)) - return ret - - def _matmul_with_relative_keys(self, x, y): - """ - x: [b, h, l, d] - y: [h or 1, m, d] - ret: [b, h, l, m] - """ - ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) - return ret - - def _get_relative_embeddings(self, relative_embeddings, length): - max_relative_position = 2 * self.window_size + 1 - # Pad first before slice to avoid using cond ops. - pad_length = max(length - (self.window_size + 1), 0) - slice_start_position = max((self.window_size + 1) - length, 0) - slice_end_position = slice_start_position + 2 * length - 1 - if pad_length > 0: - padded_relative_embeddings = F.pad( - relative_embeddings, - convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]])) - else: - padded_relative_embeddings = relative_embeddings - used_relative_embeddings = padded_relative_embeddings[:, slice_start_position:slice_end_position] - return used_relative_embeddings - - def _relative_position_to_absolute_position(self, x): - """ - x: [b, h, l, 2*l-1] - ret: [b, h, l, l] - """ - batch, heads, length, _ = x.size() - # Concat columns of pad to shift from relative to absolute indexing. - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]])) - - # Concat extra elements so to add up to shape (len+1, 2*len-1). - x_flat = x.view([batch, heads, length * 2 * length]) - x_flat = F.pad(x_flat, convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])) - - # Reshape and slice out the padded elements. - x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[:, :, :length, length - 1:] - return x_final - - def _absolute_position_to_relative_position(self, x): - """ - x: [b, h, l, l] - ret: [b, h, l, 2*l-1] - """ - batch, heads, length, _ = x.size() - # padd along column - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])) - x_flat = x.view([batch, heads, length ** 2 + length * (length - 1)]) - # add 0's in the beginning that will skew the elements after reshape - x_flat = F.pad(x_flat, convert_pad_shape([[0, 0], [0, 0], [length, 0]])) - x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:] - return x_final - - def _attention_bias_proximal(self, length): - """Bias for self-attention to encourage attention to close positions. - Args: - length: an integer scalar. - Returns: - a Tensor with shape [1, 1, length, length] - """ - r = torch.arange(length, dtype=torch.float32) - diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) - return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0) - - -class FFN(nn.Module): - def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.activation = activation - - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2) - self.conv_2 = nn.Conv1d(filter_channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - def forward(self, x, x_mask): - x = self.conv_1(x * x_mask) - if self.activation == "gelu": - x = x * torch.sigmoid(1.702 * x) - else: - x = torch.relu(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - return x * x_mask - - -class LayerNorm(nn.Module): - def __init__(self, channels, eps=1e-4): - super().__init__() - self.channels = channels - self.eps = eps - - self.gamma = nn.Parameter(torch.ones(channels)) - self.beta = nn.Parameter(torch.zeros(channels)) - - def forward(self, x): - n_dims = len(x.shape) - mean = torch.mean(x, 1, keepdim=True) - variance = torch.mean((x - mean) ** 2, 1, keepdim=True) - - x = (x - mean) * torch.rsqrt(variance + self.eps) - - shape = [1, -1] + [1] * (n_dims - 2) - x = x * self.gamma.view(*shape) + self.beta.view(*shape) - return x - - -class ConvReluNorm(nn.Module): - def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout): - super().__init__() - self.in_channels = in_channels - self.hidden_channels = hidden_channels - self.out_channels = out_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.p_dropout = p_dropout - assert n_layers > 1, "Number of layers should be larger than 0." - - self.conv_layers = nn.ModuleList() - self.norm_layers = nn.ModuleList() - self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size // 2)) - self.norm_layers.append(LayerNorm(hidden_channels)) - self.relu_drop = nn.Sequential( - nn.ReLU(), - nn.Dropout(p_dropout)) - for _ in range(n_layers - 1): - self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size // 2)) - self.norm_layers.append(LayerNorm(hidden_channels)) - self.proj = nn.Conv1d(hidden_channels, out_channels, 1) - self.proj.weight.data.zero_() - self.proj.bias.data.zero_() - - def forward(self, x, x_mask): - x_org = x - for i in range(self.n_layers): - x = self.conv_layers[i](x * x_mask) - x = self.norm_layers[i](x) - x = self.relu_drop(x) - x = x_org + self.proj(x) - return x * x_mask - - -class RelTransformerEncoder(nn.Module): - def __init__(self, - n_vocab, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - window_size=4, - block_length=None, - prenet=True, - pre_ln=True, - ): - - super().__init__() - - self.n_vocab = n_vocab - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - self.block_length = block_length - self.prenet = prenet - self.emb = Embedding(n_vocab, hidden_channels, padding_idx=0) - - if prenet: - self.pre = ConvReluNorm(hidden_channels, hidden_channels, hidden_channels, - kernel_size=5, n_layers=3, p_dropout=0) - self.encoder = Encoder( - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - window_size=window_size, - block_length=block_length, - pre_ln=pre_ln, - ) - - def forward(self, x, x_mask=None): - if self.n_vocab > 0: - x_lengths = (x > 0).long().sum(-1) - x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h] - else: - x_lengths = (x.abs().sum(-1) > 0).long().sum(-1) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - - if self.prenet: - x = self.pre(x, x_mask) - x = self.encoder(x, x_mask) - return x.transpose(1, 2) - - -class RelTransformerEncoder(nn.Module): - def __init__(self, - n_vocab, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout=0.0, - window_size=4, - block_length=None, - prenet=True, - pre_ln=True, - ): - - super().__init__() - - self.n_vocab = n_vocab - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - self.block_length = block_length - self.prenet = prenet - if n_vocab > 0: - self.emb = Embedding(n_vocab, hidden_channels, padding_idx=0) - - if prenet: - self.pre = ConvReluNorm(hidden_channels, hidden_channels, hidden_channels, - kernel_size=5, n_layers=3, p_dropout=0) - self.encoder = Encoder( - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - window_size=window_size, - block_length=block_length, - pre_ln=pre_ln, - ) - - def forward(self, x, x_mask=None): - if self.n_vocab > 0: - x_lengths = (x > 0).long().sum(-1) - x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h] - else: - x_lengths = (x.abs().sum(-1) > 0).long().sum(-1) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - - if self.prenet: - x = self.pre(x, x_mask) - x = self.encoder(x, x_mask) - return x.transpose(1, 2) diff --git a/spaces/NATSpeech/PortaSpeech/utils/os_utils.py b/spaces/NATSpeech/PortaSpeech/utils/os_utils.py deleted file mode 100644 index 4567d17c398c535884600cdd86a36a823acb886f..0000000000000000000000000000000000000000 --- a/spaces/NATSpeech/PortaSpeech/utils/os_utils.py +++ /dev/null @@ -1,20 +0,0 @@ -import os -import subprocess - - -def link_file(from_file, to_file): - subprocess.check_call( - f'ln -s "`realpath --relative-to="{os.path.dirname(to_file)}" "{from_file}"`" "{to_file}"', shell=True) - - -def move_file(from_file, to_file): - subprocess.check_call(f'mv "{from_file}" "{to_file}"', shell=True) - - -def copy_file(from_file, to_file): - subprocess.check_call(f'cp -r "{from_file}" "{to_file}"', shell=True) - - -def remove_file(*fns): - for f in fns: - subprocess.check_call(f'rm -rf "{f}"', shell=True) diff --git a/spaces/NCTCMumbai/NCTC/models/official/nlp/transformer/optimizer.py b/spaces/NCTCMumbai/NCTC/models/official/nlp/transformer/optimizer.py deleted file mode 100644 index 176b5eb8c6ffcea8a9bccbad5fbdef1d2106e106..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/official/nlp/transformer/optimizer.py +++ /dev/null @@ -1,137 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== -"""Optimizer from addons and learning rate scheduler.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import numpy as np -import tensorflow as tf -K = tf.keras.backend - - -class LearningRateSchedule(tf.keras.optimizers.schedules.LearningRateSchedule): - """Learning rate schedule.""" - - def __init__(self, initial_learning_rate, hidden_size, warmup_steps): - """Initialize configuration of the learning rate schedule. - - Args: - initial_learning_rate: A float, the initial learning rate. - hidden_size: An integer, the model dimension in the hidden layers. - warmup_steps: An integer, the number of steps required for linear warmup. - """ - super(LearningRateSchedule, self).__init__() - self.initial_learning_rate = initial_learning_rate - self.hidden_size = hidden_size - self.warmup_steps = tf.cast(warmup_steps, tf.float32) - - def __call__(self, global_step): - """Calculate learning rate with linear warmup and rsqrt decay. - - Args: - global_step: An integer, the current global step used for learning rate - calculation. - - Returns: - A float, the learning rate needs to be used for current global step. - """ - with tf.name_scope('learning_rate_schedule'): - global_step = tf.cast(global_step, tf.float32) - learning_rate = self.initial_learning_rate - learning_rate *= (self.hidden_size**-0.5) - # Apply linear warmup - learning_rate *= tf.minimum(1.0, global_step / self.warmup_steps) - # Apply rsqrt decay - learning_rate /= tf.sqrt(tf.maximum(global_step, self.warmup_steps)) - return learning_rate - - def get_config(self): - """Get the configuration of the learning rate schedule.""" - return { - 'initial_learning_rate': self.initial_learning_rate, - 'hidden_size': self.hidden_size, - 'warmup_steps': self.warmup_steps, - } - - -class LearningRateFn(object): - """Creates learning rate function.""" - - def __init__(self, learning_rate, hidden_size, warmup_steps): - self.learning_rate = learning_rate - self.hidden_size = hidden_size - self.warmup_steps = float(warmup_steps) - - def __call__(self, global_step): - """Calculate learning rate with linear warmup and rsqrt decay.""" - step = float(global_step) - learning_rate = self.learning_rate - learning_rate *= (self.hidden_size ** -0.5) - # Apply linear warmup - learning_rate *= np.minimum(1.0, step / self.warmup_steps) - # Apply rsqrt decay - learning_rate /= np.sqrt(np.maximum(step, self.warmup_steps)) - return learning_rate - - -class LearningRateScheduler(tf.keras.callbacks.Callback): - """Keras callback to schedule learning rate. - - TODO(tianlin): Refactor this scheduler and LearningRateBatchScheduler in - official/resnet/keras/keras_common.py. - """ - - def __init__(self, schedule, init_steps=None, verbose=False): - super(LearningRateScheduler, self).__init__() - self.schedule = schedule - self.verbose = verbose - if init_steps is None: - init_steps = 0.0 - self.steps = float(init_steps) # Total steps during training. - - def on_epoch_begin(self, epoch, logs=None): - if not hasattr(self.model.optimizer, 'lr'): - raise ValueError('Optimizer must have a "lr" attribute.') - if not hasattr(self.model.optimizer, 'iterations'): - raise ValueError('Optimizer must have a "iterations" attribute.') - - def on_train_batch_begin(self, batch, logs=None): - """Adjusts learning rate for each train batch.""" - if self.verbose > 0: - iterations = K.get_value(self.model.optimizer.iterations) - print('Original iteration %d' % iterations) - - self.steps += 1.0 - try: # new API - lr = float(K.get_value(self.model.optimizer.lr)) - lr = self.schedule(self.steps, lr) - except TypeError: # Support for old API for backward compatibility - lr = self.schedule(self.steps) - if not isinstance(lr, (float, np.float32, np.float64)): - raise ValueError('The output of the "schedule" function ' - 'should be float.') - K.set_value(self.model.optimizer.lr, lr) - K.set_value(self.model.optimizer.iterations, self.steps) - - if self.verbose > 0: - print('Batch %05d Step %05d: LearningRateScheduler setting learning ' - 'rate to %s.' % (batch + 1, self.steps, lr)) - - def on_epoch_end(self, epoch, logs=None): - logs = logs or {} - logs['lr'] = K.get_value(self.model.optimizer.lr) - logs['steps'] = self.steps diff --git a/spaces/NCTCMumbai/NCTC/models/official/vision/detection/modeling/architecture/__init__.py b/spaces/NCTCMumbai/NCTC/models/official/vision/detection/modeling/architecture/__init__.py deleted file mode 100644 index 931c2ef11db4a949e6c2e95bca44e36bac1241e9..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/official/vision/detection/modeling/architecture/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright 2019 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================== diff --git a/spaces/NLPark/Misteln-Schariac/README.md b/spaces/NLPark/Misteln-Schariac/README.md deleted file mode 100644 index c0d4f2c6d9144356ca1202dc5544496ce2364d3e..0000000000000000000000000000000000000000 --- a/spaces/NLPark/Misteln-Schariac/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cecilia -emoji: 🐠 -colorFrom: blue -colorTo: purple -sdk: gradio -sdk_version: 3.50.2 -app_file: app.py -pinned: true -license: apache-2.0 -models: - - Cran-May/OpenSLIDE ---- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/multilingual/data_scripts/download_ML50_v1.sh b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/multilingual/data_scripts/download_ML50_v1.sh deleted file mode 100644 index 99fbc75920836a4b4bbdbd6b523749843288e450..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/multilingual/data_scripts/download_ML50_v1.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash -# Copyright (c) Facebook, Inc. and its 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. - -if [ -z $WORKDIR_ROOT ] ; -then - echo "please specify your working directory root in environment variable WORKDIR_ROOT. Exitting..." - exit -fi - -# first run download_wmt20.sh; it will install a few useful tools for other scripts -# TODO: need to print out instructions on downloading a few files which requires manually authentication from the websites -bash ./download_wmt20.sh - -python ./download_wmt19_and_before.py -bash ./download_wat19_my.sh -python ./download_ted_and_extract.py -bash ./download_lotus.sh -bash ./download_iitb.sh -bash ./download_af_xh.sh - - -# IWSLT downloading URLs have changed in between; TODO: fix them: -bash ./download_iwslt_and_extract.sh - -# TODO: globalvoices URLs changed; need to be fixed -bash ./download_flores_data.sh diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/add_target_dataset.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/add_target_dataset.py deleted file mode 100644 index d8a08e746dedb8a5d9d9e4b9ad149e0da469d644..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/data/add_target_dataset.py +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import torch - -from . import BaseWrapperDataset, data_utils -from fairseq.data.text_compressor import TextCompressor, TextCompressionLevel - - -class AddTargetDataset(BaseWrapperDataset): - def __init__( - self, - dataset, - labels, - pad, - eos, - batch_targets, - process_label=None, - label_len_fn=None, - add_to_input=False, - text_compression_level=TextCompressionLevel.none - ): - super().__init__(dataset) - self.labels = labels - self.batch_targets = batch_targets - self.pad = pad - self.eos = eos - self.process_label = process_label - self.label_len_fn = label_len_fn - self.add_to_input = add_to_input - self.text_compressor = TextCompressor(level=text_compression_level) - - def get_label(self, index, process_fn=None): - lbl = self.labels[index] - lbl = self.text_compressor.decompress(lbl) - return lbl if process_fn is None else process_fn(lbl) - - def __getitem__(self, index): - item = self.dataset[index] - item["label"] = self.get_label(index, process_fn=self.process_label) - return item - - def size(self, index): - sz = self.dataset.size(index) - own_sz = self.label_len_fn(self.get_label(index)) - return sz, own_sz - - def collater(self, samples): - collated = self.dataset.collater(samples) - if len(collated) == 0: - return collated - indices = set(collated["id"].tolist()) - target = [s["label"] for s in samples if s["id"] in indices] - - if self.batch_targets: - collated["target_lengths"] = torch.LongTensor([len(t) for t in target]) - target = data_utils.collate_tokens(target, pad_idx=self.pad, left_pad=False) - collated["ntokens"] = collated["target_lengths"].sum().item() - else: - collated["ntokens"] = sum([len(t) for t in target]) - - collated["target"] = target - - if self.add_to_input: - eos = target.new_full((target.size(0), 1), self.eos) - collated["target"] = torch.cat([target, eos], dim=-1).long() - collated["net_input"]["prev_output_tokens"] = torch.cat( - [eos, target], dim=-1 - ).long() - collated["ntokens"] += target.size(0) - return collated - - def filter_indices_by_size(self, indices, max_sizes): - indices, ignored = data_utils._filter_by_size_dynamic( - indices, self.size, max_sizes - ) - return indices, ignored diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/chrf.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/chrf.py deleted file mode 100644 index 0d6cb77383a44d9ac739958b79a30764f1fbf7f3..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/chrf.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from fairseq.scoring import BaseScorer, register_scorer - - -@register_scorer("chrf") -class ChrFScorer(BaseScorer): - def __init__(self, args): - super(ChrFScorer, self).__init__(args) - import sacrebleu - - self.sacrebleu = sacrebleu - - def add_string(self, ref, pred): - self.ref.append(ref) - self.pred.append(pred) - - def score(self, order=4): - return self.result_string(order).score - - def result_string(self, order=4): - if order != 4: - raise NotImplementedError - return self.sacrebleu.corpus_chrf(self.pred, [self.ref]).format() diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/wer.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/wer.py deleted file mode 100644 index 633dc47c247691c4c9e36cbdbab7d7cb74b38452..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/scoring/wer.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from dataclasses import dataclass, field - -from fairseq.dataclass import FairseqDataclass -from fairseq.scoring import BaseScorer, register_scorer -from fairseq.scoring.tokenizer import EvaluationTokenizer - - -@dataclass -class WerScorerConfig(FairseqDataclass): - wer_tokenizer: EvaluationTokenizer.ALL_TOKENIZER_TYPES = field( - default="none", metadata={"help": "sacreBLEU tokenizer to use for evaluation"} - ) - wer_remove_punct: bool = field( - default=False, metadata={"help": "remove punctuation"} - ) - wer_char_level: bool = field( - default=False, metadata={"help": "evaluate at character level"} - ) - wer_lowercase: bool = field(default=False, metadata={"help": "lowercasing"}) - - -@register_scorer("wer", dataclass=WerScorerConfig) -class WerScorer(BaseScorer): - def __init__(self, cfg): - super().__init__(cfg) - self.reset() - try: - import editdistance as ed - except ImportError: - raise ImportError("Please install editdistance to use WER scorer") - self.ed = ed - self.tokenizer = EvaluationTokenizer( - tokenizer_type=self.cfg.wer_tokenizer, - lowercase=self.cfg.wer_lowercase, - punctuation_removal=self.cfg.wer_remove_punct, - character_tokenization=self.cfg.wer_char_level, - ) - - def reset(self): - self.distance = 0 - self.ref_length = 0 - - def add_string(self, ref, pred): - ref_items = self.tokenizer.tokenize(ref).split() - pred_items = self.tokenizer.tokenize(pred).split() - self.distance += self.ed.eval(ref_items, pred_items) - self.ref_length += len(ref_items) - - def result_string(self): - return f"WER: {self.score():.2f}" - - def score(self): - return 100.0 * self.distance / self.ref_length if self.ref_length > 0 else 0 diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/tasks/translation_from_pretrained_xlm.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/tasks/translation_from_pretrained_xlm.py deleted file mode 100644 index a05f2891524a8b23482e206c1742c3b816b77afb..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/fairseq/tasks/translation_from_pretrained_xlm.py +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from dataclasses import dataclass -from fairseq.data.legacy.masked_lm_dictionary import MaskedLMDictionary -from fairseq.tasks.translation import TranslationConfig, TranslationTask - -from . import register_task - - -@dataclass -class TranslationFromPretrainedXLMConfig(TranslationConfig): - pass - - -@register_task( - "translation_from_pretrained_xlm", dataclass=TranslationFromPretrainedXLMConfig -) -class TranslationFromPretrainedXLMTask(TranslationTask): - """ - Same as TranslationTask except use the MaskedLMDictionary class so that - we can load data that was binarized with the MaskedLMDictionary class. - - This task should be used for the entire training pipeline when we want to - train an NMT model from a pretrained XLM checkpoint: binarizing NMT data, - training NMT with the pretrained XLM checkpoint, and subsequent evaluation - of that trained model. - """ - - @classmethod - def load_dictionary(cls, filename): - """Load the masked LM dictionary from the filename - - Args: - filename (str): the filename - """ - return MaskedLMDictionary.load(filename) diff --git a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/hubert/simple_kmeans/dump_w2v2_feature.py b/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/hubert/simple_kmeans/dump_w2v2_feature.py deleted file mode 100644 index a1f0d902acf0756580a1f4604feee8fc499a9a63..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/examples/hubert/simple_kmeans/dump_w2v2_feature.py +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import logging -import os -import sys - -import fairseq -import soundfile as sf -import torch -import torch.nn.functional as F - -from feature_utils import get_path_iterator, dump_feature - - -logging.basicConfig( - format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - level=os.environ.get("LOGLEVEL", "INFO").upper(), - stream=sys.stdout, -) -logger = logging.getLogger("dump_w2v2_feature") - - -class Wav2Vec2FeatureReader(object): - def __init__(self, ckpt_path, layer, max_chunk=1600000): - ( - model, - cfg, - task, - ) = fairseq.checkpoint_utils.load_model_ensemble_and_task([ckpt_path]) - self.model = model[0].eval().cuda() - self.task = task - self.layer = layer # assume this is 1-based like HuBERT - self.max_chunk = max_chunk - logger.info(f"TASK CONFIG:\n{self.task.cfg}") - logger.info(f" max_chunk = {self.max_chunk}") - logger.info(f" model:\n{self.model}") - - def read_audio(self, path, ref_len=None): - wav, sr = sf.read(path) - assert sr == self.task.cfg.sample_rate, sr - if wav.ndim == 2: - wav = wav.mean(-1) - assert wav.ndim == 1, wav.ndim - if ref_len is not None and abs(ref_len - len(wav)) > 160: - logging.warning(f"ref {ref_len} != read {len(wav)} ({path})") - return wav - - def get_feats(self, path, ref_len=None): - x = self.read_audio(path, ref_len) - with torch.no_grad(): - x = torch.from_numpy(x).float().cuda() - if self.task.cfg.normalize: - x = F.layer_norm(x, x.shape) - x = x.view(1, -1) - - feat = [] - for start in range(0, x.size(1), self.max_chunk): - x_chunk = x[:, start: start + self.max_chunk] - res = self.model.extract_features( - source=x_chunk, - padding_mask=None, - mask=False, - layer=self.layer - 1, - ) - feat_chunk = res["x"] - feat.append(feat_chunk) - return torch.cat(feat, 1).squeeze(0) - - -def main(tsv_dir, split, ckpt_path, layer, nshard, rank, feat_dir, max_chunk): - reader = Wav2Vec2FeatureReader(ckpt_path, layer, max_chunk) - generator, num = get_path_iterator(f"{tsv_dir}/{split}.tsv", nshard, rank) - dump_feature(reader, generator, num, split, nshard, rank, feat_dir) - - -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("tsv_dir") - parser.add_argument("split") - parser.add_argument("ckpt_path") - parser.add_argument("layer", type=int) - parser.add_argument("nshard", type=int) - parser.add_argument("rank", type=int) - parser.add_argument("feat_dir") - parser.add_argument("--max_chunk", type=int, default=1600000) - args = parser.parse_args() - logger.info(args) - - main(**vars(args)) diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/simultaneous_translation/modules/fixed_pre_decision.py b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/simultaneous_translation/modules/fixed_pre_decision.py deleted file mode 100644 index 3991414aed3800f301e4097e819d3064bb549c37..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/simultaneous_translation/modules/fixed_pre_decision.py +++ /dev/null @@ -1,190 +0,0 @@ -from functools import partial - -import torch -from torch import Tensor -import math -import torch.nn.functional as F - -from . import register_monotonic_attention -from .monotonic_multihead_attention import ( - MonotonicAttention, - MonotonicInfiniteLookbackAttention, - WaitKAttention -) -from typing import Dict, Optional - - -def fixed_pooling_monotonic_attention(monotonic_attention): - def create_model(monotonic_attention, klass): - class FixedStrideMonotonicAttention(monotonic_attention): - def __init__(self, args): - self.waitk_lagging = 0 - self.num_heads = 0 - self.noise_mean = 0.0 - self.noise_var = 0.0 - super().__init__(args) - self.pre_decision_type = args.fixed_pre_decision_type - self.pre_decision_ratio = args.fixed_pre_decision_ratio - self.pre_decision_pad_threshold = args.fixed_pre_decision_pad_threshold - assert self.pre_decision_ratio > 1 - - if args.fixed_pre_decision_type == "average": - self.pooling_layer = torch.nn.AvgPool1d( - kernel_size=self.pre_decision_ratio, - stride=self.pre_decision_ratio, - ceil_mode=True, - ) - elif args.fixed_pre_decision_type == "last": - - def last(key): - if key.size(2) < self.pre_decision_ratio: - return key - else: - k = key[ - :, - :, - self.pre_decision_ratio - 1:: self.pre_decision_ratio, - ].contiguous() - if key.size(-1) % self.pre_decision_ratio != 0: - k = torch.cat([k, key[:, :, -1:]], dim=-1).contiguous() - return k - - self.pooling_layer = last - else: - raise NotImplementedError - - @staticmethod - def add_args(parser): - super( - FixedStrideMonotonicAttention, FixedStrideMonotonicAttention - ).add_args(parser) - parser.add_argument( - "--fixed-pre-decision-ratio", - type=int, - required=True, - help=( - "Ratio for the fixed pre-decision," - "indicating how many encoder steps will start" - "simultaneous decision making process." - ), - ) - parser.add_argument( - "--fixed-pre-decision-type", - default="average", - choices=["average", "last"], - help="Pooling type", - ) - parser.add_argument( - "--fixed-pre-decision-pad-threshold", - type=float, - default=0.3, - help="If a part of the sequence has pad" - ",the threshold the pooled part is a pad.", - ) - - def insert_zeros(self, x): - bsz_num_heads, tgt_len, src_len = x.size() - stride = self.pre_decision_ratio - weight = F.pad(torch.ones(1, 1, 1).to(x), (stride - 1, 0)) - x_upsample = F.conv_transpose1d( - x.view(-1, src_len).unsqueeze(1), - weight, - stride=stride, - padding=0, - ) - return x_upsample.squeeze(1).view(bsz_num_heads, tgt_len, -1) - - def p_choose( - self, - query: Optional[Tensor], - key: Optional[Tensor], - key_padding_mask: Optional[Tensor] = None, - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - ): - assert key is not None - assert query is not None - src_len = key.size(0) - tgt_len = query.size(0) - batch_size = query.size(1) - - key_pool = self.pooling_layer(key.transpose(0, 2)).transpose(0, 2) - - if key_padding_mask is not None: - key_padding_mask_pool = ( - self.pooling_layer(key_padding_mask.unsqueeze(0).float()) - .squeeze(0) - .gt(self.pre_decision_pad_threshold) - ) - # Make sure at least one element is not pad - key_padding_mask_pool[:, 0] = 0 - else: - key_padding_mask_pool = None - - if incremental_state is not None: - # The floor instead of ceil is used for inference - # But make sure the length key_pool at least 1 - if ( - max(1, math.floor(key.size(0) / self.pre_decision_ratio)) - ) < key_pool.size(0): - key_pool = key_pool[:-1] - if key_padding_mask_pool is not None: - key_padding_mask_pool = key_padding_mask_pool[:-1] - - p_choose_pooled = self.p_choose_from_qk( - query, - key_pool, - key_padding_mask_pool, - incremental_state=incremental_state, - ) - - # Upsample, interpolate zeros - p_choose = self.insert_zeros(p_choose_pooled) - - if p_choose.size(-1) < src_len: - # Append zeros if the upsampled p_choose is shorter than src_len - p_choose = torch.cat( - [ - p_choose, - torch.zeros( - p_choose.size(0), - tgt_len, - src_len - p_choose.size(-1) - ).to(p_choose) - ], - dim=2 - ) - else: - # can be larger than src_len because we used ceil before - p_choose = p_choose[:, :, :src_len] - p_choose[:, :, -1] = p_choose_pooled[:, :, -1] - - assert list(p_choose.size()) == [ - batch_size * self.num_heads, - tgt_len, - src_len, - ] - - return p_choose - - FixedStrideMonotonicAttention.__name__ = klass.__name__ - return FixedStrideMonotonicAttention - - return partial(create_model, monotonic_attention) - - -@register_monotonic_attention("waitk_fixed_pre_decision") -@fixed_pooling_monotonic_attention(WaitKAttention) -class WaitKAttentionFixedStride: - pass - - -@register_monotonic_attention("hard_aligned_fixed_pre_decision") -@fixed_pooling_monotonic_attention(MonotonicAttention) -class MonotonicAttentionFixedStride: - pass - - -@register_monotonic_attention("infinite_lookback_fixed_pre_decision") -@fixed_pooling_monotonic_attention(MonotonicInfiniteLookbackAttention) -class MonotonicInfiniteLookbackAttentionFixedStride: - pass diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/stft.py b/spaces/OFA-Sys/OFA-vqa/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/stft.py deleted file mode 100644 index 63fcd431e2d7746b696aaa0d4172bc04ffb88efa..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/stft.py +++ /dev/null @@ -1,141 +0,0 @@ -""" -BSD 3-Clause License - -Copyright (c) 2017, Prem Seetharaman -All rights reserved. - -* Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -* Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -""" - -import torch -import numpy as np -import torch.nn.functional as F -from torch.autograd import Variable -from scipy.signal import get_window -from librosa.util import pad_center, tiny -from .audio_processing import window_sumsquare - - -class STFT(torch.nn.Module): - """adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft""" - def __init__(self, filter_length=800, hop_length=200, win_length=800, - window='hann'): - super(STFT, self).__init__() - self.filter_length = filter_length - self.hop_length = hop_length - self.win_length = win_length - self.window = window - self.forward_transform = None - scale = self.filter_length / self.hop_length - fourier_basis = np.fft.fft(np.eye(self.filter_length)) - - cutoff = int((self.filter_length / 2 + 1)) - fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]), - np.imag(fourier_basis[:cutoff, :])]) - - forward_basis = torch.FloatTensor(fourier_basis[:, None, :]) - inverse_basis = torch.FloatTensor( - np.linalg.pinv(scale * fourier_basis).T[:, None, :]) - - if window is not None: - assert(filter_length >= win_length) - # get window and zero center pad it to filter_length - fft_window = get_window(window, win_length, fftbins=True) - fft_window = pad_center(fft_window, filter_length) - fft_window = torch.from_numpy(fft_window).float() - - # window the bases - forward_basis *= fft_window - inverse_basis *= fft_window - - self.register_buffer('forward_basis', forward_basis.float()) - self.register_buffer('inverse_basis', inverse_basis.float()) - - def transform(self, input_data): - num_batches = input_data.size(0) - num_samples = input_data.size(1) - - self.num_samples = num_samples - - # similar to librosa, reflect-pad the input - input_data = input_data.view(num_batches, 1, num_samples) - input_data = F.pad( - input_data.unsqueeze(1), - (int(self.filter_length / 2), int(self.filter_length / 2), 0, 0), - mode='reflect') - input_data = input_data.squeeze(1) - - forward_transform = F.conv1d( - input_data, - Variable(self.forward_basis, requires_grad=False), - stride=self.hop_length, - padding=0) - - cutoff = int((self.filter_length / 2) + 1) - real_part = forward_transform[:, :cutoff, :] - imag_part = forward_transform[:, cutoff:, :] - - magnitude = torch.sqrt(real_part**2 + imag_part**2) - phase = torch.autograd.Variable( - torch.atan2(imag_part.data, real_part.data)) - - return magnitude, phase - - def inverse(self, magnitude, phase): - recombine_magnitude_phase = torch.cat( - [magnitude*torch.cos(phase), magnitude*torch.sin(phase)], dim=1) - - inverse_transform = F.conv_transpose1d( - recombine_magnitude_phase, - Variable(self.inverse_basis, requires_grad=False), - stride=self.hop_length, - padding=0) - - if self.window is not None: - window_sum = window_sumsquare( - self.window, magnitude.size(-1), hop_length=self.hop_length, - win_length=self.win_length, n_fft=self.filter_length, - dtype=np.float32) - # remove modulation effects - approx_nonzero_indices = torch.from_numpy( - np.where(window_sum > tiny(window_sum))[0]) - window_sum = torch.autograd.Variable( - torch.from_numpy(window_sum), requires_grad=False) - window_sum = window_sum.cuda() if magnitude.is_cuda else window_sum - inverse_transform[:, :, approx_nonzero_indices] /= window_sum[approx_nonzero_indices] - - # scale by hop ratio - inverse_transform *= float(self.filter_length) / self.hop_length - - inverse_transform = inverse_transform[:, :, int(self.filter_length/2):] - inverse_transform = inverse_transform[:, :, :-int(self.filter_length/2):] - - return inverse_transform - - def forward(self, input_data): - self.magnitude, self.phase = self.transform(input_data) - reconstruction = self.inverse(self.magnitude, self.phase) - return reconstruction diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/binarizer.py b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/binarizer.py deleted file mode 100644 index ae4d02a6dbbb523b76eb8684e87e38c74fe7c4a1..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/binarizer.py +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from collections import Counter -from typing import Dict - -import torch - -from fairseq.file_chunker_utils import Chunker -from fairseq.file_io import PathManager -from fairseq.tokenizer import tokenize_line - - -class Binarizer: - @staticmethod - def binarize( - filename, - dict, - consumer, - tokenize=tokenize_line, - append_eos=True, - reverse_order=False, - offset=0, - end=-1, - already_numberized=False, - ) -> Dict[str, int]: - nseq, ntok = 0, 0 - replaced = Counter() - - def replaced_consumer(word, idx): - if idx == dict.unk_index and word != dict.unk_word: - replaced.update([word]) - - with Chunker( - PathManager.get_local_path(filename), offset, end - ) as line_iterator: - for line in line_iterator: - if already_numberized: - id_strings = line.strip().split() - id_list = [int(id_string) for id_string in id_strings] - if reverse_order: - id_list.reverse() - if append_eos: - id_list.append(dict.eos()) - ids = torch.IntTensor(id_list) - else: - ids = dict.encode_line( - line=line, - line_tokenizer=tokenize, - add_if_not_exist=False, - consumer=replaced_consumer, - append_eos=append_eos, - reverse_order=reverse_order, - ) - nseq += 1 - ntok += len(ids) - consumer(ids) - return { - "nseq": nseq, - "nunk": sum(replaced.values()), - "ntok": ntok, - "replaced": replaced, - } - - @staticmethod - def binarize_alignments( - filename, alignment_parser, consumer, offset=0, end=-1 - ) -> Dict[str, int]: - nseq = 0 - - with Chunker( - PathManager.get_local_path(filename), offset, end - ) as line_iterator: - for line in line_iterator: - ids = alignment_parser(line) - nseq += 1 - consumer(ids) - return {"nseq": nseq} diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/models/bart/__init__.py b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/models/bart/__init__.py deleted file mode 100644 index a701923f7e5a2a8aa9b75e5580ddea22907f53ee..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq/models/bart/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from .hub_interface import * # noqa -from .model import * # noqa diff --git a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq_cli/eval_lm.py b/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq_cli/eval_lm.py deleted file mode 100644 index ab6e77029ef738291efd190b1cfe2435dd403dea..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-vqa/fairseq/fairseq_cli/eval_lm.py +++ /dev/null @@ -1,347 +0,0 @@ -#!/usr/bin/env python3 -u -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -""" -Evaluate the perplexity of a trained language model. -""" - -import logging -import math -import os -import sys -from argparse import Namespace -from typing import Iterable, List, Optional - -import torch -import fairseq -from fairseq import checkpoint_utils, distributed_utils, options, tasks, utils -from fairseq.dataclass.utils import convert_namespace_to_omegaconf -from fairseq.logging import progress_bar -from fairseq.logging.meters import StopwatchMeter -from fairseq.sequence_scorer import SequenceScorer -from omegaconf import DictConfig - - -logging.basicConfig( - format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - level=os.environ.get("LOGLEVEL", "INFO").upper(), - stream=sys.stdout, -) -logger = logging.getLogger("fairseq_cli.eval_lm") - - -def eval_lm( - models: List[fairseq.models.FairseqModel], - source_dictionary: fairseq.data.Dictionary, - batch_iterator: Iterable, - post_process: Optional[str] = None, - output_word_probs: bool = False, - output_word_stats: bool = False, - target_dictionary: Optional[fairseq.data.Dictionary] = None, - softmax_batch: int = 0, - remove_bos_token: bool = False, - device: Optional[torch.device] = None, -): - """ - Args: - models (List[~fairseq.models.FairseqModel]): list of models to - evaluate. Models are essentially `nn.Module` instances, but - must be compatible with fairseq's `SequenceScorer`. - source_dictionary (~fairseq.data.Dictionary): dictionary for - applying any relevant post processing or outputing word - probs/stats. - batch_iterator (Iterable): yield batches of data - post_process (Optional[str]): post-process text by removing BPE, - letter segmentation, etc. Valid options can be found in - fairseq.data.utils.post_process, although not all options - are implemented here. - output_word_probs (Optional[bool]): output words and their - predicted log probabilities - output_word_stats (Optional[bool]): output word statistics such - as word count and average probability - target_dictionary (Optional[~fairseq.data.Dictionary]): output - dictionary (defaults to *source_dictionary*) - softmax_batch (Optional[bool]): if BxT is more than this, will - batch the softmax over vocab to this amount of tokens, in - order to fit into GPU memory - remove_bos_token (Optional[bool]): if True, confirm that the - first token is the beginning-of-sentence symbol (according - to the relevant dictionary) and remove it from the output - device (Optional[torch.device]): device to use for evaluation - (defaults to device of first model parameter) - """ - if target_dictionary is None: - target_dictionary = source_dictionary - if device is None: - device = next(models[0].parameters()).device - - gen_timer = StopwatchMeter() - scorer = SequenceScorer(target_dictionary, softmax_batch) - - score_sum = 0.0 - count = 0 - - if post_process is not None: - if post_process in {"subword_nmt", "@@ "}: - bpe_cont = post_process.rstrip() - bpe_toks = { - i - for i in range(len(source_dictionary)) - if source_dictionary[i].endswith(bpe_cont) - } - else: - raise NotImplementedError( - "--post-process={post_process} is not implemented" - ) - bpe_len = len(bpe_cont) - else: - bpe_toks = None - bpe_len = 0 - - word_stats = dict() - - for sample in batch_iterator: - if "net_input" not in sample: - continue - - sample = utils.move_to_cuda(sample, device=device) - - gen_timer.start() - hypos = scorer.generate(models, sample) - gen_timer.stop(sample["ntokens"]) - - for i, hypos_i in enumerate(hypos): - hypo = hypos_i[0] - sample_id = sample["id"][i] - - tokens = hypo["tokens"] - tgt_len = tokens.numel() - pos_scores = hypo["positional_scores"].float() - - if remove_bos_token: - assert hypo["tokens"][0].item() == target_dictionary.bos() - tokens = tokens[1:] - pos_scores = pos_scores[1:] - - skipped_toks = 0 - if bpe_toks is not None: - for i in range(tgt_len - 1): - if tokens[i].item() in bpe_toks: - skipped_toks += 1 - pos_scores[i + 1] += pos_scores[i] - pos_scores[i] = 0 - - inf_scores = pos_scores.eq(float("inf")) | pos_scores.eq(float("-inf")) - if inf_scores.any(): - logger.info( - "skipping tokens with inf scores:", - target_dictionary.string(tokens[inf_scores.nonzero()]), - ) - pos_scores = pos_scores[(~inf_scores).nonzero()] - score_sum += pos_scores.sum().cpu() - count += pos_scores.numel() - skipped_toks - - if output_word_probs or output_word_stats: - w = "" - word_prob = [] - is_bpe = False - for i in range(len(tokens)): - w_ind = tokens[i].item() - w += source_dictionary[w_ind] - if bpe_toks is not None and w_ind in bpe_toks: - w = w[:-bpe_len] - is_bpe = True - else: - word_prob.append((w, pos_scores[i].item())) - - next_prob = None - ind = i + 1 - while ind < len(tokens): - if pos_scores[ind].item() != 0: - next_prob = pos_scores[ind] - break - ind += 1 - - word_stats.setdefault(w, WordStat(w, is_bpe)).add( - pos_scores[i].item(), next_prob - ) - is_bpe = False - w = "" - if output_word_probs: - logger.info( - str(int(sample_id)) - + " " - + ( - "\t".join( - "{} [{:2f}]".format(x[0], x[1]) for x in word_prob - ) - ) - ) - - avg_nll_loss = ( - -score_sum / count / math.log(2) if count > 0 else 0 - ) # convert to base 2 - logger.info( - "Evaluated {:,} tokens in {:.1f}s ({:.2f} tokens/s)".format( - gen_timer.n, gen_timer.sum, 1.0 / gen_timer.avg if gen_timer.avg > 0 else 0 - ) - ) - - if output_word_stats: - for ws in sorted(word_stats.values(), key=lambda x: x.count, reverse=True): - logger.info(ws) - - return { - "loss": avg_nll_loss, - "perplexity": 2 ** avg_nll_loss, - } - - -class WordStat(object): - def __init__(self, word, is_bpe): - self.word = word - self.is_bpe = is_bpe - self.log_prob = 0 - self.next_word_prob = 0 - self.count = 0 - self.missing_next_words = 0 - - def add(self, log_prob, next_word_prob): - """increments counters for the sum of log probs of current word and next - word (given context ending at current word). Since the next word might be at the end of the example, - or it might be not counted because it is not an ending subword unit, - also keeps track of how many of those we have seen""" - if next_word_prob is not None: - self.next_word_prob += next_word_prob - else: - self.missing_next_words += 1 - self.log_prob += log_prob - self.count += 1 - - def __str__(self): - return "{}\t{}\t{}\t{}\t{}\t{}".format( - self.word, - self.count, - self.log_prob, - self.is_bpe, - self.next_word_prob, - self.count - self.missing_next_words, - ) - - -def main(cfg: DictConfig, **unused_kwargs): - if isinstance(cfg, Namespace): - cfg = convert_namespace_to_omegaconf(cfg) - - utils.import_user_module(cfg.common) - - logger.info(cfg) - - if cfg.eval_lm.context_window > 0: - # reduce tokens per sample by the required context window size - cfg.task.tokens_per_sample -= cfg.eval_lm.context_window - - # Initialize the task using the current *cfg* - task = tasks.setup_task(cfg.task) - - # Load ensemble - logger.info("loading model(s) from {}".format(cfg.common_eval.path)) - models, model_args, task = checkpoint_utils.load_model_ensemble_and_task( - [cfg.common_eval.path], - arg_overrides=eval(cfg.common_eval.model_overrides), - suffix=cfg.checkpoint.checkpoint_suffix, - strict=(cfg.checkpoint.checkpoint_shard_count == 1), - num_shards=cfg.checkpoint.checkpoint_shard_count, - task=task, - ) - - use_fp16 = cfg.common.fp16 - use_cuda = torch.cuda.is_available() and not cfg.common.cpu - if use_cuda: - torch.cuda.set_device(cfg.distributed_training.device_id) - - # Optimize ensemble for generation and set the source and dest dicts on the model - # (required by scorer) - for model in models: - if use_fp16: - model.half() - if use_cuda and not cfg.distributed_training.pipeline_model_parallel: - model.cuda() - model.prepare_for_inference_(cfg) - - assert len(models) > 0 - - logger.info( - "num. model params: {:,}".format(sum(p.numel() for p in models[0].parameters())) - ) - - # Load dataset splits - task.load_dataset(cfg.dataset.gen_subset) - dataset = task.dataset(cfg.dataset.gen_subset) - logger.info( - "{} {} {:,} examples".format( - cfg.task.data, cfg.dataset.gen_subset, len(dataset) - ) - ) - - itr = task.eval_lm_dataloader( - dataset=dataset, - max_tokens=cfg.dataset.max_tokens or 36000, - batch_size=cfg.dataset.batch_size, - max_positions=utils.resolve_max_positions( - *[model.max_positions() for model in models] - ), - num_shards=max( - cfg.dataset.num_shards, - cfg.distributed_training.distributed_world_size, - ), - shard_id=max( - cfg.dataset.shard_id, - cfg.distributed_training.distributed_rank, - ), - num_workers=cfg.dataset.num_workers, - data_buffer_size=cfg.dataset.data_buffer_size, - context_window=cfg.eval_lm.context_window, - ) - - itr = progress_bar.progress_bar( - itr, - log_format=cfg.common.log_format, - log_interval=cfg.common.log_interval, - default_log_format=("tqdm" if not cfg.common.no_progress_bar else "simple"), - ) - - results = eval_lm( - models=models, - source_dictionary=task.source_dictionary, - batch_iterator=itr, - post_process=cfg.common_eval.post_process, - output_word_probs=cfg.eval_lm.output_word_probs, - output_word_stats=cfg.eval_lm.output_word_stats, - target_dictionary=task.target_dictionary, - softmax_batch=cfg.eval_lm.softmax_batch, - remove_bos_token=getattr(cfg.task, "add_bos_token", False), - ) - - logger.info( - "Loss (base 2): {:.4f}, Perplexity: {:.2f}".format( - results["loss"], results["perplexity"] - ) - ) - - return results - - -def cli_main(): - parser = options.get_eval_lm_parser() - args = options.parse_args_and_arch(parser) - - distributed_utils.call_main(convert_namespace_to_omegaconf(args), main) - - -if __name__ == "__main__": - cli_main() diff --git a/spaces/OIUGLK/bingo/src/pages/api/image.ts b/spaces/OIUGLK/bingo/src/pages/api/image.ts deleted file mode 100644 index 4b894bea86050c0f3888cc56f60c0cb7f8b57cfc..0000000000000000000000000000000000000000 --- a/spaces/OIUGLK/bingo/src/pages/api/image.ts +++ /dev/null @@ -1,40 +0,0 @@ -'use server' - -import { NextApiRequest, NextApiResponse } from 'next' -import { debug } from '@/lib/isomorphic' -import { createHeaders } from '@/lib/utils' -import { createImage } from '@/lib/bots/bing/utils' - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - const { prompt, id } = req.query - if (!prompt) { - return res.json({ - result: { - value: 'Image', - message: 'No Prompt' - } - }) - } - try { - const headers = createHeaders(req.cookies, { - IMAGE_BING_COOKIE: process.env.IMAGE_BING_COOKIE - }) - - debug('headers', headers) - const response = await createImage(String(prompt), String(id), { - ...headers, - 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32', - }) - res.writeHead(200, { - 'Content-Type': 'text/plain; charset=UTF-8', - }) - return res.end(response) - } catch (e) { - return res.json({ - result: { - value: 'Error', - message: `${e}` - } - }) - } -} diff --git a/spaces/OpenMotionLab/MotionGPT/mGPT/data/humanml/common/quaternion.py b/spaces/OpenMotionLab/MotionGPT/mGPT/data/humanml/common/quaternion.py deleted file mode 100644 index dca3d890080a4e91e3f275f442b0aed006562881..0000000000000000000000000000000000000000 --- a/spaces/OpenMotionLab/MotionGPT/mGPT/data/humanml/common/quaternion.py +++ /dev/null @@ -1,423 +0,0 @@ -# Copyright (c) 2018-present, Facebook, Inc. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. -# - -import torch -import numpy as np - -_EPS4 = np.finfo(float).eps * 4.0 - -_FLOAT_EPS = np.finfo(np.float64).eps - -# PyTorch-backed implementations -def qinv(q): - assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)' - mask = torch.ones_like(q) - mask[..., 1:] = -mask[..., 1:] - return q * mask - - -def qinv_np(q): - assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)' - return qinv(torch.from_numpy(q).float()).numpy() - - -def qnormalize(q): - assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)' - return q / torch.norm(q, dim=-1, keepdim=True) - - -def qmul(q, r): - """ - Multiply quaternion(s) q with quaternion(s) r. - Expects two equally-sized tensors of shape (*, 4), where * denotes any number of dimensions. - Returns q*r as a tensor of shape (*, 4). - """ - assert q.shape[-1] == 4 - assert r.shape[-1] == 4 - - original_shape = q.shape - - # Compute outer product - terms = torch.bmm(r.view(-1, 4, 1), q.view(-1, 1, 4)) - - w = terms[:, 0, 0] - terms[:, 1, 1] - terms[:, 2, 2] - terms[:, 3, 3] - x = terms[:, 0, 1] + terms[:, 1, 0] - terms[:, 2, 3] + terms[:, 3, 2] - y = terms[:, 0, 2] + terms[:, 1, 3] + terms[:, 2, 0] - terms[:, 3, 1] - z = terms[:, 0, 3] - terms[:, 1, 2] + terms[:, 2, 1] + terms[:, 3, 0] - return torch.stack((w, x, y, z), dim=1).view(original_shape) - - -def qrot(q, v): - """ - Rotate vector(s) v about the rotation described by quaternion(s) q. - Expects a tensor of shape (*, 4) for q and a tensor of shape (*, 3) for v, - where * denotes any number of dimensions. - Returns a tensor of shape (*, 3). - """ - assert q.shape[-1] == 4 - assert v.shape[-1] == 3 - assert q.shape[:-1] == v.shape[:-1] - - original_shape = list(v.shape) - # print(q.shape) - q = q.contiguous().view(-1, 4) - v = v.contiguous().view(-1, 3) - - qvec = q[:, 1:] - uv = torch.cross(qvec, v, dim=1) - uuv = torch.cross(qvec, uv, dim=1) - return (v + 2 * (q[:, :1] * uv + uuv)).view(original_shape) - - -def qeuler(q, order, epsilon=0, deg=True): - """ - Convert quaternion(s) q to Euler angles. - Expects a tensor of shape (*, 4), where * denotes any number of dimensions. - Returns a tensor of shape (*, 3). - """ - assert q.shape[-1] == 4 - - original_shape = list(q.shape) - original_shape[-1] = 3 - q = q.view(-1, 4) - - q0 = q[:, 0] - q1 = q[:, 1] - q2 = q[:, 2] - q3 = q[:, 3] - - if order == 'xyz': - x = torch.atan2(2 * (q0 * q1 - q2 * q3), 1 - 2 * (q1 * q1 + q2 * q2)) - y = torch.asin(torch.clamp(2 * (q1 * q3 + q0 * q2), -1 + epsilon, 1 - epsilon)) - z = torch.atan2(2 * (q0 * q3 - q1 * q2), 1 - 2 * (q2 * q2 + q3 * q3)) - elif order == 'yzx': - x = torch.atan2(2 * (q0 * q1 - q2 * q3), 1 - 2 * (q1 * q1 + q3 * q3)) - y = torch.atan2(2 * (q0 * q2 - q1 * q3), 1 - 2 * (q2 * q2 + q3 * q3)) - z = torch.asin(torch.clamp(2 * (q1 * q2 + q0 * q3), -1 + epsilon, 1 - epsilon)) - elif order == 'zxy': - x = torch.asin(torch.clamp(2 * (q0 * q1 + q2 * q3), -1 + epsilon, 1 - epsilon)) - y = torch.atan2(2 * (q0 * q2 - q1 * q3), 1 - 2 * (q1 * q1 + q2 * q2)) - z = torch.atan2(2 * (q0 * q3 - q1 * q2), 1 - 2 * (q1 * q1 + q3 * q3)) - elif order == 'xzy': - x = torch.atan2(2 * (q0 * q1 + q2 * q3), 1 - 2 * (q1 * q1 + q3 * q3)) - y = torch.atan2(2 * (q0 * q2 + q1 * q3), 1 - 2 * (q2 * q2 + q3 * q3)) - z = torch.asin(torch.clamp(2 * (q0 * q3 - q1 * q2), -1 + epsilon, 1 - epsilon)) - elif order == 'yxz': - x = torch.asin(torch.clamp(2 * (q0 * q1 - q2 * q3), -1 + epsilon, 1 - epsilon)) - y = torch.atan2(2 * (q1 * q3 + q0 * q2), 1 - 2 * (q1 * q1 + q2 * q2)) - z = torch.atan2(2 * (q1 * q2 + q0 * q3), 1 - 2 * (q1 * q1 + q3 * q3)) - elif order == 'zyx': - x = torch.atan2(2 * (q0 * q1 + q2 * q3), 1 - 2 * (q1 * q1 + q2 * q2)) - y = torch.asin(torch.clamp(2 * (q0 * q2 - q1 * q3), -1 + epsilon, 1 - epsilon)) - z = torch.atan2(2 * (q0 * q3 + q1 * q2), 1 - 2 * (q2 * q2 + q3 * q3)) - else: - raise - - if deg: - return torch.stack((x, y, z), dim=1).view(original_shape) * 180 / np.pi - else: - return torch.stack((x, y, z), dim=1).view(original_shape) - - -# Numpy-backed implementations - -def qmul_np(q, r): - q = torch.from_numpy(q).contiguous().float() - r = torch.from_numpy(r).contiguous().float() - return qmul(q, r).numpy() - - -def qrot_np(q, v): - q = torch.from_numpy(q).contiguous().float() - v = torch.from_numpy(v).contiguous().float() - return qrot(q, v).numpy() - - -def qeuler_np(q, order, epsilon=0, use_gpu=False): - if use_gpu: - q = torch.from_numpy(q).cuda().float() - return qeuler(q, order, epsilon).cpu().numpy() - else: - q = torch.from_numpy(q).contiguous().float() - return qeuler(q, order, epsilon).numpy() - - -def qfix(q): - """ - Enforce quaternion continuity across the time dimension by selecting - the representation (q or -q) with minimal distance (or, equivalently, maximal dot product) - between two consecutive frames. - - Expects a tensor of shape (L, J, 4), where L is the sequence length and J is the number of joints. - Returns a tensor of the same shape. - """ - assert len(q.shape) == 3 - assert q.shape[-1] == 4 - - result = q.copy() - dot_products = np.sum(q[1:] * q[:-1], axis=2) - mask = dot_products < 0 - mask = (np.cumsum(mask, axis=0) % 2).astype(bool) - result[1:][mask] *= -1 - return result - - -def euler2quat(e, order, deg=True): - """ - Convert Euler angles to quaternions. - """ - assert e.shape[-1] == 3 - - original_shape = list(e.shape) - original_shape[-1] = 4 - - e = e.view(-1, 3) - - ## if euler angles in degrees - if deg: - e = e * np.pi / 180. - - x = e[:, 0] - y = e[:, 1] - z = e[:, 2] - - rx = torch.stack((torch.cos(x / 2), torch.sin(x / 2), torch.zeros_like(x), torch.zeros_like(x)), dim=1) - ry = torch.stack((torch.cos(y / 2), torch.zeros_like(y), torch.sin(y / 2), torch.zeros_like(y)), dim=1) - rz = torch.stack((torch.cos(z / 2), torch.zeros_like(z), torch.zeros_like(z), torch.sin(z / 2)), dim=1) - - result = None - for coord in order: - if coord == 'x': - r = rx - elif coord == 'y': - r = ry - elif coord == 'z': - r = rz - else: - raise - if result is None: - result = r - else: - result = qmul(result, r) - - # Reverse antipodal representation to have a non-negative "w" - if order in ['xyz', 'yzx', 'zxy']: - result *= -1 - - return result.view(original_shape) - - -def expmap_to_quaternion(e): - """ - Convert axis-angle rotations (aka exponential maps) to quaternions. - Stable formula from "Practical Parameterization of Rotations Using the Exponential Map". - Expects a tensor of shape (*, 3), where * denotes any number of dimensions. - Returns a tensor of shape (*, 4). - """ - assert e.shape[-1] == 3 - - original_shape = list(e.shape) - original_shape[-1] = 4 - e = e.reshape(-1, 3) - - theta = np.linalg.norm(e, axis=1).reshape(-1, 1) - w = np.cos(0.5 * theta).reshape(-1, 1) - xyz = 0.5 * np.sinc(0.5 * theta / np.pi) * e - return np.concatenate((w, xyz), axis=1).reshape(original_shape) - - -def euler_to_quaternion(e, order): - """ - Convert Euler angles to quaternions. - """ - assert e.shape[-1] == 3 - - original_shape = list(e.shape) - original_shape[-1] = 4 - - e = e.reshape(-1, 3) - - x = e[:, 0] - y = e[:, 1] - z = e[:, 2] - - rx = np.stack((np.cos(x / 2), np.sin(x / 2), np.zeros_like(x), np.zeros_like(x)), axis=1) - ry = np.stack((np.cos(y / 2), np.zeros_like(y), np.sin(y / 2), np.zeros_like(y)), axis=1) - rz = np.stack((np.cos(z / 2), np.zeros_like(z), np.zeros_like(z), np.sin(z / 2)), axis=1) - - result = None - for coord in order: - if coord == 'x': - r = rx - elif coord == 'y': - r = ry - elif coord == 'z': - r = rz - else: - raise - if result is None: - result = r - else: - result = qmul_np(result, r) - - # Reverse antipodal representation to have a non-negative "w" - if order in ['xyz', 'yzx', 'zxy']: - result *= -1 - - return result.reshape(original_shape) - - -def quaternion_to_matrix(quaternions): - """ - Convert rotations given as quaternions to rotation matrices. - Args: - quaternions: quaternions with real part first, - as tensor of shape (..., 4). - Returns: - Rotation matrices as tensor of shape (..., 3, 3). - """ - r, i, j, k = torch.unbind(quaternions, -1) - two_s = 2.0 / (quaternions * quaternions).sum(-1) - - o = torch.stack( - ( - 1 - two_s * (j * j + k * k), - two_s * (i * j - k * r), - two_s * (i * k + j * r), - two_s * (i * j + k * r), - 1 - two_s * (i * i + k * k), - two_s * (j * k - i * r), - two_s * (i * k - j * r), - two_s * (j * k + i * r), - 1 - two_s * (i * i + j * j), - ), - -1, - ) - return o.reshape(quaternions.shape[:-1] + (3, 3)) - - -def quaternion_to_matrix_np(quaternions): - q = torch.from_numpy(quaternions).contiguous().float() - return quaternion_to_matrix(q).numpy() - - -def quaternion_to_cont6d_np(quaternions): - rotation_mat = quaternion_to_matrix_np(quaternions) - cont_6d = np.concatenate([rotation_mat[..., 0], rotation_mat[..., 1]], axis=-1) - return cont_6d - - -def quaternion_to_cont6d(quaternions): - rotation_mat = quaternion_to_matrix(quaternions) - cont_6d = torch.cat([rotation_mat[..., 0], rotation_mat[..., 1]], dim=-1) - return cont_6d - - -def cont6d_to_matrix(cont6d): - assert cont6d.shape[-1] == 6, "The last dimension must be 6" - x_raw = cont6d[..., 0:3] - y_raw = cont6d[..., 3:6] - - x = x_raw / torch.norm(x_raw, dim=-1, keepdim=True) - z = torch.cross(x, y_raw, dim=-1) - z = z / torch.norm(z, dim=-1, keepdim=True) - - y = torch.cross(z, x, dim=-1) - - x = x[..., None] - y = y[..., None] - z = z[..., None] - - mat = torch.cat([x, y, z], dim=-1) - return mat - - -def cont6d_to_matrix_np(cont6d): - q = torch.from_numpy(cont6d).contiguous().float() - return cont6d_to_matrix(q).numpy() - - -def qpow(q0, t, dtype=torch.float): - ''' q0 : tensor of quaternions - t: tensor of powers - ''' - q0 = qnormalize(q0) - theta0 = torch.acos(q0[..., 0]) - - ## if theta0 is close to zero, add epsilon to avoid NaNs - mask = (theta0 <= 10e-10) * (theta0 >= -10e-10) - theta0 = (1 - mask) * theta0 + mask * 10e-10 - v0 = q0[..., 1:] / torch.sin(theta0).view(-1, 1) - - if isinstance(t, torch.Tensor): - q = torch.zeros(t.shape + q0.shape) - theta = t.view(-1, 1) * theta0.view(1, -1) - else: ## if t is a number - q = torch.zeros(q0.shape) - theta = t * theta0 - - q[..., 0] = torch.cos(theta) - q[..., 1:] = v0 * torch.sin(theta).unsqueeze(-1) - - return q.to(dtype) - - -def qslerp(q0, q1, t): - ''' - q0: starting quaternion - q1: ending quaternion - t: array of points along the way - - Returns: - Tensor of Slerps: t.shape + q0.shape - ''' - - q0 = qnormalize(q0) - q1 = qnormalize(q1) - q_ = qpow(qmul(q1, qinv(q0)), t) - - return qmul(q_, - q0.contiguous().view(torch.Size([1] * len(t.shape)) + q0.shape).expand(t.shape + q0.shape).contiguous()) - - -def qbetween(v0, v1): - ''' - find the quaternion used to rotate v0 to v1 - ''' - assert v0.shape[-1] == 3, 'v0 must be of the shape (*, 3)' - assert v1.shape[-1] == 3, 'v1 must be of the shape (*, 3)' - - v = torch.cross(v0, v1) - w = torch.sqrt((v0 ** 2).sum(dim=-1, keepdim=True) * (v1 ** 2).sum(dim=-1, keepdim=True)) + (v0 * v1).sum(dim=-1, - keepdim=True) - return qnormalize(torch.cat([w, v], dim=-1)) - - -def qbetween_np(v0, v1): - ''' - find the quaternion used to rotate v0 to v1 - ''' - assert v0.shape[-1] == 3, 'v0 must be of the shape (*, 3)' - assert v1.shape[-1] == 3, 'v1 must be of the shape (*, 3)' - - v0 = torch.from_numpy(v0).float() - v1 = torch.from_numpy(v1).float() - return qbetween(v0, v1).numpy() - - -def lerp(p0, p1, t): - if not isinstance(t, torch.Tensor): - t = torch.Tensor([t]) - - new_shape = t.shape + p0.shape - new_view_t = t.shape + torch.Size([1] * len(p0.shape)) - new_view_p = torch.Size([1] * len(t.shape)) + p0.shape - p0 = p0.view(new_view_p).expand(new_shape) - p1 = p1.view(new_view_p).expand(new_shape) - t = t.view(new_view_t).expand(new_shape) - - return p0 + t * (p1 - p0) diff --git a/spaces/PAIR/PAIR-Diffusion/ldm/modules/midas/midas/dpt_depth.py b/spaces/PAIR/PAIR-Diffusion/ldm/modules/midas/midas/dpt_depth.py deleted file mode 100644 index 4e9aab5d2767dffea39da5b3f30e2798688216f1..0000000000000000000000000000000000000000 --- a/spaces/PAIR/PAIR-Diffusion/ldm/modules/midas/midas/dpt_depth.py +++ /dev/null @@ -1,109 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F - -from .base_model import BaseModel -from .blocks import ( - FeatureFusionBlock, - FeatureFusionBlock_custom, - Interpolate, - _make_encoder, - forward_vit, -) - - -def _make_fusion_block(features, use_bn): - return FeatureFusionBlock_custom( - features, - nn.ReLU(False), - deconv=False, - bn=use_bn, - expand=False, - align_corners=True, - ) - - -class DPT(BaseModel): - def __init__( - self, - head, - features=256, - backbone="vitb_rn50_384", - readout="project", - channels_last=False, - use_bn=False, - ): - - super(DPT, self).__init__() - - self.channels_last = channels_last - - hooks = { - "vitb_rn50_384": [0, 1, 8, 11], - "vitb16_384": [2, 5, 8, 11], - "vitl16_384": [5, 11, 17, 23], - } - - # Instantiate backbone and reassemble blocks - self.pretrained, self.scratch = _make_encoder( - backbone, - features, - False, # Set to true of you want to train from scratch, uses ImageNet weights - groups=1, - expand=False, - exportable=False, - hooks=hooks[backbone], - use_readout=readout, - ) - - self.scratch.refinenet1 = _make_fusion_block(features, use_bn) - self.scratch.refinenet2 = _make_fusion_block(features, use_bn) - self.scratch.refinenet3 = _make_fusion_block(features, use_bn) - self.scratch.refinenet4 = _make_fusion_block(features, use_bn) - - self.scratch.output_conv = head - - - def forward(self, x): - if self.channels_last == True: - x.contiguous(memory_format=torch.channels_last) - - layer_1, layer_2, layer_3, layer_4 = forward_vit(self.pretrained, x) - - layer_1_rn = self.scratch.layer1_rn(layer_1) - layer_2_rn = self.scratch.layer2_rn(layer_2) - layer_3_rn = self.scratch.layer3_rn(layer_3) - layer_4_rn = self.scratch.layer4_rn(layer_4) - - path_4 = self.scratch.refinenet4(layer_4_rn) - path_3 = self.scratch.refinenet3(path_4, layer_3_rn) - path_2 = self.scratch.refinenet2(path_3, layer_2_rn) - path_1 = self.scratch.refinenet1(path_2, layer_1_rn) - - out = self.scratch.output_conv(path_1) - - return out - - -class DPTDepthModel(DPT): - def __init__(self, path=None, non_negative=True, **kwargs): - features = kwargs["features"] if "features" in kwargs else 256 - - head = nn.Sequential( - nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1), - Interpolate(scale_factor=2, mode="bilinear", align_corners=True), - nn.Conv2d(features // 2, 32, kernel_size=3, stride=1, padding=1), - nn.ReLU(True), - nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), - nn.ReLU(True) if non_negative else nn.Identity(), - nn.Identity(), - ) - - super().__init__(head, **kwargs) - - if path is not None: - self.load(path) - - def forward(self, x): - return super().forward(x).squeeze(dim=1) - diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/fileio/handlers/pickle_handler.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/fileio/handlers/pickle_handler.py deleted file mode 100644 index b37c79bed4ef9fd8913715e62dbe3fc5cafdc3aa..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/fileio/handlers/pickle_handler.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import pickle - -from .base import BaseFileHandler - - -class PickleHandler(BaseFileHandler): - - str_like = False - - def load_from_fileobj(self, file, **kwargs): - return pickle.load(file, **kwargs) - - def load_from_path(self, filepath, **kwargs): - return super(PickleHandler, self).load_from_path( - filepath, mode='rb', **kwargs) - - def dump_to_str(self, obj, **kwargs): - kwargs.setdefault('protocol', 2) - return pickle.dumps(obj, **kwargs) - - def dump_to_fileobj(self, obj, file, **kwargs): - kwargs.setdefault('protocol', 2) - pickle.dump(obj, file, **kwargs) - - def dump_to_path(self, obj, filepath, **kwargs): - super(PickleHandler, self).dump_to_path( - obj, filepath, mode='wb', **kwargs) diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmseg/datasets/pipelines/test_time_aug.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmseg/datasets/pipelines/test_time_aug.py deleted file mode 100644 index 6a1611a04d9d927223c9afbe5bf68af04d62937a..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmseg/datasets/pipelines/test_time_aug.py +++ /dev/null @@ -1,133 +0,0 @@ -import warnings - -import annotator.uniformer.mmcv as mmcv - -from ..builder import PIPELINES -from .compose import Compose - - -@PIPELINES.register_module() -class MultiScaleFlipAug(object): - """Test-time augmentation with multiple scales and flipping. - - An example configuration is as followed: - - .. code-block:: - - img_scale=(2048, 1024), - img_ratios=[0.5, 1.0], - flip=True, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='RandomFlip'), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ] - - After MultiScaleFLipAug with above configuration, the results are wrapped - into lists of the same length as followed: - - .. code-block:: - - dict( - img=[...], - img_shape=[...], - scale=[(1024, 512), (1024, 512), (2048, 1024), (2048, 1024)] - flip=[False, True, False, True] - ... - ) - - Args: - transforms (list[dict]): Transforms to apply in each augmentation. - img_scale (None | tuple | list[tuple]): Images scales for resizing. - img_ratios (float | list[float]): Image ratios for resizing - flip (bool): Whether apply flip augmentation. Default: False. - flip_direction (str | list[str]): Flip augmentation directions, - options are "horizontal" and "vertical". If flip_direction is list, - multiple flip augmentations will be applied. - It has no effect when flip == False. Default: "horizontal". - """ - - def __init__(self, - transforms, - img_scale, - img_ratios=None, - flip=False, - flip_direction='horizontal'): - self.transforms = Compose(transforms) - if img_ratios is not None: - img_ratios = img_ratios if isinstance(img_ratios, - list) else [img_ratios] - assert mmcv.is_list_of(img_ratios, float) - if img_scale is None: - # mode 1: given img_scale=None and a range of image ratio - self.img_scale = None - assert mmcv.is_list_of(img_ratios, float) - elif isinstance(img_scale, tuple) and mmcv.is_list_of( - img_ratios, float): - assert len(img_scale) == 2 - # mode 2: given a scale and a range of image ratio - self.img_scale = [(int(img_scale[0] * ratio), - int(img_scale[1] * ratio)) - for ratio in img_ratios] - else: - # mode 3: given multiple scales - self.img_scale = img_scale if isinstance(img_scale, - list) else [img_scale] - assert mmcv.is_list_of(self.img_scale, tuple) or self.img_scale is None - self.flip = flip - self.img_ratios = img_ratios - self.flip_direction = flip_direction if isinstance( - flip_direction, list) else [flip_direction] - assert mmcv.is_list_of(self.flip_direction, str) - if not self.flip and self.flip_direction != ['horizontal']: - warnings.warn( - 'flip_direction has no effect when flip is set to False') - if (self.flip - and not any([t['type'] == 'RandomFlip' for t in transforms])): - warnings.warn( - 'flip has no effect when RandomFlip is not in transforms') - - def __call__(self, results): - """Call function to apply test time augment transforms on results. - - Args: - results (dict): Result dict contains the data to transform. - - Returns: - dict[str: list]: The augmented data, where each value is wrapped - into a list. - """ - - aug_data = [] - if self.img_scale is None and mmcv.is_list_of(self.img_ratios, float): - h, w = results['img'].shape[:2] - img_scale = [(int(w * ratio), int(h * ratio)) - for ratio in self.img_ratios] - else: - img_scale = self.img_scale - flip_aug = [False, True] if self.flip else [False] - for scale in img_scale: - for flip in flip_aug: - for direction in self.flip_direction: - _results = results.copy() - _results['scale'] = scale - _results['flip'] = flip - _results['flip_direction'] = direction - data = self.transforms(_results) - aug_data.append(data) - # list of dict to dict of list - aug_data_dict = {key: [] for key in aug_data[0]} - for data in aug_data: - for key, val in data.items(): - aug_data_dict[key].append(val) - return aug_data_dict - - def __repr__(self): - repr_str = self.__class__.__name__ - repr_str += f'(transforms={self.transforms}, ' - repr_str += f'img_scale={self.img_scale}, flip={self.flip})' - repr_str += f'flip_direction={self.flip_direction}' - return repr_str diff --git a/spaces/PKaushik/humandetect/yolov6/utils/config.py b/spaces/PKaushik/humandetect/yolov6/utils/config.py deleted file mode 100644 index 7f9c13a3085e0738a3547fc35c5106defed4c489..0000000000000000000000000000000000000000 --- a/spaces/PKaushik/humandetect/yolov6/utils/config.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# The code is based on -# https://github.com/open-mmlab/mmcv/blob/master/mmcv/utils/config.py -# Copyright (c) OpenMMLab. - -import os.path as osp -import shutil -import sys -import tempfile -from importlib import import_module -from addict import Dict - - -class ConfigDict(Dict): - - def __missing__(self, name): - raise KeyError(name) - - def __getattr__(self, name): - try: - value = super(ConfigDict, self).__getattr__(name) - except KeyError: - ex = AttributeError("'{}' object has no attribute '{}'".format( - self.__class__.__name__, name)) - except Exception as e: - ex = e - else: - return value - raise ex - - -class Config(object): - - @staticmethod - def _file2dict(filename): - filename = str(filename) - if filename.endswith('.py'): - with tempfile.TemporaryDirectory() as temp_config_dir: - shutil.copyfile(filename, - osp.join(temp_config_dir, '_tempconfig.py')) - sys.path.insert(0, temp_config_dir) - mod = import_module('_tempconfig') - sys.path.pop(0) - cfg_dict = { - name: value - for name, value in mod.__dict__.items() - if not name.startswith('__') - } - # delete imported module - del sys.modules['_tempconfig'] - else: - raise IOError('Only .py type are supported now!') - cfg_text = filename + '\n' - with open(filename, 'r') as f: - cfg_text += f.read() - - return cfg_dict, cfg_text - - @staticmethod - def fromfile(filename): - cfg_dict, cfg_text = Config._file2dict(filename) - return Config(cfg_dict, cfg_text=cfg_text, filename=filename) - - def __init__(self, cfg_dict=None, cfg_text=None, filename=None): - if cfg_dict is None: - cfg_dict = dict() - elif not isinstance(cfg_dict, dict): - raise TypeError('cfg_dict must be a dict, but got {}'.format( - type(cfg_dict))) - - super(Config, self).__setattr__('_cfg_dict', ConfigDict(cfg_dict)) - super(Config, self).__setattr__('_filename', filename) - if cfg_text: - text = cfg_text - elif filename: - with open(filename, 'r') as f: - text = f.read() - else: - text = '' - super(Config, self).__setattr__('_text', text) - - @property - def filename(self): - return self._filename - - @property - def text(self): - return self._text - - def __repr__(self): - return 'Config (path: {}): {}'.format(self.filename, - self._cfg_dict.__repr__()) - - def __getattr__(self, name): - return getattr(self._cfg_dict, name) - - def __setattr__(self, name, value): - if isinstance(value, dict): - value = ConfigDict(value) - self._cfg_dict.__setattr__(name, value) diff --git a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/version.py b/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/version.py deleted file mode 100644 index 1cce4e50bd692d4002e3cac3c545a3fb2efe95d0..0000000000000000000000000000000000000000 --- a/spaces/Pie31415/control-animation/annotator/uniformer/mmcv/version.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -__version__ = '1.3.17' - - -def parse_version_info(version_str: str, length: int = 4) -> tuple: - """Parse a version string into a tuple. - - Args: - version_str (str): The version string. - length (int): The maximum number of version levels. Default: 4. - - Returns: - tuple[int | str]: The version info, e.g., "1.3.0" is parsed into - (1, 3, 0, 0, 0, 0), and "2.0.0rc1" is parsed into - (2, 0, 0, 0, 'rc', 1) (when length is set to 4). - """ - from packaging.version import parse - version = parse(version_str) - assert version.release, f'failed to parse version {version_str}' - release = list(version.release) - release = release[:length] - if len(release) < length: - release = release + [0] * (length - len(release)) - if version.is_prerelease: - release.extend(list(version.pre)) - elif version.is_postrelease: - release.extend(list(version.post)) - else: - release.extend([0, 0]) - return tuple(release) - - -version_info = tuple(int(x) for x in __version__.split('.')[:3]) - -__all__ = ['__version__', 'version_info', 'parse_version_info'] diff --git a/spaces/PureNaCl/Toxic-Tweets-MS2/scrapper.py b/spaces/PureNaCl/Toxic-Tweets-MS2/scrapper.py deleted file mode 100644 index 1ed6727c3f90096af6f9d4482059da67fa67544b..0000000000000000000000000000000000000000 --- a/spaces/PureNaCl/Toxic-Tweets-MS2/scrapper.py +++ /dev/null @@ -1,26 +0,0 @@ - -from selenium import webdriver -from selenium.webdriver.common.by import By -DRIVER_PATH = "/Driver/chromedriver" -HUGGING_FACE_DOC_URL = "https://huggingface.co/transformers/v3.3.1/pretrained_models.html" -PRETRAINED_MODEL_NAME_XPATH = '//*[@id="pretrained-models"]/div/table/tbody/tr/td/p/code/span' -def scrape_for_pretrained_model_names(driver): - driver.get(HUGGING_FACE_DOC_URL) - names =driver.find_elements(By.XPATH, PRETRAINED_MODEL_NAME_XPATH) - result = [name.text+"\n" for name in names] - with open('model-names.txt', 'w') as f: - f.writelines(result) - print(len(names)) - with open('model-names.txt', 'r') as f: - model_names = f.readlines() - model_names = [m.strip() for m in model_names] - print(model_names) - print(len(model_names)) - - -if __name__ == "__main__": - driver = driver = webdriver.Chrome(executable_path=DRIVER_PATH) - scrape_for_pretrained_model_names(driver) - - - \ No newline at end of file diff --git a/spaces/QCRI/mt-bench-ar/README.md b/spaces/QCRI/mt-bench-ar/README.md deleted file mode 100644 index 6fbc528146f6433ba673194514a568aef3929784..0000000000000000000000000000000000000000 --- a/spaces/QCRI/mt-bench-ar/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Mt Bench Ar -emoji: 🏆 -colorFrom: blue -colorTo: indigo -sdk: gradio -sdk_version: 3.49.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/RaIDooN/huggyllama-llama-13b/README.md b/spaces/RaIDooN/huggyllama-llama-13b/README.md deleted file mode 100644 index 5aac01d1f1b2baef2b40df55fe95cb66c0ce2797..0000000000000000000000000000000000000000 --- a/spaces/RaIDooN/huggyllama-llama-13b/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Huggyllama Llama 13b -emoji: 👀 -colorFrom: green -colorTo: purple -sdk: gradio -sdk_version: 3.27.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Ramse/TTS_Hindi/modules/hifigan/utils/train.py b/spaces/Ramse/TTS_Hindi/modules/hifigan/utils/train.py deleted file mode 100644 index 902f68dee3b3a1edc36cee9867804ceea747af4b..0000000000000000000000000000000000000000 --- a/spaces/Ramse/TTS_Hindi/modules/hifigan/utils/train.py +++ /dev/null @@ -1,226 +0,0 @@ -import os -import math -import tqdm -import torch -import itertools -import traceback -from utils.validation import validate -from model.generator import Generator -from model.multiscale import MultiScaleDiscriminator -from model.mpd import MPD -from .utils import get_commit_hash -from utils.stft_loss import MultiResolutionSTFTLoss -import numpy as np -from utils.stft import TacotronSTFT - - -def num_params(model, print_out=True): - parameters = filter(lambda p: p.requires_grad, model.parameters()) - parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000 - if print_out: - print('Trainable Parameters: %.3fM' % parameters) - -def train(args, pt_dir, chkpt_path, trainloader, valloader, writer, logger, hp, hp_str): - model_g = Generator(hp.audio.n_mel_channels).cuda() - model_d = MultiScaleDiscriminator(hp.model.num_D, hp.model.ndf, hp.model.n_layers, - hp.model.downsampling_factor, hp.model.disc_out).cuda() - model_d_mpd = MPD().cuda() - - optim_g = torch.optim.AdamW(model_g.parameters(), - lr=hp.train.adam.lr, betas=(hp.train.adam.beta1, hp.train.adam.beta2)) - optim_d = torch.optim.AdamW(itertools.chain(model_d.parameters(), model_d_mpd.parameters()), - lr=hp.train.adam.lr, betas=(hp.train.adam.beta1, hp.train.adam.beta2)) - - - stft = TacotronSTFT(filter_length=hp.audio.filter_length, - hop_length=hp.audio.hop_length, - win_length=hp.audio.win_length, - n_mel_channels=hp.audio.n_mel_channels, - sampling_rate=hp.audio.sampling_rate, - mel_fmin=hp.audio.mel_fmin, - mel_fmax=hp.audio.mel_fmax) - - githash = get_commit_hash() - - init_epoch = -1 - step = 0 - - if chkpt_path is not None: - logger.info("Resuming from checkpoint: %s" % chkpt_path) - checkpoint = torch.load(chkpt_path) - model_g.load_state_dict(checkpoint['model_g']) - model_d.load_state_dict(checkpoint['model_d']) - model_d_mpd.load_state_dict(checkpoint['model_d_mpd']) - optim_g.load_state_dict(checkpoint['optim_g']) - optim_d.load_state_dict(checkpoint['optim_d']) - step = checkpoint['step'] - init_epoch = checkpoint['epoch'] - - if hp_str != checkpoint['hp_str']: - logger.warning("New hparams is different from checkpoint. Will use new.") - - if githash != checkpoint['githash']: - logger.warning("Code might be different: git hash is different.") - logger.warning("%s -> %s" % (checkpoint['githash'], githash)) - - else: - logger.info("Starting new training run.") - - # this accelerates training when the size of minibatch is always consistent. - # if not consistent, it'll horribly slow down. - torch.backends.cudnn.benchmark = True - scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hp.train.adam.lr_decay, last_epoch=init_epoch) - scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hp.train.adam.lr_decay, last_epoch=init_epoch) - - try: - model_g.train() - model_d.train() - stft_loss = MultiResolutionSTFTLoss() - criterion = torch.nn.MSELoss().cuda() - l1loss = torch.nn.L1Loss() - - - for epoch in itertools.count(init_epoch + 1): - if epoch % hp.log.validation_interval == 0: - with torch.no_grad(): - validate(hp, model_g, model_d, model_d_mpd, valloader, stft_loss, l1loss, criterion, stft, writer, - step) - - trainloader.dataset.shuffle_mapping() - loader = tqdm.tqdm(trainloader, desc='Loading train data') - avg_g_loss = [] - avg_d_loss = [] - avg_adv_loss = [] - for (melG, audioG), (melD, audioD) in loader: - melG = melG.cuda() # torch.Size([16, 80, 64]) - audioG = audioG.cuda() # torch.Size([16, 1, 16000]) - melD = melD.cuda() # torch.Size([16, 80, 64]) - audioD = audioD.cuda() # torch.Size([16, 1, 16000] - - # generator - optim_g.zero_grad() - fake_audio = model_g(melG)[:, :, :hp.audio.segment_length] # torch.Size([16, 1, 12800]) - - loss_g = 0.0 - - sc_loss, mag_loss = stft_loss(fake_audio[:, :, :audioG.size(2)].squeeze(1), audioG.squeeze(1)) - loss_g += sc_loss + mag_loss # STFT Loss - - adv_loss = 0.0 - loss_mel = 0.0 - if step > hp.train.discriminator_train_start_steps: - - # for multi-scale discriminator - disc_real_scores, disc_real_feats = model_d(audioG) - disc_fake_scores, disc_fake_feats = model_d(fake_audio) - - for score_fake in disc_fake_scores: - # adv_loss += torch.mean(torch.sum(torch.pow(score_fake - 1.0, 2), dim=[1, 2])) - adv_loss += criterion(score_fake, torch.ones_like(score_fake)) - adv_loss = adv_loss / len(disc_fake_scores) # len(disc_fake) = 3 - - # MPD Adverserial loss - mpd_real_scores, mpd_real_feats = model_d_mpd(audioG) - mpd_fake_scores, mpd_fake_feats = model_d_mpd(fake_audio) - - for score_fake in mpd_fake_scores: - adv_mpd_loss = criterion(score_fake, torch.ones_like(score_fake)) - adv_mpd_loss = adv_mpd_loss / len(mpd_fake_scores) - adv_loss = adv_loss + adv_mpd_loss # Adv Loss - - # Mel Loss - mel_fake = stft.mel_spectrogram(fake_audio.squeeze(1), requires_grad=True) - loss_mel += l1loss(melG[:, :, :mel_fake.size(2)], mel_fake.cuda()) # Mel L1 loss - loss_g += hp.model.lambda_mel * loss_mel - - if hp.model.feat_loss: - for feats_fake, feats_real in zip(disc_fake_feats, disc_real_feats): - for feat_f, feat_r in zip(feats_fake, feats_real): - adv_loss += hp.model.feat_match * torch.mean(torch.abs(feat_f - feat_r)) - - for feats_fake, feats_real in zip(mpd_fake_feats, mpd_real_feats): - for feat_f, feat_r in zip(feats_fake, feats_real): - adv_loss += hp.model.feat_match * torch.mean(torch.abs(feat_f - feat_r)) - - loss_g += hp.model.lambda_adv * adv_loss - - loss_g.backward() - optim_g.step() - - # discriminator - loss_d_avg = 0.0 - if step > hp.train.discriminator_train_start_steps: - fake_audio = model_g(melD)[:, :, :hp.audio.segment_length] - fake_audio = fake_audio.detach() - loss_d_sum = 0.0 - for _ in range(hp.train.rep_discriminator): - optim_d.zero_grad() - disc_fake_scores, _ = model_d(fake_audio) - disc_real_scores, _ = model_d(audioD) - loss_d = 0.0 - - # MSD - for score_fake, score_real in zip(disc_fake_scores, disc_real_scores): - loss_d_real = criterion(score_real, torch.ones_like(score_real)) - loss_d_fake = criterion(score_fake, torch.zeros_like(score_fake)) - loss_d_real = loss_d_real / len(disc_real_scores) # len(disc_real) = 3 - loss_d_fake = loss_d_fake / len(disc_fake_scores) # len(disc_fake) = 3 - loss_d += loss_d_real + loss_d_fake # MSD loss - loss_d_sum += loss_d - - # MPD Adverserial loss - mpd_fake_scores, _ = model_d_mpd(fake_audio) - mpd_real_scores, _ = model_d_mpd(audioD) - for score_fake, score_real in zip(mpd_fake_scores, mpd_real_scores): - loss_mpd_real = criterion(score_real, torch.ones_like(score_real)) - loss_mpd_fake = criterion(score_fake, torch.zeros_like(score_fake)) - loss_mpd = (loss_mpd_fake + loss_mpd_real)/len(mpd_real_scores) # MPD Loss - loss_d += loss_mpd - - loss_d.backward() - optim_d.step() - loss_d_sum += loss_mpd - - loss_d_avg = loss_d_sum / hp.train.rep_discriminator - loss_d_avg = loss_d_avg.item() - - step += 1 - # logging - loss_g = loss_g.item() - avg_g_loss.append(loss_g) - avg_d_loss.append(loss_d_avg) - avg_adv_loss.append(adv_loss) - - if any([loss_g > 1e8, math.isnan(loss_g), loss_d_avg > 1e8, math.isnan(loss_d_avg)]): - logger.error("loss_g %.01f loss_d_avg %.01f at step %d!" % (loss_g, loss_d_avg, step)) - raise Exception("Loss exploded") - - if step % hp.log.summary_interval == 0: - writer.log_training(loss_g, loss_d_avg, adv_loss, loss_mel, step) - loader.set_description( - "Avg : g %.04f d %.04f ad %.04f| step %d" % (sum(avg_g_loss) / len(avg_g_loss), - sum(avg_d_loss) / len(avg_d_loss), - sum(avg_adv_loss) / len(avg_adv_loss), - step)) - if epoch % hp.log.save_interval == 0: - save_path = os.path.join(pt_dir, '%s_%s_%04d.pt' - % (args.name, githash, epoch)) - torch.save({ - 'model_g': model_g.state_dict(), - 'model_d': model_d.state_dict(), - 'model_d_mpd': model_d_mpd.state_dict(), - 'optim_g': optim_g.state_dict(), - 'optim_d': optim_d.state_dict(), - 'step': step, - 'epoch': epoch, - 'hp_str': hp_str, - 'githash': githash, - }, save_path) - logger.info("Saved checkpoint to: %s" % save_path) - - scheduler_g.step() - scheduler_d.step() - - except Exception as e: - logger.info("Exiting due to exception: %s" % e) - traceback.print_exc() diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/models/necks/yolo_neck.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/models/necks/yolo_neck.py deleted file mode 100644 index c2f9b9ef3859796c284c16ad1a92fe41ecbed613..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet_null/models/necks/yolo_neck.py +++ /dev/null @@ -1,136 +0,0 @@ -# Copyright (c) 2019 Western Digital Corporation or its affiliates. - -import torch -import torch.nn as nn -import torch.nn.functional as F -from mmcv.cnn import ConvModule - -from ..builder import NECKS - - -class DetectionBlock(nn.Module): - """Detection block in YOLO neck. - - Let out_channels = n, the DetectionBlock contains: - Six ConvLayers, 1 Conv2D Layer and 1 YoloLayer. - The first 6 ConvLayers are formed the following way: - 1x1xn, 3x3x2n, 1x1xn, 3x3x2n, 1x1xn, 3x3x2n. - The Conv2D layer is 1x1x255. - Some block will have branch after the fifth ConvLayer. - The input channel is arbitrary (in_channels) - - Args: - in_channels (int): The number of input channels. - out_channels (int): The number of output channels. - conv_cfg (dict): Config dict for convolution layer. Default: None. - norm_cfg (dict): Dictionary to construct and config norm layer. - Default: dict(type='BN', requires_grad=True) - act_cfg (dict): Config dict for activation layer. - Default: dict(type='LeakyReLU', negative_slope=0.1). - """ - - def __init__(self, - in_channels, - out_channels, - conv_cfg=None, - norm_cfg=dict(type='BN', requires_grad=True), - act_cfg=dict(type='LeakyReLU', negative_slope=0.1)): - super(DetectionBlock, self).__init__() - double_out_channels = out_channels * 2 - - # shortcut - cfg = dict(conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) - self.conv1 = ConvModule(in_channels, out_channels, 1, **cfg) - self.conv2 = ConvModule( - out_channels, double_out_channels, 3, padding=1, **cfg) - self.conv3 = ConvModule(double_out_channels, out_channels, 1, **cfg) - self.conv4 = ConvModule( - out_channels, double_out_channels, 3, padding=1, **cfg) - self.conv5 = ConvModule(double_out_channels, out_channels, 1, **cfg) - - def forward(self, x): - tmp = self.conv1(x) - tmp = self.conv2(tmp) - tmp = self.conv3(tmp) - tmp = self.conv4(tmp) - out = self.conv5(tmp) - return out - - -@NECKS.register_module() -class YOLOV3Neck(nn.Module): - """The neck of YOLOV3. - - It can be treated as a simplified version of FPN. It - will take the result from Darknet backbone and do some upsampling and - concatenation. It will finally output the detection result. - - Note: - The input feats should be from top to bottom. - i.e., from high-lvl to low-lvl - But YOLOV3Neck will process them in reversed order. - i.e., from bottom (high-lvl) to top (low-lvl) - - Args: - num_scales (int): The number of scales / stages. - in_channels (int): The number of input channels. - out_channels (int): The number of output channels. - conv_cfg (dict): Config dict for convolution layer. Default: None. - norm_cfg (dict): Dictionary to construct and config norm layer. - Default: dict(type='BN', requires_grad=True) - act_cfg (dict): Config dict for activation layer. - Default: dict(type='LeakyReLU', negative_slope=0.1). - """ - - def __init__(self, - num_scales, - in_channels, - out_channels, - conv_cfg=None, - norm_cfg=dict(type='BN', requires_grad=True), - act_cfg=dict(type='LeakyReLU', negative_slope=0.1)): - super(YOLOV3Neck, self).__init__() - assert (num_scales == len(in_channels) == len(out_channels)) - self.num_scales = num_scales - self.in_channels = in_channels - self.out_channels = out_channels - - # shortcut - cfg = dict(conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) - - # To support arbitrary scales, the code looks awful, but it works. - # Better solution is welcomed. - self.detect1 = DetectionBlock(in_channels[0], out_channels[0], **cfg) - for i in range(1, self.num_scales): - in_c, out_c = self.in_channels[i], self.out_channels[i] - self.add_module(f'conv{i}', ConvModule(in_c, out_c, 1, **cfg)) - # in_c + out_c : High-lvl feats will be cat with low-lvl feats - self.add_module(f'detect{i+1}', - DetectionBlock(in_c + out_c, out_c, **cfg)) - - def forward(self, feats): - assert len(feats) == self.num_scales - - # processed from bottom (high-lvl) to top (low-lvl) - outs = [] - out = self.detect1(feats[-1]) - outs.append(out) - - for i, x in enumerate(reversed(feats[:-1])): - conv = getattr(self, f'conv{i+1}') - tmp = conv(out) - - # Cat with low-lvl feats - tmp = F.interpolate(tmp, scale_factor=2) - tmp = torch.cat((tmp, x), 1) - - detect = getattr(self, f'detect{i+2}') - out = detect(tmp) - outs.append(out) - - return tuple(outs) - - def init_weights(self): - """Initialize the weights of module.""" - # init is done in ConvModule - pass diff --git a/spaces/Rothfeld/stable-diffusion-mat-outpainting-primer/dnnlib/util.py b/spaces/Rothfeld/stable-diffusion-mat-outpainting-primer/dnnlib/util.py deleted file mode 100644 index 76725336d01e75e1c68daa88be47f4fde0bbc63b..0000000000000000000000000000000000000000 --- a/spaces/Rothfeld/stable-diffusion-mat-outpainting-primer/dnnlib/util.py +++ /dev/null @@ -1,477 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - -"""Miscellaneous utility classes and functions.""" - -import ctypes -import fnmatch -import importlib -import inspect -import numpy as np -import os -import shutil -import sys -import types -import io -import pickle -import re -import requests -import html -import hashlib -import glob -import tempfile -import urllib -import urllib.request -import uuid - -from distutils.util import strtobool -from typing import Any, List, Tuple, Union - - -# Util classes -# ------------------------------------------------------------------------------------------ - - -class EasyDict(dict): - """Convenience class that behaves like a dict but allows access with the attribute syntax.""" - - def __getattr__(self, name: str) -> Any: - try: - return self[name] - except KeyError: - raise AttributeError(name) - - def __setattr__(self, name: str, value: Any) -> None: - self[name] = value - - def __delattr__(self, name: str) -> None: - del self[name] - - -class Logger(object): - """Redirect stderr to stdout, optionally print stdout to a file, and optionally force flushing on both stdout and the file.""" - - def __init__(self, file_name: str = None, file_mode: str = "w", should_flush: bool = True): - self.file = None - - if file_name is not None: - self.file = open(file_name, file_mode) - - self.should_flush = should_flush - self.stdout = sys.stdout - self.stderr = sys.stderr - - sys.stdout = self - sys.stderr = self - - def __enter__(self) -> "Logger": - return self - - def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: - self.close() - - def write(self, text: Union[str, bytes]) -> None: - """Write text to stdout (and a file) and optionally flush.""" - if isinstance(text, bytes): - text = text.decode() - if len(text) == 0: # workaround for a bug in VSCode debugger: sys.stdout.write(''); sys.stdout.flush() => crash - return - - if self.file is not None: - self.file.write(text) - - self.stdout.write(text) - - if self.should_flush: - self.flush() - - def flush(self) -> None: - """Flush written text to both stdout and a file, if open.""" - if self.file is not None: - self.file.flush() - - self.stdout.flush() - - def close(self) -> None: - """Flush, close possible files, and remove stdout/stderr mirroring.""" - self.flush() - - # if using multiple loggers, prevent closing in wrong order - if sys.stdout is self: - sys.stdout = self.stdout - if sys.stderr is self: - sys.stderr = self.stderr - - if self.file is not None: - self.file.close() - self.file = None - - -# Cache directories -# ------------------------------------------------------------------------------------------ - -_dnnlib_cache_dir = None - -def set_cache_dir(path: str) -> None: - global _dnnlib_cache_dir - _dnnlib_cache_dir = path - -def make_cache_dir_path(*paths: str) -> str: - if _dnnlib_cache_dir is not None: - return os.path.join(_dnnlib_cache_dir, *paths) - if 'DNNLIB_CACHE_DIR' in os.environ: - return os.path.join(os.environ['DNNLIB_CACHE_DIR'], *paths) - if 'HOME' in os.environ: - return os.path.join(os.environ['HOME'], '.cache', 'dnnlib', *paths) - if 'USERPROFILE' in os.environ: - return os.path.join(os.environ['USERPROFILE'], '.cache', 'dnnlib', *paths) - return os.path.join(tempfile.gettempdir(), '.cache', 'dnnlib', *paths) - -# Small util functions -# ------------------------------------------------------------------------------------------ - - -def format_time(seconds: Union[int, float]) -> str: - """Convert the seconds to human readable string with days, hours, minutes and seconds.""" - s = int(np.rint(seconds)) - - if s < 60: - return "{0}s".format(s) - elif s < 60 * 60: - return "{0}m {1:02}s".format(s // 60, s % 60) - elif s < 24 * 60 * 60: - return "{0}h {1:02}m {2:02}s".format(s // (60 * 60), (s // 60) % 60, s % 60) - else: - return "{0}d {1:02}h {2:02}m".format(s // (24 * 60 * 60), (s // (60 * 60)) % 24, (s // 60) % 60) - - -def ask_yes_no(question: str) -> bool: - """Ask the user the question until the user inputs a valid answer.""" - while True: - try: - print("{0} [y/n]".format(question)) - return strtobool(input().lower()) - except ValueError: - pass - - -def tuple_product(t: Tuple) -> Any: - """Calculate the product of the tuple elements.""" - result = 1 - - for v in t: - result *= v - - return result - - -_str_to_ctype = { - "uint8": ctypes.c_ubyte, - "uint16": ctypes.c_uint16, - "uint32": ctypes.c_uint32, - "uint64": ctypes.c_uint64, - "int8": ctypes.c_byte, - "int16": ctypes.c_int16, - "int32": ctypes.c_int32, - "int64": ctypes.c_int64, - "float32": ctypes.c_float, - "float64": ctypes.c_double -} - - -def get_dtype_and_ctype(type_obj: Any) -> Tuple[np.dtype, Any]: - """Given a type name string (or an object having a __name__ attribute), return matching Numpy and ctypes types that have the same size in bytes.""" - type_str = None - - if isinstance(type_obj, str): - type_str = type_obj - elif hasattr(type_obj, "__name__"): - type_str = type_obj.__name__ - elif hasattr(type_obj, "name"): - type_str = type_obj.name - else: - raise RuntimeError("Cannot infer type name from input") - - assert type_str in _str_to_ctype.keys() - - my_dtype = np.dtype(type_str) - my_ctype = _str_to_ctype[type_str] - - assert my_dtype.itemsize == ctypes.sizeof(my_ctype) - - return my_dtype, my_ctype - - -def is_pickleable(obj: Any) -> bool: - try: - with io.BytesIO() as stream: - pickle.dump(obj, stream) - return True - except: - return False - - -# Functionality to import modules/objects by name, and call functions by name -# ------------------------------------------------------------------------------------------ - -def get_module_from_obj_name(obj_name: str) -> Tuple[types.ModuleType, str]: - """Searches for the underlying module behind the name to some python object. - Returns the module and the object name (original name with module part removed).""" - - # allow convenience shorthands, substitute them by full names - obj_name = re.sub("^np.", "numpy.", obj_name) - obj_name = re.sub("^tf.", "tensorflow.", obj_name) - - # list alternatives for (module_name, local_obj_name) - parts = obj_name.split(".") - name_pairs = [(".".join(parts[:i]), ".".join(parts[i:])) for i in range(len(parts), 0, -1)] - - # try each alternative in turn - for module_name, local_obj_name in name_pairs: - try: - module = importlib.import_module(module_name) # may raise ImportError - get_obj_from_module(module, local_obj_name) # may raise AttributeError - return module, local_obj_name - except: - pass - - # maybe some of the modules themselves contain errors? - for module_name, _local_obj_name in name_pairs: - try: - importlib.import_module(module_name) # may raise ImportError - except ImportError: - if not str(sys.exc_info()[1]).startswith("No module named '" + module_name + "'"): - raise - - # maybe the requested attribute is missing? - for module_name, local_obj_name in name_pairs: - try: - module = importlib.import_module(module_name) # may raise ImportError - get_obj_from_module(module, local_obj_name) # may raise AttributeError - except ImportError: - pass - - # we are out of luck, but we have no idea why - raise ImportError(obj_name) - - -def get_obj_from_module(module: types.ModuleType, obj_name: str) -> Any: - """Traverses the object name and returns the last (rightmost) python object.""" - if obj_name == '': - return module - obj = module - for part in obj_name.split("."): - obj = getattr(obj, part) - return obj - - -def get_obj_by_name(name: str) -> Any: - """Finds the python object with the given name.""" - module, obj_name = get_module_from_obj_name(name) - return get_obj_from_module(module, obj_name) - - -def call_func_by_name(*args, func_name: str = None, **kwargs) -> Any: - """Finds the python object with the given name and calls it as a function.""" - assert func_name is not None - func_obj = get_obj_by_name(func_name) - assert callable(func_obj) - return func_obj(*args, **kwargs) - - -def construct_class_by_name(*args, class_name: str = None, **kwargs) -> Any: - """Finds the python class with the given name and constructs it with the given arguments.""" - return call_func_by_name(*args, func_name=class_name, **kwargs) - - -def get_module_dir_by_obj_name(obj_name: str) -> str: - """Get the directory path of the module containing the given object name.""" - module, _ = get_module_from_obj_name(obj_name) - return os.path.dirname(inspect.getfile(module)) - - -def is_top_level_function(obj: Any) -> bool: - """Determine whether the given object is a top-level function, i.e., defined at module scope using 'def'.""" - return callable(obj) and obj.__name__ in sys.modules[obj.__module__].__dict__ - - -def get_top_level_function_name(obj: Any) -> str: - """Return the fully-qualified name of a top-level function.""" - assert is_top_level_function(obj) - module = obj.__module__ - if module == '__main__': - module = os.path.splitext(os.path.basename(sys.modules[module].__file__))[0] - return module + "." + obj.__name__ - - -# File system helpers -# ------------------------------------------------------------------------------------------ - -def list_dir_recursively_with_ignore(dir_path: str, ignores: List[str] = None, add_base_to_relative: bool = False) -> List[Tuple[str, str]]: - """List all files recursively in a given directory while ignoring given file and directory names. - Returns list of tuples containing both absolute and relative paths.""" - assert os.path.isdir(dir_path) - base_name = os.path.basename(os.path.normpath(dir_path)) - - if ignores is None: - ignores = [] - - result = [] - - for root, dirs, files in os.walk(dir_path, topdown=True): - for ignore_ in ignores: - dirs_to_remove = [d for d in dirs if fnmatch.fnmatch(d, ignore_)] - - # dirs need to be edited in-place - for d in dirs_to_remove: - dirs.remove(d) - - files = [f for f in files if not fnmatch.fnmatch(f, ignore_)] - - absolute_paths = [os.path.join(root, f) for f in files] - relative_paths = [os.path.relpath(p, dir_path) for p in absolute_paths] - - if add_base_to_relative: - relative_paths = [os.path.join(base_name, p) for p in relative_paths] - - assert len(absolute_paths) == len(relative_paths) - result += zip(absolute_paths, relative_paths) - - return result - - -def copy_files_and_create_dirs(files: List[Tuple[str, str]]) -> None: - """Takes in a list of tuples of (src, dst) paths and copies files. - Will create all necessary directories.""" - for file in files: - target_dir_name = os.path.dirname(file[1]) - - # will create all intermediate-level directories - if not os.path.exists(target_dir_name): - os.makedirs(target_dir_name) - - shutil.copyfile(file[0], file[1]) - - -# URL helpers -# ------------------------------------------------------------------------------------------ - -def is_url(obj: Any, allow_file_urls: bool = False) -> bool: - """Determine whether the given object is a valid URL string.""" - if not isinstance(obj, str) or not "://" in obj: - return False - if allow_file_urls and obj.startswith('file://'): - return True - try: - res = requests.compat.urlparse(obj) - if not res.scheme or not res.netloc or not "." in res.netloc: - return False - res = requests.compat.urlparse(requests.compat.urljoin(obj, "/")) - if not res.scheme or not res.netloc or not "." in res.netloc: - return False - except: - return False - return True - - -def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: bool = True, return_filename: bool = False, cache: bool = True) -> Any: - """Download the given URL and return a binary-mode file object to access the data.""" - assert num_attempts >= 1 - assert not (return_filename and (not cache)) - - # Doesn't look like an URL scheme so interpret it as a local filename. - if not re.match('^[a-z]+://', url): - return url if return_filename else open(url, "rb") - - # Handle file URLs. This code handles unusual file:// patterns that - # arise on Windows: - # - # file:///c:/foo.txt - # - # which would translate to a local '/c:/foo.txt' filename that's - # invalid. Drop the forward slash for such pathnames. - # - # If you touch this code path, you should test it on both Linux and - # Windows. - # - # Some internet resources suggest using urllib.request.url2pathname() but - # but that converts forward slashes to backslashes and this causes - # its own set of problems. - if url.startswith('file://'): - filename = urllib.parse.urlparse(url).path - if re.match(r'^/[a-zA-Z]:', filename): - filename = filename[1:] - return filename if return_filename else open(filename, "rb") - - assert is_url(url) - - # Lookup from cache. - if cache_dir is None: - cache_dir = make_cache_dir_path('downloads') - - url_md5 = hashlib.md5(url.encode("utf-8")).hexdigest() - if cache: - cache_files = glob.glob(os.path.join(cache_dir, url_md5 + "_*")) - if len(cache_files) == 1: - filename = cache_files[0] - return filename if return_filename else open(filename, "rb") - - # Download. - url_name = None - url_data = None - with requests.Session() as session: - if verbose: - print("Downloading %s ..." % url, end="", flush=True) - for attempts_left in reversed(range(num_attempts)): - try: - with session.get(url) as res: - res.raise_for_status() - if len(res.content) == 0: - raise IOError("No data received") - - if len(res.content) < 8192: - content_str = res.content.decode("utf-8") - if "download_warning" in res.headers.get("Set-Cookie", ""): - links = [html.unescape(link) for link in content_str.split('"') if "export=download" in link] - if len(links) == 1: - url = requests.compat.urljoin(url, links[0]) - raise IOError("Google Drive virus checker nag") - if "Google Drive - Quota exceeded" in content_str: - raise IOError("Google Drive download quota exceeded -- please try again later") - - match = re.search(r'filename="([^"]*)"', res.headers.get("Content-Disposition", "")) - url_name = match[1] if match else url - url_data = res.content - if verbose: - print(" done") - break - except KeyboardInterrupt: - raise - except: - if not attempts_left: - if verbose: - print(" failed") - raise - if verbose: - print(".", end="", flush=True) - - # Save to cache. - if cache: - safe_name = re.sub(r"[^0-9a-zA-Z-._]", "_", url_name) - cache_file = os.path.join(cache_dir, url_md5 + "_" + safe_name) - temp_file = os.path.join(cache_dir, "tmp_" + uuid.uuid4().hex + "_" + url_md5 + "_" + safe_name) - os.makedirs(cache_dir, exist_ok=True) - with open(temp_file, "wb") as f: - f.write(url_data) - os.replace(temp_file, cache_file) # atomic - if return_filename: - return cache_file - - # Return data as file object. - assert not return_filename - return io.BytesIO(url_data) diff --git a/spaces/SeyedAli/Image-Object-Detection/app.py b/spaces/SeyedAli/Image-Object-Detection/app.py deleted file mode 100644 index 33ed6ffa31c2b305aae6f6ea1a1eda72382092c1..0000000000000000000000000000000000000000 --- a/spaces/SeyedAli/Image-Object-Detection/app.py +++ /dev/null @@ -1,86 +0,0 @@ -from transformers import AutoFeatureExtractor, YolosForObjectDetection -import gradio as gr -from PIL import Image -import torch -import matplotlib.pyplot as plt -import io -import numpy as np - - -COLORS = [[0.000, 0.447, 0.741], [0.850, 0.325, 0.098], [0.929, 0.694, 0.125], - [0.494, 0.184, 0.556], [0.466, 0.674, 0.188], [0.301, 0.745, 0.933]] - - -def process_class_list(classes_string: str): - if classes_string == "": - return [] - classes_list = classes_string.split(",") - classes_list = [x.strip() for x in classes_list] - return classes_list - -def model_inference(img, model_name: str, prob_threshold: int, classes_to_show = str): - feature_extractor = AutoFeatureExtractor.from_pretrained(f"hustvl/{model_name}") - model = YolosForObjectDetection.from_pretrained(f"hustvl/{model_name}") - - img = Image.fromarray(img) - - pixel_values = feature_extractor(img, return_tensors="pt").pixel_values - - with torch.no_grad(): - outputs = model(pixel_values, output_attentions=True) - - probas = outputs.logits.softmax(-1)[0, :, :-1] - keep = probas.max(-1).values > prob_threshold - - target_sizes = torch.tensor(img.size[::-1]).unsqueeze(0) - postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes) - bboxes_scaled = postprocessed_outputs[0]['boxes'] - - classes_list = process_class_list(classes_to_show) - res_img = plot_results(img, probas[keep], bboxes_scaled[keep], model, classes_list) - - return res_img - -def plot_results(pil_img, prob, boxes, model, classes_list): - plt.figure(figsize=(16,10)) - plt.imshow(pil_img) - ax = plt.gca() - colors = COLORS * 100 - for p, (xmin, ymin, xmax, ymax), c in zip(prob, boxes.tolist(), colors): - cl = p.argmax() - object_class = model.config.id2label[cl.item()] - - if len(classes_list) > 0 : - if object_class not in classes_list: - continue - - ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, - fill=False, color=c, linewidth=3)) - text = f'{object_class}: {p[cl]:0.2f}' - ax.text(xmin, ymin, text, fontsize=15, - bbox=dict(facecolor='yellow', alpha=0.5)) - plt.axis('off') - return fig2img(plt.gcf()) - -def fig2img(fig): - buf = io.BytesIO() - fig.savefig(buf) - buf.seek(0) - img = Image.open(buf) - return img - -description = """YOLOS - Object Detection""" - -image_in = gr.components.Image() -image_out = gr.components.Image() -model_choice = gr.components.Dropdown(["yolos-tiny", "yolos-small", "yolos-base", "yolos-small-300", "yolos-small-dwr"], value="yolos-small", label="YOLOS Model") -prob_threshold_slider = gr.components.Slider(minimum=0, maximum=1.0, step=0.01, value=0.9, label="Probability Threshold") -classes_to_show = gr.components.Textbox(placeholder="e.g. person, truck", label="Classes to use (defaulted to detect all classes)") - -Iface = gr.Interface( - fn=model_inference, - inputs=[image_in,model_choice, prob_threshold_slider, classes_to_show], - outputs=image_out, - title="YOLOS - Object Detection", - description=description, -).launch() \ No newline at end of file diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/magics/extension.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/magics/extension.py deleted file mode 100644 index 2bc76b2d552f18e40b70b766a7827cf8df17dfe8..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/magics/extension.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Implementation of magic functions for the extension machinery. -""" -#----------------------------------------------------------------------------- -# Copyright (c) 2012 The IPython Development Team. -# -# Distributed under the terms of the Modified BSD License. -# -# The full license is in the file COPYING.txt, distributed with this software. -#----------------------------------------------------------------------------- - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- - - -# Our own packages -from IPython.core.error import UsageError -from IPython.core.magic import Magics, magics_class, line_magic - -#----------------------------------------------------------------------------- -# Magic implementation classes -#----------------------------------------------------------------------------- - -@magics_class -class ExtensionMagics(Magics): - """Magics to manage the IPython extensions system.""" - - @line_magic - def load_ext(self, module_str): - """Load an IPython extension by its module name.""" - if not module_str: - raise UsageError('Missing module name.') - res = self.shell.extension_manager.load_extension(module_str) - - if res == 'already loaded': - print("The %s extension is already loaded. To reload it, use:" % module_str) - print(" %reload_ext", module_str) - elif res == 'no load function': - print("The %s module is not an IPython extension." % module_str) - - @line_magic - def unload_ext(self, module_str): - """Unload an IPython extension by its module name. - - Not all extensions can be unloaded, only those which define an - ``unload_ipython_extension`` function. - """ - if not module_str: - raise UsageError('Missing module name.') - - res = self.shell.extension_manager.unload_extension(module_str) - - if res == 'no unload function': - print("The %s extension doesn't define how to unload it." % module_str) - elif res == "not loaded": - print("The %s extension is not loaded." % module_str) - - @line_magic - def reload_ext(self, module_str): - """Reload an IPython extension by its module name.""" - if not module_str: - raise UsageError('Missing module name.') - self.shell.extension_manager.reload_extension(module_str) diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/clickhouse_connect/datatypes/__init__.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/clickhouse_connect/datatypes/__init__.py deleted file mode 100644 index aa9b8c2f5d29e75889856750f3bfe8ed89889865..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/clickhouse_connect/datatypes/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -import clickhouse_connect.datatypes.container -import clickhouse_connect.datatypes.network -import clickhouse_connect.datatypes.numeric -import clickhouse_connect.datatypes.special -import clickhouse_connect.datatypes.string -import clickhouse_connect.datatypes.temporal -import clickhouse_connect.datatypes.registry diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/base_doc/docarray_response.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/base_doc/docarray_response.py deleted file mode 100644 index a9f807ab6b4c1add4547d77dca53529e16570c48..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/docarray/base_doc/docarray_response.py +++ /dev/null @@ -1,35 +0,0 @@ -from typing import TYPE_CHECKING, Any - -from docarray.base_doc.io.json import orjson_dumps -from docarray.utils._internal.misc import import_library - -if TYPE_CHECKING: - from fastapi.responses import JSONResponse -else: - fastapi = import_library('fastapi', raise_error=True) - JSONResponse = fastapi.responses.JSONResponse - - -class DocArrayResponse(JSONResponse): - """ - This is a custom Response class for FastAPI and starlette. This is needed - to handle serialization of the Document types when using FastAPI - - --- - - ```python - from docarray.documets import Text - from docarray.base_doc import DocResponse - - - @app.post("/doc/", response_model=Text, response_class=DocResponse) - async def create_item(doc: Text) -> Text: - return doc - ``` - - --- - - """ - - def render(self, content: Any) -> bytes: - return orjson_dumps(content) diff --git a/spaces/TRI-ML/risk_biased_prediction/risk_biased/utils/metrics.py b/spaces/TRI-ML/risk_biased_prediction/risk_biased/utils/metrics.py deleted file mode 100644 index 65318ce8b9f32c32b449628037a0d6cdcb91ad57..0000000000000000000000000000000000000000 --- a/spaces/TRI-ML/risk_biased_prediction/risk_biased/utils/metrics.py +++ /dev/null @@ -1,81 +0,0 @@ -from typing import Optional - -import torch - - -def FDE( - pred: torch.Tensor, truth: torch.Tensor, mask_loss: Optional[torch.Tensor] = None -): - """ - pred (Tensor): (..., time, xy) - truth (Tensor): (..., time, xy) - mask_loss (Tensor): (..., time) Defaults to None. - """ - if mask_loss is None: - return torch.mean( - torch.sqrt( - torch.sum(torch.square(pred[..., -1, :2] - truth[..., -1, :2]), -1) - ) - ) - else: - mask_loss = mask_loss.float() - return torch.sum( - torch.sqrt( - torch.sum(torch.square(pred[..., -1, :2] - truth[..., -1, :2]), -1) - ) - * mask_loss[..., -1] - ) / torch.sum(mask_loss[..., -1]).clamp_min(1) - - -def ADE( - pred: torch.Tensor, truth: torch.Tensor, mask_loss: Optional[torch.Tensor] = None -): - """ - pred (Tensor): (..., time, xy) - truth (Tensor): (..., time, xy) - mask_loss (Tensor): (..., time) Defaults to None. - """ - if mask_loss is None: - return torch.mean( - torch.sqrt( - torch.sum(torch.square(pred[..., :, :2] - truth[..., :, :2]), -1) - ) - ) - else: - mask_loss = mask_loss.float() - return torch.sum( - torch.sqrt( - torch.sum(torch.square(pred[..., :, :2] - truth[..., :, :2]), -1) - ) - * mask_loss - ) / torch.sum(mask_loss).clamp_min(1) - - -def minFDE( - pred: torch.Tensor, truth: torch.Tensor, mask_loss: Optional[torch.Tensor] = None -): - """ - pred (Tensor): (..., n_samples, time, xy) - truth (Tensor): (..., time, xy) - mask_loss (Tensor): (..., time) Defaults to None. - """ - if mask_loss is None: - min_distances, _ = torch.min( - torch.sqrt( - torch.sum(torch.square(pred[..., -1, :2] - truth[..., -1, :2]), -1) - ), - -1, - ) - return torch.mean(min_distances) - else: - mask_loss = mask_loss[..., -1].float() - final_distances = torch.sqrt( - torch.sum(torch.square(pred[..., -1, :2] - truth[..., -1, :2]), -1) - ) - max_final_distance = torch.max(final_distances * mask_loss) - min_distances, _ = torch.min( - final_distances + max_final_distance * (1 - mask_loss), -1 - ) - return torch.sum(min_distances * mask_loss.any(-1)) / torch.sum( - mask_loss.any(-1) - ).clamp_min(1) diff --git a/spaces/TabPFN/TabPFNPrediction/TabPFN/losses.py b/spaces/TabPFN/TabPFNPrediction/TabPFN/losses.py deleted file mode 100644 index 734d8f7ab3b6613eb2fba9feffdfaa46215106af..0000000000000000000000000000000000000000 --- a/spaces/TabPFN/TabPFNPrediction/TabPFN/losses.py +++ /dev/null @@ -1,41 +0,0 @@ -import torch -from torch import nn - -class CrossEntropyForMulticlassLoss(torch.nn.CrossEntropyLoss): - # This loss applies cross entropy after reducing the number of prediction - # dimensions to the number of classes in the target - - # TODO: loss.item() doesn't work so the displayed losses are Nans - def __init__(self, num_classes, weight=None, size_average=None, ignore_index: int = -100, - reduce=None, reduction: str = 'mean', label_smoothing: float = 0.0) -> None: - super().__init__(size_average=size_average, reduce=reduce, reduction=reduction, ignore_index=ignore_index) - self.num_classes = num_classes - - def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: - loss = torch.zeros_like(input[:, :, 0]) - for b in range(target.shape[1]): - l = super().forward(input[:, b, 0:len(torch.unique(target[:, b]))], target[:, b]) - loss[:, b] += l - return loss.flatten() - -def JointBCELossWithLogits(output, target): - # output shape: (S, B, NS) with NS = Number of sequences - # target shape: (S, B, SL) - # Loss = -log(mean_NS(prod_SL(p(target_SL, output_NS)))) - # Here at the moment NS = SL - output = output.unsqueeze(-1).repeat(1, 1, 1, target.shape[-1]) # (S, B, NS, SL) - output = output.permute(2, 0, 1, 3) # (NS, S, B, SL) - print(target.shape, output.shape) - loss = (target * torch.sigmoid(output)) + ((1-target) * (1-torch.sigmoid(output))) - loss = loss.prod(-1) - loss = loss.mean(0) - loss = -torch.log(loss) - loss = loss.mean() - return loss - -class ScaledSoftmaxCE(nn.Module): - def forward(self, x, label): - logits = x[..., :-10] - temp_scales = x[..., -10:] - - logprobs = logits.softmax(-1) diff --git a/spaces/TandCAcceptMe/face-swap-docker/chain_img_processor/video.py b/spaces/TandCAcceptMe/face-swap-docker/chain_img_processor/video.py deleted file mode 100644 index 857aea1a99eab21676f10341f4ad03dcd7f29d8a..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/chain_img_processor/video.py +++ /dev/null @@ -1,132 +0,0 @@ -import roop.globals - -from threading import Thread -from chain_img_processor import ChainImgProcessor - -class ThreadWithReturnValue(Thread): - - def __init__(self, group=None, target=None, name=None, - args=(), kwargs={}, Verbose=None): - Thread.__init__(self, group, target, name, args, kwargs) - self._return = None - - def run(self): - if self._target is not None: - self._return = self._target(*self._args, - **self._kwargs) - - def join(self, *args): - Thread.join(self, *args) - return self._return - - -# in beta -class ChainVideoProcessor(ChainImgProcessor): - def __init__(self): - ChainImgProcessor.__init__(self) - - self.video_save_codec = "libx264" - self.video_save_crf = 14 - - def init_with_plugins(self): - self.init_plugins(["core","core_video"]) - self.display_init_info() - - init_on_start_arr = self.init_on_start.split(",") - for proc_id in init_on_start_arr: - self.init_processor(proc_id) - - def run_video_chain(self, source_video, target_video, fps, threads:int = 1, chain = None, params_frame_gen_func = None, video_audio = None): - import cv2 - from tqdm import tqdm - from chain_img_processor.ffmpeg_writer import FFMPEG_VideoWriter # ffmpeg install needed - - cap = cv2.VideoCapture(source_video) - # width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - # height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) - frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - - # first frame do manually - because upscale may happen, we need to estimate width/height - ret, frame = cap.read() - if params_frame_gen_func is not None: - params = params_frame_gen_func(self, frame) - else: - params = {} - params["original_frame"] = frame - frame_processed, params = self.run_chain(frame,params,chain) - height, width, channels = frame_processed.shape - - self.fill_processors_for_thread_chains(threads,chain) - #print(self.processors_objects) - #import threading - #locks:list[threading.Lock] = [] - locks: list[bool] = [] - for i in range(threads): - #locks.append(threading.Lock()) - locks.append(False) - - temp = [] - with FFMPEG_VideoWriter(target_video, (width, height), fps, codec=roop.globals.video_encoder, crf=roop.globals.video_quality, audiofile=video_audio) as output_video_ff: - with tqdm(total=frame_count, desc='Processing', unit="frame", dynamic_ncols=True, - bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]') as progress: - - # do first frame - output_video_ff.write_frame(frame_processed) - progress.update(1) # - cnt_frames = 0 - - # do rest frames - while True: - # getting frame - ret, frame = cap.read() - - if not ret: - break - cnt_frames+=1 - thread_ind = cnt_frames % threads - # we are having an array of length %gpu_threads%, running in parallel - # so if array is equal or longer than gpu threads, waiting - #while len(temp) >= threads: - while locks[thread_ind]: - #print('WAIT', thread_ind) - # we are order dependent, so we are forced to wait for first element to finish. When finished removing thread from the list - frame_processed, params = temp.pop(0).join() - locks[params["_thread_index"]] = False - #print('OFF',cnt_frames,locks[params["_thread_index"]],locks) - # writing into output - output_video_ff.write_frame(frame_processed) - # updating the status - progress.update(1) - - # calc params for frame - if params_frame_gen_func is not None: - params = params_frame_gen_func(self,frame) - else: - params = {} - - # adding new frame to the list and starting it - locks[thread_ind] = True - #print('ON', cnt_frames, thread_ind, locks) - params["original_frame"] = frame - temp.append( - ThreadWithReturnValue(target=self.run_chain, args=(frame, params, chain, thread_ind))) - temp[-1].start() - - while len(temp) > 0: - # we are order dependent, so we are forced to wait for first element to finish. When finished removing thread from the list - frame_processed, params = temp.pop(0).join() - locks[params["_thread_index"]] = False - # writing into output - output_video_ff.write_frame(frame_processed) - - progress.update(1) - - #print("FINAL", locks) - -_video_processor:ChainVideoProcessor = None -def get_single_video_processor() -> ChainVideoProcessor: - global _video_processor - if _video_processor is None: - _video_processor = ChainVideoProcessor() - _video_processor.init_with_plugins() - return _video_processor diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/idna/core.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/idna/core.py deleted file mode 100644 index 4f3003711020eac05ef5a19ab29ba5670d89f642..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/idna/core.py +++ /dev/null @@ -1,400 +0,0 @@ -from . import idnadata -import bisect -import unicodedata -import re -from typing import Union, Optional -from .intranges import intranges_contain - -_virama_combining_class = 9 -_alabel_prefix = b'xn--' -_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]') - -class IDNAError(UnicodeError): - """ Base exception for all IDNA-encoding related problems """ - pass - - -class IDNABidiError(IDNAError): - """ Exception when bidirectional requirements are not satisfied """ - pass - - -class InvalidCodepoint(IDNAError): - """ Exception when a disallowed or unallocated codepoint is used """ - pass - - -class InvalidCodepointContext(IDNAError): - """ Exception when the codepoint is not valid in the context it is used """ - pass - - -def _combining_class(cp: int) -> int: - v = unicodedata.combining(chr(cp)) - if v == 0: - if not unicodedata.name(chr(cp)): - raise ValueError('Unknown character in unicodedata') - return v - -def _is_script(cp: str, script: str) -> bool: - return intranges_contain(ord(cp), idnadata.scripts[script]) - -def _punycode(s: str) -> bytes: - return s.encode('punycode') - -def _unot(s: int) -> str: - return 'U+{:04X}'.format(s) - - -def valid_label_length(label: Union[bytes, str]) -> bool: - if len(label) > 63: - return False - return True - - -def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool: - if len(label) > (254 if trailing_dot else 253): - return False - return True - - -def check_bidi(label: str, check_ltr: bool = False) -> bool: - # Bidi rules should only be applied if string contains RTL characters - bidi_label = False - for (idx, cp) in enumerate(label, 1): - direction = unicodedata.bidirectional(cp) - if direction == '': - # String likely comes from a newer version of Unicode - raise IDNABidiError('Unknown directionality in label {} at position {}'.format(repr(label), idx)) - if direction in ['R', 'AL', 'AN']: - bidi_label = True - if not bidi_label and not check_ltr: - return True - - # Bidi rule 1 - direction = unicodedata.bidirectional(label[0]) - if direction in ['R', 'AL']: - rtl = True - elif direction == 'L': - rtl = False - else: - raise IDNABidiError('First codepoint in label {} must be directionality L, R or AL'.format(repr(label))) - - valid_ending = False - number_type = None # type: Optional[str] - for (idx, cp) in enumerate(label, 1): - direction = unicodedata.bidirectional(cp) - - if rtl: - # Bidi rule 2 - if not direction in ['R', 'AL', 'AN', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']: - raise IDNABidiError('Invalid direction for codepoint at position {} in a right-to-left label'.format(idx)) - # Bidi rule 3 - if direction in ['R', 'AL', 'EN', 'AN']: - valid_ending = True - elif direction != 'NSM': - valid_ending = False - # Bidi rule 4 - if direction in ['AN', 'EN']: - if not number_type: - number_type = direction - else: - if number_type != direction: - raise IDNABidiError('Can not mix numeral types in a right-to-left label') - else: - # Bidi rule 5 - if not direction in ['L', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']: - raise IDNABidiError('Invalid direction for codepoint at position {} in a left-to-right label'.format(idx)) - # Bidi rule 6 - if direction in ['L', 'EN']: - valid_ending = True - elif direction != 'NSM': - valid_ending = False - - if not valid_ending: - raise IDNABidiError('Label ends with illegal codepoint directionality') - - return True - - -def check_initial_combiner(label: str) -> bool: - if unicodedata.category(label[0])[0] == 'M': - raise IDNAError('Label begins with an illegal combining character') - return True - - -def check_hyphen_ok(label: str) -> bool: - if label[2:4] == '--': - raise IDNAError('Label has disallowed hyphens in 3rd and 4th position') - if label[0] == '-' or label[-1] == '-': - raise IDNAError('Label must not start or end with a hyphen') - return True - - -def check_nfc(label: str) -> None: - if unicodedata.normalize('NFC', label) != label: - raise IDNAError('Label must be in Normalization Form C') - - -def valid_contextj(label: str, pos: int) -> bool: - cp_value = ord(label[pos]) - - if cp_value == 0x200c: - - if pos > 0: - if _combining_class(ord(label[pos - 1])) == _virama_combining_class: - return True - - ok = False - for i in range(pos-1, -1, -1): - joining_type = idnadata.joining_types.get(ord(label[i])) - if joining_type == ord('T'): - continue - if joining_type in [ord('L'), ord('D')]: - ok = True - break - - if not ok: - return False - - ok = False - for i in range(pos+1, len(label)): - joining_type = idnadata.joining_types.get(ord(label[i])) - if joining_type == ord('T'): - continue - if joining_type in [ord('R'), ord('D')]: - ok = True - break - return ok - - if cp_value == 0x200d: - - if pos > 0: - if _combining_class(ord(label[pos - 1])) == _virama_combining_class: - return True - return False - - else: - - return False - - -def valid_contexto(label: str, pos: int, exception: bool = False) -> bool: - cp_value = ord(label[pos]) - - if cp_value == 0x00b7: - if 0 < pos < len(label)-1: - if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c: - return True - return False - - elif cp_value == 0x0375: - if pos < len(label)-1 and len(label) > 1: - return _is_script(label[pos + 1], 'Greek') - return False - - elif cp_value == 0x05f3 or cp_value == 0x05f4: - if pos > 0: - return _is_script(label[pos - 1], 'Hebrew') - return False - - elif cp_value == 0x30fb: - for cp in label: - if cp == '\u30fb': - continue - if _is_script(cp, 'Hiragana') or _is_script(cp, 'Katakana') or _is_script(cp, 'Han'): - return True - return False - - elif 0x660 <= cp_value <= 0x669: - for cp in label: - if 0x6f0 <= ord(cp) <= 0x06f9: - return False - return True - - elif 0x6f0 <= cp_value <= 0x6f9: - for cp in label: - if 0x660 <= ord(cp) <= 0x0669: - return False - return True - - return False - - -def check_label(label: Union[str, bytes, bytearray]) -> None: - if isinstance(label, (bytes, bytearray)): - label = label.decode('utf-8') - if len(label) == 0: - raise IDNAError('Empty Label') - - check_nfc(label) - check_hyphen_ok(label) - check_initial_combiner(label) - - for (pos, cp) in enumerate(label): - cp_value = ord(cp) - if intranges_contain(cp_value, idnadata.codepoint_classes['PVALID']): - continue - elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTJ']): - try: - if not valid_contextj(label, pos): - raise InvalidCodepointContext('Joiner {} not allowed at position {} in {}'.format( - _unot(cp_value), pos+1, repr(label))) - except ValueError: - raise IDNAError('Unknown codepoint adjacent to joiner {} at position {} in {}'.format( - _unot(cp_value), pos+1, repr(label))) - elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTO']): - if not valid_contexto(label, pos): - raise InvalidCodepointContext('Codepoint {} not allowed at position {} in {}'.format(_unot(cp_value), pos+1, repr(label))) - else: - raise InvalidCodepoint('Codepoint {} at position {} of {} not allowed'.format(_unot(cp_value), pos+1, repr(label))) - - check_bidi(label) - - -def alabel(label: str) -> bytes: - try: - label_bytes = label.encode('ascii') - ulabel(label_bytes) - if not valid_label_length(label_bytes): - raise IDNAError('Label too long') - return label_bytes - except UnicodeEncodeError: - pass - - if not label: - raise IDNAError('No Input') - - label = str(label) - check_label(label) - label_bytes = _punycode(label) - label_bytes = _alabel_prefix + label_bytes - - if not valid_label_length(label_bytes): - raise IDNAError('Label too long') - - return label_bytes - - -def ulabel(label: Union[str, bytes, bytearray]) -> str: - if not isinstance(label, (bytes, bytearray)): - try: - label_bytes = label.encode('ascii') - except UnicodeEncodeError: - check_label(label) - return label - else: - label_bytes = label - - label_bytes = label_bytes.lower() - if label_bytes.startswith(_alabel_prefix): - label_bytes = label_bytes[len(_alabel_prefix):] - if not label_bytes: - raise IDNAError('Malformed A-label, no Punycode eligible content found') - if label_bytes.decode('ascii')[-1] == '-': - raise IDNAError('A-label must not end with a hyphen') - else: - check_label(label_bytes) - return label_bytes.decode('ascii') - - try: - label = label_bytes.decode('punycode') - except UnicodeError: - raise IDNAError('Invalid A-label') - check_label(label) - return label - - -def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str: - """Re-map the characters in the string according to UTS46 processing.""" - from .uts46data import uts46data - output = '' - - for pos, char in enumerate(domain): - code_point = ord(char) - try: - uts46row = uts46data[code_point if code_point < 256 else - bisect.bisect_left(uts46data, (code_point, 'Z')) - 1] - status = uts46row[1] - replacement = None # type: Optional[str] - if len(uts46row) == 3: - replacement = uts46row[2] # type: ignore - if (status == 'V' or - (status == 'D' and not transitional) or - (status == '3' and not std3_rules and replacement is None)): - output += char - elif replacement is not None and (status == 'M' or - (status == '3' and not std3_rules) or - (status == 'D' and transitional)): - output += replacement - elif status != 'I': - raise IndexError() - except IndexError: - raise InvalidCodepoint( - 'Codepoint {} not allowed at position {} in {}'.format( - _unot(code_point), pos + 1, repr(domain))) - - return unicodedata.normalize('NFC', output) - - -def encode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False, transitional: bool = False) -> bytes: - if isinstance(s, (bytes, bytearray)): - try: - s = s.decode('ascii') - except UnicodeDecodeError: - raise IDNAError('should pass a unicode string to the function rather than a byte string.') - if uts46: - s = uts46_remap(s, std3_rules, transitional) - trailing_dot = False - result = [] - if strict: - labels = s.split('.') - else: - labels = _unicode_dots_re.split(s) - if not labels or labels == ['']: - raise IDNAError('Empty domain') - if labels[-1] == '': - del labels[-1] - trailing_dot = True - for label in labels: - s = alabel(label) - if s: - result.append(s) - else: - raise IDNAError('Empty label') - if trailing_dot: - result.append(b'') - s = b'.'.join(result) - if not valid_string_length(s, trailing_dot): - raise IDNAError('Domain too long') - return s - - -def decode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False) -> str: - try: - if isinstance(s, (bytes, bytearray)): - s = s.decode('ascii') - except UnicodeDecodeError: - raise IDNAError('Invalid ASCII in A-label') - if uts46: - s = uts46_remap(s, std3_rules, False) - trailing_dot = False - result = [] - if not strict: - labels = _unicode_dots_re.split(s) - else: - labels = s.split('.') - if not labels or labels == ['']: - raise IDNAError('Empty domain') - if not labels[-1]: - del labels[-1] - trailing_dot = True - for label in labels: - s = ulabel(label) - if s: - result.append(s) - else: - raise IDNAError('Empty label') - if trailing_dot: - result.append('') - return '.'.join(result) diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/resolvelib/providers.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/resolvelib/providers.py deleted file mode 100644 index e99d87ee75f6f665989a109828e07ef81cb3410c..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/pip/_vendor/resolvelib/providers.py +++ /dev/null @@ -1,133 +0,0 @@ -class AbstractProvider(object): - """Delegate class to provide the required interface for the resolver.""" - - def identify(self, requirement_or_candidate): - """Given a requirement, return an identifier for it. - - This is used to identify a requirement, e.g. whether two requirements - should have their specifier parts merged. - """ - raise NotImplementedError - - def get_preference( - self, - identifier, - resolutions, - candidates, - information, - backtrack_causes, - ): - """Produce a sort key for given requirement based on preference. - - The preference is defined as "I think this requirement should be - resolved first". The lower the return value is, the more preferred - this group of arguments is. - - :param identifier: An identifier as returned by ``identify()``. This - identifies the dependency matches which should be returned. - :param resolutions: Mapping of candidates currently pinned by the - resolver. Each key is an identifier, and the value is a candidate. - The candidate may conflict with requirements from ``information``. - :param candidates: Mapping of each dependency's possible candidates. - Each value is an iterator of candidates. - :param information: Mapping of requirement information of each package. - Each value is an iterator of *requirement information*. - :param backtrack_causes: Sequence of requirement information that were - the requirements that caused the resolver to most recently backtrack. - - A *requirement information* instance is a named tuple with two members: - - * ``requirement`` specifies a requirement contributing to the current - list of candidates. - * ``parent`` specifies the candidate that provides (depended on) the - requirement, or ``None`` to indicate a root requirement. - - The preference could depend on various issues, including (not - necessarily in this order): - - * Is this package pinned in the current resolution result? - * How relaxed is the requirement? Stricter ones should probably be - worked on first? (I don't know, actually.) - * How many possibilities are there to satisfy this requirement? Those - with few left should likely be worked on first, I guess? - * Are there any known conflicts for this requirement? We should - probably work on those with the most known conflicts. - - A sortable value should be returned (this will be used as the ``key`` - parameter of the built-in sorting function). The smaller the value is, - the more preferred this requirement is (i.e. the sorting function - is called with ``reverse=False``). - """ - raise NotImplementedError - - def find_matches(self, identifier, requirements, incompatibilities): - """Find all possible candidates that satisfy the given constraints. - - :param identifier: An identifier as returned by ``identify()``. This - identifies the dependency matches of which should be returned. - :param requirements: A mapping of requirements that all returned - candidates must satisfy. Each key is an identifier, and the value - an iterator of requirements for that dependency. - :param incompatibilities: A mapping of known incompatibilities of - each dependency. Each key is an identifier, and the value an - iterator of incompatibilities known to the resolver. All - incompatibilities *must* be excluded from the return value. - - This should try to get candidates based on the requirements' types. - For VCS, local, and archive requirements, the one-and-only match is - returned, and for a "named" requirement, the index(es) should be - consulted to find concrete candidates for this requirement. - - The return value should produce candidates ordered by preference; the - most preferred candidate should come first. The return type may be one - of the following: - - * A callable that returns an iterator that yields candidates. - * An collection of candidates. - * An iterable of candidates. This will be consumed immediately into a - list of candidates. - """ - raise NotImplementedError - - def is_satisfied_by(self, requirement, candidate): - """Whether the given requirement can be satisfied by a candidate. - - The candidate is guaranteed to have been generated from the - requirement. - - A boolean should be returned to indicate whether ``candidate`` is a - viable solution to the requirement. - """ - raise NotImplementedError - - def get_dependencies(self, candidate): - """Get dependencies of a candidate. - - This should return a collection of requirements that `candidate` - specifies as its dependencies. - """ - raise NotImplementedError - - -class AbstractResolver(object): - """The thing that performs the actual resolution work.""" - - base_exception = Exception - - def __init__(self, provider, reporter): - self.provider = provider - self.reporter = reporter - - def resolve(self, requirements, **kwargs): - """Take a collection of constraints, spit out the resolution result. - - This returns a representation of the final resolution state, with one - guarenteed attribute ``mapping`` that contains resolved candidates as - values. The keys are their respective identifiers. - - :param requirements: A collection of constraints. - :param kwargs: Additional keyword arguments that subclasses may accept. - - :raises: ``self.base_exception`` or its subclass. - """ - raise NotImplementedError diff --git a/spaces/TandCAcceptMe/face-swap-docker/roop/face_analyser.py b/spaces/TandCAcceptMe/face-swap-docker/roop/face_analyser.py deleted file mode 100644 index bec0088f270ab6f06b6cdffd695f597e13a5ee95..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/roop/face_analyser.py +++ /dev/null @@ -1,65 +0,0 @@ -import threading -from typing import Any -import insightface - -import roop.globals -from roop.typing import Frame -import cv2 -from PIL import Image -from roop.capturer import get_video_frame - -FACE_ANALYSER = None -THREAD_LOCK = threading.Lock() - - -def get_face_analyser() -> Any: - global FACE_ANALYSER - - with THREAD_LOCK: - if FACE_ANALYSER is None: - FACE_ANALYSER = insightface.app.FaceAnalysis(name='buffalo_l', providers=roop.globals.execution_providers) - FACE_ANALYSER.prepare(ctx_id=0, det_size=(640, 640)) - return FACE_ANALYSER - - -def get_first_face(frame: Frame) -> Any: - faces = get_face_analyser().get(frame) - try: - return min(faces, key=lambda x: x.bbox[0]) - # return sorted(faces, reverse=True, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))[0] - except ValueError: - return None - - -def get_all_faces(frame: Frame) -> Any: - try: - faces = get_face_analyser().get(frame) - return sorted(faces, key = lambda x : x.bbox[0]) - except IndexError: - return None - -def extract_face_images(source_filename, video_info): - face_data = [] - source_image = None - - if video_info[0]: - frame = get_video_frame(source_filename, video_info[1]) - if frame is not None: - source_image = frame - else: - return face_data - else: - source_image = cv2.imread(source_filename) - - - faces = get_all_faces(source_image) - - i = 0 - for face in faces: - (startX, startY, endX, endY) = face['bbox'].astype("int") - face_temp = source_image[startY:endY, startX:endX] - if face_temp.size < 1: - continue - i += 1 - face_data.append([face, face_temp]) - return face_data \ No newline at end of file diff --git a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/configs/common/models/panoptic_fpn.py b/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/configs/common/models/panoptic_fpn.py deleted file mode 100644 index 88f55d2ce9db62e61445d6a3700067d9d864ecae..0000000000000000000000000000000000000000 --- a/spaces/TencentARC/VLog/models/grit_src/third_party/CenterNet2/configs/common/models/panoptic_fpn.py +++ /dev/null @@ -1,20 +0,0 @@ -from detectron2.config import LazyCall as L -from detectron2.layers import ShapeSpec -from detectron2.modeling import PanopticFPN -from detectron2.modeling.meta_arch.semantic_seg import SemSegFPNHead - -from .mask_rcnn_fpn import model - -model._target_ = PanopticFPN -model.sem_seg_head = L(SemSegFPNHead)( - input_shape={ - f: L(ShapeSpec)(stride=s, channels="${....backbone.out_channels}") - for f, s in zip(["p2", "p3", "p4", "p5"], [4, 8, 16, 32]) - }, - ignore_value=255, - num_classes=54, # COCO stuff + 1 - conv_dims=128, - common_stride=4, - loss_weight=0.5, - norm="GN", -) diff --git a/spaces/UjjwalVIT/Text_analysis_and_metadata_app/stanfordmodel/NERDemo.java b/spaces/UjjwalVIT/Text_analysis_and_metadata_app/stanfordmodel/NERDemo.java deleted file mode 100644 index 73e6ed1540bba3e8728992dcbb22fd7fe2388614..0000000000000000000000000000000000000000 --- a/spaces/UjjwalVIT/Text_analysis_and_metadata_app/stanfordmodel/NERDemo.java +++ /dev/null @@ -1,171 +0,0 @@ -import edu.stanford.nlp.ie.AbstractSequenceClassifier; -import edu.stanford.nlp.ie.crf.*; -import edu.stanford.nlp.io.IOUtils; -import edu.stanford.nlp.ling.CoreLabel; -import edu.stanford.nlp.ling.CoreAnnotations; -import edu.stanford.nlp.sequences.DocumentReaderAndWriter; -import edu.stanford.nlp.util.Triple; - -import java.util.List; - - -/** This is a demo of calling CRFClassifier programmatically. - *

- * Usage: {@code java -mx400m -cp "*" NERDemo [serializedClassifier [fileName]] } - *

- * If arguments aren't specified, they default to - * classifiers/english.all.3class.distsim.crf.ser.gz and some hardcoded sample text. - * If run with arguments, it shows some of the ways to get k-best labelings and - * probabilities out with CRFClassifier. If run without arguments, it shows some of - * the alternative output formats that you can get. - *

- * To use CRFClassifier from the command line: - *

- * {@code java -mx400m edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier [classifier] -textFile [file] } - *

- * Or if the file is already tokenized and one word per line, perhaps in - * a tab-separated value format with extra columns for part-of-speech tag, - * etc., use the version below (note the 's' instead of the 'x'): - *

- * {@code java -mx400m edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier [classifier] -testFile [file] } - *
- * - * @author Jenny Finkel - * @author Christopher Manning - */ - -public class NERDemo { - - public static void main(String[] args) throws Exception { - - String serializedClassifier = "classifiers/english.all.3class.distsim.crf.ser.gz"; - - if (args.length > 0) { - serializedClassifier = args[0]; - } - - AbstractSequenceClassifier classifier = CRFClassifier.getClassifier(serializedClassifier); - - /* For either a file to annotate or for the hardcoded text example, this - demo file shows several ways to process the input, for teaching purposes. - */ - - if (args.length > 1) { - - /* For the file, it shows (1) how to run NER on a String, (2) how - to get the entities in the String with character offsets, and - (3) how to run NER on a whole file (without loading it into a String). - */ - - String fileContents = IOUtils.slurpFile(args[1]); - List> out = classifier.classify(fileContents); - for (List sentence : out) { - for (CoreLabel word : sentence) { - System.out.print(word.word() + '/' + word.get(CoreAnnotations.AnswerAnnotation.class) + ' '); - } - System.out.println(); - } - - System.out.println("---"); - out = classifier.classifyFile(args[1]); - for (List sentence : out) { - for (CoreLabel word : sentence) { - System.out.print(word.word() + '/' + word.get(CoreAnnotations.AnswerAnnotation.class) + ' '); - } - System.out.println(); - } - - System.out.println("---"); - List> list = classifier.classifyToCharacterOffsets(fileContents); - for (Triple item : list) { - System.out.println(item.first() + ": " + fileContents.substring(item.second(), item.third())); - } - System.out.println("---"); - System.out.println("Ten best entity labelings"); - DocumentReaderAndWriter readerAndWriter = classifier.makePlainTextReaderAndWriter(); - classifier.classifyAndWriteAnswersKBest(args[1], 10, readerAndWriter); - - System.out.println("---"); - System.out.println("Per-token marginalized probabilities"); - classifier.printProbs(args[1], readerAndWriter); - - // -- This code prints out the first order (token pair) clique probabilities. - // -- But that output is a bit overwhelming, so we leave it commented out by default. - // System.out.println("---"); - // System.out.println("First Order Clique Probabilities"); - // ((CRFClassifier) classifier).printFirstOrderProbs(args[1], readerAndWriter); - - } else { - - /* For the hard-coded String, it shows how to run it on a single - sentence, and how to do this and produce several formats, including - slash tags and an inline XML output format. It also shows the full - contents of the {@code CoreLabel}s that are constructed by the - classifier. And it shows getting out the probabilities of different - assignments and an n-best list of classifications with probabilities. - */ - - String[] example = {"Good afternoon Rajat Raina, how are you today?", - "I go to school at Stanford University, which is located in California." }; - for (String str : example) { - System.out.println(classifier.classifyToString(str)); - } - System.out.println("---"); - - for (String str : example) { - // This one puts in spaces and newlines between tokens, so just print not println. - System.out.print(classifier.classifyToString(str, "slashTags", false)); - } - System.out.println("---"); - - for (String str : example) { - // This one is best for dealing with the output as a TSV (tab-separated column) file. - // The first column gives entities, the second their classes, and the third the remaining text in a document - System.out.print(classifier.classifyToString(str, "tabbedEntities", false)); - } - System.out.println("---"); - - for (String str : example) { - System.out.println(classifier.classifyWithInlineXML(str)); - } - System.out.println("---"); - - for (String str : example) { - System.out.println(classifier.classifyToString(str, "xml", true)); - } - System.out.println("---"); - - for (String str : example) { - System.out.print(classifier.classifyToString(str, "tsv", false)); - } - System.out.println("---"); - - // This gets out entities with character offsets - int j = 0; - for (String str : example) { - j++; - List> triples = classifier.classifyToCharacterOffsets(str); - for (Triple trip : triples) { - System.out.printf("%s over character offsets [%d, %d) in sentence %d.%n", - trip.first(), trip.second(), trip.third, j); - } - } - System.out.println("---"); - - // This prints out all the details of what is stored for each token - int i=0; - for (String str : example) { - for (List lcl : classifier.classify(str)) { - for (CoreLabel cl : lcl) { - System.out.print(i++ + ": "); - System.out.println(cl.toShorterString()); - } - } - } - - System.out.println("---"); - - } - } - -} diff --git a/spaces/VIPLab/Caption-Anything/caption_anything/text_refiner/__init__.py b/spaces/VIPLab/Caption-Anything/caption_anything/text_refiner/__init__.py deleted file mode 100644 index 853c07b880c00c5336b9f1e4e3c1f5e8d4c2ca74..0000000000000000000000000000000000000000 --- a/spaces/VIPLab/Caption-Anything/caption_anything/text_refiner/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from .text_refiner import TextRefiner - - -def build_text_refiner(type, device, args=None, api_key=""): - if type == 'base': - return TextRefiner(device, api_key) \ No newline at end of file diff --git a/spaces/Vinnybustacap/Gryphe-MythoLogic-13b/README.md b/spaces/Vinnybustacap/Gryphe-MythoLogic-13b/README.md deleted file mode 100644 index 096e45664aaf69d0b20655607a3d1ea1826060a9..0000000000000000000000000000000000000000 --- a/spaces/Vinnybustacap/Gryphe-MythoLogic-13b/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Gryphe MythoLogic 13b -emoji: 😻 -colorFrom: gray -colorTo: pink -sdk: gradio -sdk_version: 3.36.1 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Woocy/541GPT/config.py b/spaces/Woocy/541GPT/config.py deleted file mode 100644 index 4c67f00031bc42394312237ae01f4cd1611b1e46..0000000000000000000000000000000000000000 --- a/spaces/Woocy/541GPT/config.py +++ /dev/null @@ -1,187 +0,0 @@ - -from collections import defaultdict -from contextlib import contextmanager -import os -import logging -import sys -import commentjson as json - - -from shared import * -from presets import * - -__all__ = [ - "my_api_key", - "authflag", - "auth_list", - "dockerflag", - "retrieve_proxy", - "log_level", - "advance_docs", - "update_doc_config", - "render_latex", - "usage_limit", - "multi_api_key", - "server_name", - "server_port", - "share", - "hide_history_when_not_logged_in" -] - -# 添加一个统一的config文件,避免文件过多造成的疑惑(优先级最低) -# 同时,也可以为后续支持自定义功能提供config的帮助 -if os.path.exists("config.json"): - with open("config.json", "r", encoding='utf-8') as f: - config = json.load(f) -else: - config = {} - -lang_config = config.get("language", "auto") -language = os.environ.get("LANGUAGE", lang_config) - -hide_history_when_not_logged_in = config.get("hide_history_when_not_logged_in", False) - -if os.path.exists("api_key.txt"): - logging.info("检测到api_key.txt文件,正在进行迁移...") - with open("api_key.txt", "r") as f: - config["openai_api_key"] = f.read().strip() - os.rename("api_key.txt", "api_key(deprecated).txt") - with open("config.json", "w", encoding='utf-8') as f: - json.dump(config, f, indent=4) - -if os.path.exists("auth.json"): - logging.info("检测到auth.json文件,正在进行迁移...") - auth_list = [] - with open("auth.json", "r", encoding='utf-8') as f: - auth = json.load(f) - for _ in auth: - if auth[_]["username"] and auth[_]["password"]: - auth_list.append((auth[_]["username"], auth[_]["password"])) - else: - logging.error("请检查auth.json文件中的用户名和密码!") - sys.exit(1) - config["users"] = auth_list - os.rename("auth.json", "auth(deprecated).json") - with open("config.json", "w", encoding='utf-8') as f: - json.dump(config, f, indent=4) - -## 处理docker if we are running in Docker -dockerflag = config.get("dockerflag", False) -if os.environ.get("dockerrun") == "yes": - dockerflag = True - -## 处理 api-key 以及 允许的用户列表 -my_api_key = config.get("openai_api_key", "") -my_api_key = os.environ.get("OPENAI_API_KEY", my_api_key) - -xmchat_api_key = config.get("xmchat_api_key", "") -os.environ["XMCHAT_API_KEY"] = xmchat_api_key - -render_latex = config.get("render_latex", True) - -if render_latex: - os.environ["RENDER_LATEX"] = "yes" -else: - os.environ["RENDER_LATEX"] = "no" - -usage_limit = os.environ.get("USAGE_LIMIT", config.get("usage_limit", 120)) - -## 多账户机制 -multi_api_key = config.get("multi_api_key", False) # 是否开启多账户机制 -if multi_api_key: - api_key_list = config.get("api_key_list", []) - if len(api_key_list) == 0: - logging.error("多账号模式已开启,但api_key_list为空,请检查config.json") - sys.exit(1) - shared.state.set_api_key_queue(api_key_list) - -auth_list = config.get("users", []) # 实际上是使用者的列表 -authflag = len(auth_list) > 0 # 是否开启认证的状态值,改为判断auth_list长度 - -# 处理自定义的api_host,优先读环境变量的配置,如果存在则自动装配 -api_host = os.environ.get("api_host", config.get("api_host", "")) -if api_host: - shared.state.set_api_host(api_host) - -@contextmanager -def retrieve_openai_api(api_key = None): - old_api_key = os.environ.get("OPENAI_API_KEY", "") - if api_key is None: - os.environ["OPENAI_API_KEY"] = my_api_key - yield my_api_key - else: - os.environ["OPENAI_API_KEY"] = api_key - yield api_key - os.environ["OPENAI_API_KEY"] = old_api_key - -## 处理log -log_level = config.get("log_level", "INFO") -logging.basicConfig( - level=log_level, - format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s", -) - -## 处理代理: -http_proxy = config.get("http_proxy", "") -https_proxy = config.get("https_proxy", "") -http_proxy = os.environ.get("HTTP_PROXY", http_proxy) -https_proxy = os.environ.get("HTTPS_PROXY", https_proxy) - -# 重置系统变量,在不需要设置的时候不设置环境变量,以免引起全局代理报错 -os.environ["HTTP_PROXY"] = "" -os.environ["HTTPS_PROXY"] = "" - -local_embedding = config.get("local_embedding", False) # 是否使用本地embedding - -@contextmanager -def retrieve_proxy(proxy=None): - """ - 1, 如果proxy = NONE,设置环境变量,并返回最新设置的代理 - 2,如果proxy != NONE,更新当前的代理配置,但是不更新环境变量 - """ - global http_proxy, https_proxy - if proxy is not None: - http_proxy = proxy - https_proxy = proxy - yield http_proxy, https_proxy - else: - old_var = os.environ["HTTP_PROXY"], os.environ["HTTPS_PROXY"] - os.environ["HTTP_PROXY"] = http_proxy - os.environ["HTTPS_PROXY"] = https_proxy - yield http_proxy, https_proxy # return new proxy - - # return old proxy - os.environ["HTTP_PROXY"], os.environ["HTTPS_PROXY"] = old_var - - -## 处理advance docs -advance_docs = defaultdict(lambda: defaultdict(dict)) -advance_docs.update(config.get("advance_docs", {})) -def update_doc_config(two_column_pdf): - global advance_docs - advance_docs["pdf"]["two_column"] = two_column_pdf - - logging.info(f"更新后的文件参数为:{advance_docs}") - -## 处理gradio.launch参数 -server_name = config.get("server_name", None) -server_port = config.get("server_port", None) -if server_name is None: - if dockerflag: - server_name = "0.0.0.0" - else: - server_name = "127.0.0.1" -if server_port is None: - if dockerflag: - server_port = 7860 - -assert server_port is None or type(server_port) == int, "要求port设置为int类型" - -# 设置默认model -default_model = config.get("default_model", "") -try: - presets.DEFAULT_MODEL = presets.MODELS.index(default_model) -except ValueError: - pass - -share = config.get("share", False) diff --git a/spaces/XS-1/BW_IMAGE_VIDEO_COLORIZER/fastai/callbacks/__init__.py b/spaces/XS-1/BW_IMAGE_VIDEO_COLORIZER/fastai/callbacks/__init__.py deleted file mode 100644 index f3032b58f89f954496b10722efcfdd539b5a6725..0000000000000000000000000000000000000000 --- a/spaces/XS-1/BW_IMAGE_VIDEO_COLORIZER/fastai/callbacks/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -from .lr_finder import * -from .one_cycle import * -from .fp16 import * -from .general_sched import * -from .hooks import * -from .mixup import * -from .rnn import * -from .tracker import * -from .csv_logger import * -from .loss_metrics import * -from .oversampling import * diff --git a/spaces/Xenova/semantic-image-search-client/_next/static/chunks/pages/_error-c92d5c4bb2b49926.js b/spaces/Xenova/semantic-image-search-client/_next/static/chunks/pages/_error-c92d5c4bb2b49926.js deleted file mode 100644 index 1ddc2d3f4412562d41ba4f7ffacfb1028e1d4b4c..0000000000000000000000000000000000000000 --- a/spaces/Xenova/semantic-image-search-client/_next/static/chunks/pages/_error-c92d5c4bb2b49926.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[820],{1981:function(n,_,u){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_error",function(){return u(3441)}])}},function(n){n.O(0,[888,774,179],function(){return n(n.s=1981)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/spaces/Xenova/the-tokenizer-playground/assets/worker-a1928d09.js b/spaces/Xenova/the-tokenizer-playground/assets/worker-a1928d09.js deleted file mode 100644 index cced855ff625657b93a766e4f112be073ee6cf45..0000000000000000000000000000000000000000 --- a/spaces/Xenova/the-tokenizer-playground/assets/worker-a1928d09.js +++ /dev/null @@ -1,1790 +0,0 @@ -var fn=Object.defineProperty;var gn=(tt,y,n)=>y in tt?fn(tt,y,{enumerable:!0,configurable:!0,writable:!0,value:n}):tt[y]=n;var jt=(tt,y,n)=>(gn(tt,typeof y!="symbol"?y+"":y,n),n);(function(){var tt;"use strict";function _mergeNamespaces(y,n){return n.forEach(function(u){u&&typeof u!="string"&&!Array.isArray(u)&&Object.keys(u).forEach(function(d){if(d!=="default"&&!(d in y)){var l=Object.getOwnPropertyDescriptor(u,d);Object.defineProperty(y,d,l.get?l:{enumerable:!0,get:function(){return u[d]}})}})}),Object.freeze(y)}function dispatchCallback(y,n){y!==null&&y(n)}function reverseDictionary(y){return Object.fromEntries(Object.entries(y).map(([n,u])=>[u,n]))}function escapeRegExp(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Callable=class{constructor(){let y=function(...n){return y._call(...n)};return Object.setPrototypeOf(y,new.target.prototype)}_call(...y){throw Error("Must implement _call method in subclass")}};function isTypedArray(y){var n,u,d;return((d=(u=(n=y==null?void 0:y.prototype)==null?void 0:n.__proto__)==null?void 0:u.constructor)==null?void 0:d.name)==="TypedArray"}function isIntegralNumber(y){return Number.isInteger(y)||typeof y=="bigint"}function exists(y){return y!=null}function mergeArrays(...y){return Array.prototype.concat.apply([],y)}var sharp={},ONNX_NODE=Object.freeze({__proto__:null,default:sharp});function getDefaultExportFromCjs(y){return y&&y.__esModule&&Object.prototype.hasOwnProperty.call(y,"default")?y.default:y}function getAugmentedNamespace(y){if(y.__esModule)return y;var n=y.default;if(typeof n=="function"){var u=function d(){return this instanceof d?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};u.prototype=n.prototype}else u={};return Object.defineProperty(u,"__esModule",{value:!0}),Object.keys(y).forEach(function(d){var l=Object.getOwnPropertyDescriptor(y,d);Object.defineProperty(u,d,l.get?l:{enumerable:!0,get:function(){return y[d]}})}),u}var ortWeb_min$1={exports:{}};const backends={},backendsSortedByPriority=[],registerBackend=(y,n,u)=>{if(n&&typeof n.init=="function"&&typeof n.createSessionHandler=="function"){const d=backends[y];if(d===void 0)backends[y]={backend:n,priority:u};else{if(d.priority>u)return;if(d.priority===u&&d.backend!==n)throw new Error(`cannot register backend "${y}" using priority ${u}`)}if(u>=0){const l=backendsSortedByPriority.indexOf(y);l!==-1&&backendsSortedByPriority.splice(l,1);for(let p=0;p{const n=y.length===0?backendsSortedByPriority:y,u=[];for(const d of n){const l=backends[d];if(l){if(l.initialized)return l.backend;if(l.aborted)continue;const p=!!l.initPromise;try{return p||(l.initPromise=l.backend.init()),await l.initPromise,l.initialized=!0,l.backend}catch(s){p||u.push({name:d,err:s}),l.aborted=!0}finally{delete l.initPromise}}}throw new Error(`no available backend found. ERR: ${u.map(d=>`[${d.name}] ${d.err}`).join(", ")}`)};class EnvImpl{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);this.logLevelInternal=n}}get logLevel(){return this.logLevelInternal}}const env$1=new EnvImpl,isBigInt64ArrayAvailable=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",isBigUint64ArrayAvailable=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function",NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);isBigInt64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64")),isBigUint64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64"));const calculateSize=y=>{let n=1;for(let u=0;u{const t=document.createElement("canvas"),e=t.getContext("2d");if(!n||!e)return o();const r=new Image;r.crossOrigin="Anonymous",r.src=n,r.onload=()=>{t.width=r.width,t.height=r.height,e.drawImage(r,0,0,t.width,t.height);const i=e.getImageData(0,0,t.width,t.height);if(u!==void 0){if(u.height!==void 0&&u.height!==t.height)throw new Error("Image input config height doesn't match ImageBitmap height");if(f.height=t.height,u.width!==void 0&&u.width!==t.width)throw new Error("Image input config width doesn't match ImageBitmap width");f.width=t.width}else f.height=t.height,f.width=t.width;a(at.bufferToTensor(i.data,f))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(h!==void 0)return at.bufferToTensor(h,f);throw new Error("Input data provided is not supported - aborted tensor creation")}toImageData(n){var u,d;const l=document.createElement("canvas").getContext("2d");let p;if(l!=null){const s=this.dims[3],h=this.dims[2],f=this.dims[1],a=n!==void 0&&n.format!==void 0?n.format:"RGB",o=n!==void 0&&((u=n.norm)===null||u===void 0?void 0:u.mean)!==void 0?n.norm.mean:255,t=n!==void 0&&((d=n.norm)===null||d===void 0?void 0:d.bias)!==void 0?n.norm.bias:0,e=h*s;if(n!==void 0){if(n.height!==void 0&&n.height!==h)throw new Error("Image output config height doesn't match tensor height");if(n.width!==void 0&&n.width!==s)throw new Error("Image output config width doesn't match tensor width");if(n.format!==void 0&&f===4&&n.format!=="RGBA"||f===3&&n.format!=="RGB"&&n.format!=="BGR")throw new Error("Tensor format doesn't match input tensor dims")}const r=4;let i=0,c=1,g=2,m=3,b=0,_=e,w=e*2,v=-1;a==="RGBA"?(b=0,_=e,w=e*2,v=e*3):a==="RGB"?(b=0,_=e,w=e*2):a==="RBG"&&(b=0,w=e,_=e*2),p=l.createImageData(s,h);for(let S=0;S"u")throw new Error(`input '${a}' is missing in 'feeds'.`);if(s)for(const a of this.outputNames)l[a]=null;const h=await this.handler.run(n,l,p),f={};for(const a in h)Object.hasOwnProperty.call(h,a)&&(f[a]=new Tensor$1(h[a].type,h[a].data,h[a].dims));return f}static async create(n,u,d,l){let p,s={};if(typeof n=="string"){if(p=n,typeof u=="object"&&u!==null)s=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(n instanceof Uint8Array){if(p=n,typeof u=="object"&&u!==null)s=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer){const t=n;let e=0,r=n.byteLength;if(typeof u=="object"&&u!==null)s=u;else if(typeof u=="number"){if(e=u,!Number.isSafeInteger(e))throw new RangeError("'byteOffset' must be an integer.");if(e<0||e>=t.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${t.byteLength}).`);if(r=n.byteLength-e,typeof d=="number"){if(r=d,!Number.isSafeInteger(r))throw new RangeError("'byteLength' must be an integer.");if(r<=0||e+r>t.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${t.byteLength-e}].`);if(typeof l=="object"&&l!==null)s=l;else if(typeof l<"u")throw new TypeError("'options' must be an object.")}else if(typeof d<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof u<"u")throw new TypeError("'options' must be an object.");p=new Uint8Array(t,e,r)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const f=(s.executionProviders||[]).map(t=>typeof t=="string"?t:t.name),o=await(await resolveBackend(f)).createSessionHandler(p,s);return new dn(o)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const InferenceSession$1=InferenceSession$2;var lib=Object.freeze({__proto__:null,InferenceSession:InferenceSession$1,Tensor:Tensor$1,env:env$1,registerBackend}),require$$0=getAugmentedNamespace(lib);/*! -* ONNX Runtime Web v1.14.0 -* Copyright (c) Microsoft Corporation. All rights reserved. -* Licensed under the MIT License. -*/(function(module,exports){(function(y,n){module.exports=n(require$$0)})(self,__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(y,n,u)=>{var d,l=(d=(d=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(p){function s(){return X.buffer!=ne&&Ee(X.buffer),me}function h(){return X.buffer!=ne&&Ee(X.buffer),Ie}function f(){return X.buffer!=ne&&Ee(X.buffer),Oe}function a(){return X.buffer!=ne&&Ee(X.buffer),ce}function o(){return X.buffer!=ne&&Ee(X.buffer),Te}var t,e,r;p=p||{},t||(t=p!==void 0?p:{}),t.ready=new Promise(function(x,A){e=x,r=A});var i,c,g,m,b,_,w=Object.assign({},t),v="./this.program",S=(x,A)=>{throw A},O=typeof window=="object",E=typeof importScripts=="function",T=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I=t.ENVIRONMENT_IS_PTHREAD||!1,C="";function B(x){return t.locateFile?t.locateFile(x,C):C+x}if(T){let x;C=E?u(908).dirname(C)+"/":"//",_=()=>{b||(m=u(1384),b=u(908))},i=function(A,k){return _(),A=b.normalize(A),m.readFileSync(A,k?void 0:"utf8")},g=A=>((A=i(A,!0)).buffer||(A=new Uint8Array(A)),A),c=(A,k,M)=>{_(),A=b.normalize(A),m.readFile(A,function(j,V){j?M(j):k(V.buffer)})},1{if(Ve())throw process.exitCode=A,k;k instanceof Ze||z("exiting due to exception: "+k),process.exit(A)},t.inspect=function(){return"[Emscripten Module object]"};try{x=u(9925)}catch(A){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),A}u.g.Worker=x.Worker}else(O||E)&&(E?C=self.location.href:typeof document<"u"&&document.currentScript&&(C=document.currentScript.src),d&&(C=d),C=C.indexOf("blob:")!==0?C.substr(0,C.replace(/[?#].*/,"").lastIndexOf("/")+1):"",T||(i=x=>{var A=new XMLHttpRequest;return A.open("GET",x,!1),A.send(null),A.responseText},E&&(g=x=>{var A=new XMLHttpRequest;return A.open("GET",x,!1),A.responseType="arraybuffer",A.send(null),new Uint8Array(A.response)}),c=(x,A,k)=>{var M=new XMLHttpRequest;M.open("GET",x,!0),M.responseType="arraybuffer",M.onload=()=>{M.status==200||M.status==0&&M.response?A(M.response):k()},M.onerror=k,M.send(null)}));T&&typeof performance>"u"&&(u.g.performance=u(6953).performance);var F=console.log.bind(console),N=console.warn.bind(console);T&&(_(),F=x=>m.writeSync(1,x+` -`),N=x=>m.writeSync(2,x+` -`));var H,$=t.print||F,z=t.printErr||N;Object.assign(t,w),w=null,t.thisProgram&&(v=t.thisProgram),t.quit&&(S=t.quit),t.wasmBinary&&(H=t.wasmBinary);var Q=t.noExitRuntime||!1;typeof WebAssembly!="object"&&pe("no native wasm support detected");var X,te,ne,me,Ie,Oe,ce,Te,_e=!1,Le=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function We(x,A,k){var M=(A>>>=0)+k;for(k=A;x[k]&&!(k>=M);)++k;if(16(j=(240&j)==224?(15&j)<<12|V<<6|K:(7&j)<<18|V<<12|K<<6|63&x[A++])?M+=String.fromCharCode(j):(j-=65536,M+=String.fromCharCode(55296|j>>10,56320|1023&j))}}else M+=String.fromCharCode(j)}return M}function Ae(x,A){return(x>>>=0)?We(h(),x,A):""}function Ce(x,A,k,M){if(!(0>>=0;M=k+M-1;for(var V=0;V=K&&(K=65536+((1023&K)<<10)|1023&x.charCodeAt(++V)),127>=K){if(k>=M)break;A[k++>>>0]=K}else{if(2047>=K){if(k+1>=M)break;A[k++>>>0]=192|K>>6}else{if(65535>=K){if(k+2>=M)break;A[k++>>>0]=224|K>>12}else{if(k+3>=M)break;A[k++>>>0]=240|K>>18,A[k++>>>0]=128|K>>12&63}A[k++>>>0]=128|K>>6&63}A[k++>>>0]=128|63&K}}return A[k>>>0]=0,k-j}function Me(x){for(var A=0,k=0;k=M?A++:2047>=M?A+=2:55296<=M&&57343>=M?(A+=4,++k):A+=3}return A}function Ee(x){ne=x,t.HEAP8=me=new Int8Array(x),t.HEAP16=new Int16Array(x),t.HEAP32=Oe=new Int32Array(x),t.HEAPU8=Ie=new Uint8Array(x),t.HEAPU16=new Uint16Array(x),t.HEAPU32=ce=new Uint32Array(x),t.HEAPF32=new Float32Array(x),t.HEAPF64=Te=new Float64Array(x)}I&&(ne=t.buffer);var ve=t.INITIAL_MEMORY||16777216;if(I)X=t.wasmMemory,ne=t.buffer;else if(t.wasmMemory)X=t.wasmMemory;else if(!((X=new WebAssembly.Memory({initial:ve/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw z("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),T&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");X&&(ne=X.buffer),ve=ne.byteLength,Ee(ne);var je,ze=[],Ue=[],He=[],Ke=[];function Ve(){return Q||!1}function Be(){var x=t.preRun.shift();ze.unshift(x)}var Se,Fe=0,Xe=null;function pe(x){throw I?postMessage({cmd:"onAbort",arg:x}):t.onAbort&&t.onAbort(x),z(x="Aborted("+x+")"),_e=!0,x=new WebAssembly.RuntimeError(x+". Build with -sASSERTIONS for more info."),r(x),x}function ht(){return Se.startsWith("data:application/octet-stream;base64,")}function ut(){var x=Se;try{if(x==Se&&H)return new Uint8Array(H);if(g)return g(x);throw"both async and sync fetching of the wasm failed"}catch(A){pe(A)}}Se="ort-wasm-threaded.wasm",ht()||(Se=B(Se));var Et={};function Ze(x){this.name="ExitStatus",this.message="Program terminated with exit("+x+")",this.status=x}function lt(x){(x=re.Vb[x])||pe(),re.mc(x)}function ct(x){var A=re.Cc();if(!A)return 6;re.ac.push(A),re.Vb[x.Ub]=A,A.Ub=x.Ub;var k={cmd:"run",start_routine:x.Ic,arg:x.zc,pthread_ptr:x.Ub};return A.$b=()=>{k.time=performance.now(),A.postMessage(k,x.Nc)},A.loaded&&(A.$b(),delete A.$b),0}function Ne(x){if(I)return Z(1,1,x);Ve()||(re.oc(),t.onExit&&t.onExit(x),_e=!0),S(x,new Ze(x))}function rt(x,A){if(!A&&I)throw It(x),"unwind";Ve()||I||(Wt(),nt(He),qt(0),Ct[1].length&&Nt(1,10),Ct[2].length&&Nt(2,10),re.oc()),Ne(x)}var re={Yb:[],ac:[],qc:[],Vb:{},fc:function(){I&&re.Ec()},Pc:function(){},Ec:function(){re.receiveObjectTransfer=re.Gc,re.threadInitTLS=re.pc,re.setExitStatus=re.nc,Q=!1},nc:function(){},oc:function(){for(var x of Object.values(re.Vb))re.mc(x);for(x of re.Yb)x.terminate();re.Yb=[]},mc:function(x){var A=x.Ub;delete re.Vb[A],re.Yb.push(x),re.ac.splice(re.ac.indexOf(x),1),x.Ub=0,Ft(A)},Gc:function(){},pc:function(){re.qc.forEach(x=>x())},Fc:function(x,A){x.onmessage=k=>{var M=(k=k.data).cmd;if(x.Ub&&(re.Bc=x.Ub),k.targetThread&&k.targetThread!=Dt()){var j=re.Vb[k.Qc];j?j.postMessage(k,k.transferList):z('Internal error! Worker sent a message "'+M+'" to target pthread '+k.targetThread+", but that thread no longer exists!")}else M==="processProxyingQueue"?L(k.queue):M==="spawnThread"?ct(k):M==="cleanupThread"?lt(k.thread):M==="killThread"?(k=k.thread,M=re.Vb[k],delete re.Vb[k],M.terminate(),Ft(k),re.ac.splice(re.ac.indexOf(M),1),M.Ub=0):M==="cancelThread"?re.Vb[k.thread].postMessage({cmd:"cancel"}):M==="loaded"?(x.loaded=!0,A&&A(x),x.$b&&(x.$b(),delete x.$b)):M==="print"?$("Thread "+k.threadId+": "+k.text):M==="printErr"?z("Thread "+k.threadId+": "+k.text):M==="alert"?alert("Thread "+k.threadId+": "+k.text):k.target==="setimmediate"?x.postMessage(k):M==="onAbort"?t.onAbort&&t.onAbort(k.arg):M&&z("worker sent an unknown command "+M);re.Bc=void 0},x.onerror=k=>{throw z("worker sent an error! "+k.filename+":"+k.lineno+": "+k.message),k},T&&(x.on("message",function(k){x.onmessage({data:k})}),x.on("error",function(k){x.onerror(k)}),x.on("detachedExit",function(){})),x.postMessage({cmd:"load",urlOrBlob:t.mainScriptUrlOrBlob||d,wasmMemory:X,wasmModule:te})},yc:function(){var x=B("ort-wasm-threaded.worker.js");re.Yb.push(new Worker(x))},Cc:function(){return re.Yb.length==0&&(re.yc(),re.Fc(re.Yb[0])),re.Yb.pop()}};function nt(x){for(;0>2>>>0];x=f()[x+48>>2>>>0],Zt(A,A-x),ue(A)};var Qe=[];function ye(x){var A=Qe[x];return A||(x>=Qe.length&&(Qe.length=x+1),Qe[x]=A=je.get(x)),A}t.invokeEntryPoint=function(x,A){x=ye(x)(A),Ve()?re.nc(x):Kt(x)};var it,pt,ot=[],se=0,ie=0;function oe(x){this.Zb=x,this.Sb=x-24,this.xc=function(A){a()[this.Sb+4>>2>>>0]=A},this.bc=function(){return a()[this.Sb+4>>2>>>0]},this.wc=function(A){a()[this.Sb+8>>2>>>0]=A},this.Dc=function(){return a()[this.Sb+8>>2>>>0]},this.rc=function(){f()[this.Sb>>2>>>0]=0},this.hc=function(A){A=A?1:0,s()[this.Sb+12>>0>>>0]=A},this.uc=function(){return s()[this.Sb+12>>0>>>0]!=0},this.ic=function(A){A=A?1:0,s()[this.Sb+13>>0>>>0]=A},this.kc=function(){return s()[this.Sb+13>>0>>>0]!=0},this.fc=function(A,k){this.cc(0),this.xc(A),this.wc(k),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(f(),this.Sb>>2,1)},this.Hc=function(){return Atomics.sub(f(),this.Sb>>2,1)===1},this.cc=function(A){a()[this.Sb+16>>2>>>0]=A},this.tc=function(){return a()[this.Sb+16>>2>>>0]},this.vc=function(){if(Qt(this.bc()))return a()[this.Zb>>2>>>0];var A=this.tc();return A!==0?A:this.Zb}}function ft(x){return Gt(new oe(x).Sb)}function st(x,A,k,M){return I?Z(3,1,x,A,k,M):gt(x,A,k,M)}function gt(x,A,k,M){if(typeof SharedArrayBuffer>"u")return z("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var j=[];return I&&j.length===0?st(x,A,k,M):(x={Ic:k,Ub:x,zc:M,Nc:j},I?(x.Oc="spawnThread",postMessage(x,j),0):ct(x))}function mt(x,A,k){return I?Z(4,1,x,A,k):0}function bt(x,A){if(I)return Z(5,1,x,A)}function yt(x,A){if(I)return Z(6,1,x,A)}function _t(x,A,k){if(I)return Z(7,1,x,A,k)}function wt(x,A,k){return I?Z(8,1,x,A,k):0}function vt(x,A){if(I)return Z(9,1,x,A)}function Tt(x,A,k){if(I)return Z(10,1,x,A,k)}function xt(x,A,k,M){if(I)return Z(11,1,x,A,k,M)}function St(x,A,k,M){if(I)return Z(12,1,x,A,k,M)}function Ot(x,A,k,M){if(I)return Z(13,1,x,A,k,M)}function At(x){if(I)return Z(14,1,x)}function P(x,A){if(I)return Z(15,1,x,A)}function D(x,A,k){if(I)return Z(16,1,x,A,k)}function L(x){Atomics.store(f(),x>>2,1),Dt()&&Yt(x),Atomics.compareExchange(f(),x>>2,1,0)}function R(x){return a()[x>>>2]+4294967296*f()[x+4>>>2]}function U(x,A,k,M,j,V){return I?Z(17,1,x,A,k,M,j,V):-52}function W(x,A,k,M,j,V){if(I)return Z(18,1,x,A,k,M,j,V)}function Y(x){var A=Me(x)+1,k=Lt(A);return k&&Ce(x,s(),k,A),k}function J(x,A,k){function M(fe){return(fe=fe.toTimeString().match(/\(([A-Za-z ]+)\)$/))?fe[1]:"GMT"}if(I)return Z(19,1,x,A,k);var j=new Date().getFullYear(),V=new Date(j,0,1),K=new Date(j,6,1);j=V.getTimezoneOffset();var ee=K.getTimezoneOffset(),he=Math.max(j,ee);f()[x>>2>>>0]=60*he,f()[A>>2>>>0]=+(j!=ee),x=M(V),A=M(K),x=Y(x),A=Y(A),ee>2>>>0]=x,a()[k+4>>2>>>0]=A):(a()[k>>2>>>0]=A,a()[k+4>>2>>>0]=x)}function Z(x,A){var k=arguments.length-2,M=arguments;return Pt(()=>{for(var j=Rt(8*k),V=j>>3,K=0;K>>0]=ee}return Xt(x,k,j,A)})}t.executeNotifiedProxyingQueue=L,pt=T?()=>{var x=process.hrtime();return 1e3*x[0]+x[1]/1e6}:I?()=>performance.now()-t.__performance_now_clock_drift:()=>performance.now();var ae,we=[],$e={};function De(){if(!ae){var x,A={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:v||"./this.program"};for(x in $e)$e[x]===void 0?delete A[x]:A[x]=$e[x];var k=[];for(x in A)k.push(x+"="+A[x]);ae=k}return ae}function G(x,A){if(I)return Z(20,1,x,A);var k=0;return De().forEach(function(M,j){var V=A+k;for(j=a()[x+4*j>>2>>>0]=V,V=0;V>0>>>0]=M.charCodeAt(V);s()[j>>0>>>0]=0,k+=M.length+1}),0}function ge(x,A){if(I)return Z(21,1,x,A);var k=De();a()[x>>2>>>0]=k.length;var M=0;return k.forEach(function(j){M+=j.length+1}),a()[A>>2>>>0]=M,0}function xe(x){return I?Z(22,1,x):52}function Ge(x,A,k,M){return I?Z(23,1,x,A,k,M):52}function Je(x,A,k,M,j){return I?Z(24,1,x,A,k,M,j):70}var Ct=[null,[],[]];function Nt(x,A){var k=Ct[x];A===0||A===10?((x===1?$:z)(We(k,0)),k.length=0):k.push(A)}function Bt(x,A,k,M){if(I)return Z(25,1,x,A,k,M);for(var j=0,V=0;V>2>>>0],ee=a()[A+4>>2>>>0];A+=8;for(var he=0;he>>0]);j+=ee}return a()[M>>2>>>0]=j,0}var Re=0;function kt(x){return x%4==0&&(x%100!=0||x%400==0)}var zt=[31,29,31,30,31,30,31,31,30,31,30,31],Ut=[31,28,31,30,31,30,31,31,30,31,30,31];function Vt(x,A,k,M){function j(q,be,Pe){for(q=typeof q=="number"?q.toString():q||"";q.lengthdt?-1:0et-q.getDate())){q.setDate(q.getDate()+be);break}be-=et-q.getDate()+1,q.setDate(1),11>Pe?q.setMonth(Pe+1):(q.setMonth(0),q.setFullYear(q.getFullYear()+1))}return Pe=new Date(q.getFullYear()+1,0,4),be=ee(new Date(q.getFullYear(),0,4)),Pe=ee(Pe),0>=K(be,q)?0>=K(Pe,q)?q.getFullYear()+1:q.getFullYear():q.getFullYear()-1}var fe=f()[M+40>>2>>>0];for(var ke in M={Lc:f()[M>>2>>>0],Kc:f()[M+4>>2>>>0],dc:f()[M+8>>2>>>0],jc:f()[M+12>>2>>>0],ec:f()[M+16>>2>>>0],Xb:f()[M+20>>2>>>0],Tb:f()[M+24>>2>>>0],Wb:f()[M+28>>2>>>0],Rc:f()[M+32>>2>>>0],Jc:f()[M+36>>2>>>0],Mc:fe?Ae(fe):""},k=Ae(k),fe={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})k=k.replace(new RegExp(ke,"g"),fe[ke]);var Ye="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),qe="January February March April May June July August September October November December".split(" ");for(ke in fe={"%a":function(q){return Ye[q.Tb].substring(0,3)},"%A":function(q){return Ye[q.Tb]},"%b":function(q){return qe[q.ec].substring(0,3)},"%B":function(q){return qe[q.ec]},"%C":function(q){return V((q.Xb+1900)/100|0,2)},"%d":function(q){return V(q.jc,2)},"%e":function(q){return j(q.jc,2," ")},"%g":function(q){return he(q).toString().substring(2)},"%G":function(q){return he(q)},"%H":function(q){return V(q.dc,2)},"%I":function(q){return(q=q.dc)==0?q=12:12q.dc?"AM":"PM"},"%S":function(q){return V(q.Lc,2)},"%t":function(){return" "},"%u":function(q){return q.Tb||7},"%U":function(q){return V(Math.floor((q.Wb+7-q.Tb)/7),2)},"%V":function(q){var be=Math.floor((q.Wb+7-(q.Tb+6)%7)/7);if(2>=(q.Tb+371-q.Wb-2)%7&&be++,be)be==53&&((Pe=(q.Tb+371-q.Wb)%7)==4||Pe==3&&kt(q.Xb)||(be=1));else{be=52;var Pe=(q.Tb+7-q.Wb-1)%7;(Pe==4||Pe==5&&kt(q.Xb%400-1))&&be++}return V(be,2)},"%w":function(q){return q.Tb},"%W":function(q){return V(Math.floor((q.Wb+7-(q.Tb+6)%7)/7),2)},"%y":function(q){return(q.Xb+1900).toString().substring(2)},"%Y":function(q){return q.Xb+1900},"%z":function(q){var be=0<=(q=q.Jc);return q=Math.abs(q)/60,(be?"+":"-")+("0000"+(q/60*100+q%60)).slice(-4)},"%Z":function(q){return q.Mc},"%%":function(){return"%"}},k=k.replace(/%%/g,"\0\0"),fe)k.includes(ke)&&(k=k.replace(new RegExp(ke,"g"),fe[ke](M)));return ke=function(q){var be=Array(Me(q)+1);return Ce(q,be,0,be.length),be}(k=k.replace(/\0\0/g,"%")),ke.length>A?0:(function(q,be){s().set(q,be>>>0)}(ke,x),ke.length-1)}re.fc();var hn=[null,Ne,It,st,mt,bt,yt,_t,wt,vt,Tt,xt,St,Ot,At,P,D,U,W,J,G,ge,xe,Ge,Je,Bt],pn={b:function(x){return Lt(x+24)+24},n:function(x){return(x=new oe(x)).uc()||(x.hc(!0),se--),x.ic(!1),ot.push(x),x.sc(),x.vc()},ma:function(x){throw z("Unexpected exception thrown, this is not properly supported - aborting"),_e=!0,x},x:function(){de(0);var x=ot.pop();if(x.Hc()&&!x.kc()){var A=x.Dc();A&&ye(A)(x.Zb),ft(x.Zb)}ie=0},e:function(){var x=ie;if(!x)return Re=0;var A=new oe(x);A.cc(x);var k=A.bc();if(!k)return Re=0,x;for(var M=Array.prototype.slice.call(arguments),j=0;jL(M));else if(I)postMessage({targetThread:x,cmd:"processProxyingQueue",queue:M});else{if(!(x=re.Vb[x]))return;x.postMessage({cmd:"processProxyingQueue",queue:M})}return 1},Ea:function(){return-1},Pa:function(x,A){x=new Date(1e3*R(x)),f()[A>>2>>>0]=x.getUTCSeconds(),f()[A+4>>2>>>0]=x.getUTCMinutes(),f()[A+8>>2>>>0]=x.getUTCHours(),f()[A+12>>2>>>0]=x.getUTCDate(),f()[A+16>>2>>>0]=x.getUTCMonth(),f()[A+20>>2>>>0]=x.getUTCFullYear()-1900,f()[A+24>>2>>>0]=x.getUTCDay(),x=(x.getTime()-Date.UTC(x.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,f()[A+28>>2>>>0]=x},Qa:function(x,A){x=new Date(1e3*R(x)),f()[A>>2>>>0]=x.getSeconds(),f()[A+4>>2>>>0]=x.getMinutes(),f()[A+8>>2>>>0]=x.getHours(),f()[A+12>>2>>>0]=x.getDate(),f()[A+16>>2>>>0]=x.getMonth(),f()[A+20>>2>>>0]=x.getFullYear()-1900,f()[A+24>>2>>>0]=x.getDay();var k=new Date(x.getFullYear(),0,1),M=(x.getTime()-k.getTime())/864e5|0;f()[A+28>>2>>>0]=M,f()[A+36>>2>>>0]=-60*x.getTimezoneOffset(),M=new Date(x.getFullYear(),6,1).getTimezoneOffset(),x=0|(M!=(k=k.getTimezoneOffset())&&x.getTimezoneOffset()==Math.min(k,M)),f()[A+32>>2>>>0]=x},Ra:function(x){var A=new Date(f()[x+20>>2>>>0]+1900,f()[x+16>>2>>>0],f()[x+12>>2>>>0],f()[x+8>>2>>>0],f()[x+4>>2>>>0],f()[x>>2>>>0],0),k=f()[x+32>>2>>>0],M=A.getTimezoneOffset(),j=new Date(A.getFullYear(),0,1),V=new Date(A.getFullYear(),6,1).getTimezoneOffset(),K=j.getTimezoneOffset(),ee=Math.min(K,V);return 0>k?f()[x+32>>2>>>0]=+(V!=K&&ee==M):0>2>>>0]=A.getDay(),k=(A.getTime()-j.getTime())/864e5|0,f()[x+28>>2>>>0]=k,f()[x>>2>>>0]=A.getSeconds(),f()[x+4>>2>>>0]=A.getMinutes(),f()[x+8>>2>>>0]=A.getHours(),f()[x+12>>2>>>0]=A.getDate(),f()[x+16>>2>>>0]=A.getMonth(),A.getTime()/1e3|0},Aa:U,Ba:W,Sa:function x(A,k,M){x.Ac||(x.Ac=!0,J(A,k,M))},y:function(){pe("")},U:function(){if(!T&&!E){var x="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";it||(it={}),it[x]||(it[x]=1,T&&(x="warning: "+x),z(x))}},ra:function(){return 4294901760},B:pt,Ia:function(x,A,k){h().copyWithin(x>>>0,A>>>0,A+k>>>0)},F:function(){return T?u(3993).cpus().length:navigator.hardwareConcurrency},Da:function(x,A,k){we.length=A,k>>=3;for(var M=0;M>>0];return(0>x?Et[-x-1]:hn[x]).apply(null,we)},qa:function(x){var A=h().length;if((x>>>=0)<=A||4294901760=k;k*=2){var M=A*(1+.2/k);M=Math.min(M,x+100663296);var j=Math;M=Math.max(x,M),j=j.min.call(j,4294901760,M+(65536-M%65536)%65536);e:{try{X.grow(j-ne.byteLength+65535>>>16),Ee(X.buffer);var V=1;break e}catch{}V=void 0}if(V)return!0}return!1},Na:function(){throw"unwind"},Ga:G,Ha:ge,J:rt,I:xe,S:Ge,ga:Je,R:Bt,d:function(){return Re},na:function x(A,k){x.lc||(x.lc=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var j=new Uint8Array(1);return()=>(crypto.getRandomValues(j),j[0])}if(T)try{var V=u(Object(function(){var K=new Error("Cannot find module 'crypto'");throw K.code="MODULE_NOT_FOUND",K}()));return()=>V.randomBytes(1)[0]}catch{}return()=>pe("randomDevice")}());for(var M=0;M>0>>>0]=x.lc();return 0},ia:function(x,A,k){var M=le();try{return ye(x)(A,k)}catch(j){if(ue(M),j!==j+0)throw j;de(1,0)}},ja:function(x,A,k){var M=le();try{return ye(x)(A,k)}catch(j){if(ue(M),j!==j+0)throw j;de(1,0)}},K:function(x){var A=le();try{return ye(x)()}catch(k){if(ue(A),k!==k+0)throw k;de(1,0)}},f:function(x,A){var k=le();try{return ye(x)(A)}catch(M){if(ue(k),M!==M+0)throw M;de(1,0)}},P:function(x,A,k){var M=le();try{return ye(x)(A,k)}catch(j){if(ue(M),j!==j+0)throw j;de(1,0)}},Q:function(x,A,k){var M=le();try{return ye(x)(A,k)}catch(j){if(ue(M),j!==j+0)throw j;de(1,0)}},k:function(x,A,k){var M=le();try{return ye(x)(A,k)}catch(j){if(ue(M),j!==j+0)throw j;de(1,0)}},p:function(x,A,k,M){var j=le();try{return ye(x)(A,k,M)}catch(V){if(ue(j),V!==V+0)throw V;de(1,0)}},q:function(x,A,k,M,j){var V=le();try{return ye(x)(A,k,M,j)}catch(K){if(ue(V),K!==K+0)throw K;de(1,0)}},N:function(x,A,k,M,j,V){var K=le();try{return ye(x)(A,k,M,j,V)}catch(ee){if(ue(K),ee!==ee+0)throw ee;de(1,0)}},s:function(x,A,k,M,j,V){var K=le();try{return ye(x)(A,k,M,j,V)}catch(ee){if(ue(K),ee!==ee+0)throw ee;de(1,0)}},w:function(x,A,k,M,j,V,K){var ee=le();try{return ye(x)(A,k,M,j,V,K)}catch(he){if(ue(ee),he!==he+0)throw he;de(1,0)}},L:function(x,A,k,M,j,V,K,ee){var he=le();try{return ye(x)(A,k,M,j,V,K,ee)}catch(fe){if(ue(he),fe!==fe+0)throw fe;de(1,0)}},E:function(x,A,k,M,j,V,K,ee,he,fe,ke,Ye){var qe=le();try{return ye(x)(A,k,M,j,V,K,ee,he,fe,ke,Ye)}catch(q){if(ue(qe),q!==q+0)throw q;de(1,0)}},aa:function(x,A,k,M,j,V,K,ee){var he=le();try{return un(x,A,k,M,j,V,K,ee)}catch(fe){if(ue(he),fe!==fe+0)throw fe;de(1,0)}},_:function(x,A,k,M,j,V,K){var ee=le();try{return en(x,A,k,M,j,V,K)}catch(he){if(ue(ee),he!==he+0)throw he;de(1,0)}},Z:function(x,A,k,M,j){var V=le();try{return ln(x,A,k,M,j)}catch(K){if(ue(V),K!==K+0)throw K;de(1,0)}},ca:function(x,A,k,M){var j=le();try{return sn(x,A,k,M)}catch(V){if(ue(j),V!==V+0)throw V;de(1,0)}},$:function(x){var A=le();try{return Jt(x)}catch(k){if(ue(A),k!==k+0)throw k;de(1,0)}},ba:function(x,A){var k=le();try{return an(x,A)}catch(M){if(ue(k),M!==M+0)throw M;de(1,0)}},Y:function(x,A,k){var M=le();try{return tn(x,A,k)}catch(j){if(ue(M),j!==j+0)throw j;de(1,0)}},g:function(x){var A=le();try{ye(x)()}catch(k){if(ue(A),k!==k+0)throw k;de(1,0)}},r:function(x,A){var k=le();try{ye(x)(A)}catch(M){if(ue(k),M!==M+0)throw M;de(1,0)}},i:function(x,A,k){var M=le();try{ye(x)(A,k)}catch(j){if(ue(M),j!==j+0)throw j;de(1,0)}},ha:function(x,A,k,M){var j=le();try{ye(x)(A,k,M)}catch(V){if(ue(j),V!==V+0)throw V;de(1,0)}},m:function(x,A,k,M){var j=le();try{ye(x)(A,k,M)}catch(V){if(ue(j),V!==V+0)throw V;de(1,0)}},v:function(x,A,k,M,j){var V=le();try{ye(x)(A,k,M,j)}catch(K){if(ue(V),K!==K+0)throw K;de(1,0)}},u:function(x,A,k,M,j,V){var K=le();try{ye(x)(A,k,M,j,V)}catch(ee){if(ue(K),ee!==ee+0)throw ee;de(1,0)}},O:function(x,A,k,M,j,V,K){var ee=le();try{ye(x)(A,k,M,j,V,K)}catch(he){if(ue(ee),he!==he+0)throw he;de(1,0)}},A:function(x,A,k,M,j,V,K,ee){var he=le();try{ye(x)(A,k,M,j,V,K,ee)}catch(fe){if(ue(he),fe!==fe+0)throw fe;de(1,0)}},ka:function(x,A,k,M,j,V,K,ee,he){var fe=le();try{ye(x)(A,k,M,j,V,K,ee,he)}catch(ke){if(ue(fe),ke!==ke+0)throw ke;de(1,0)}},C:function(x,A,k,M,j,V,K,ee,he,fe,ke){var Ye=le();try{ye(x)(A,k,M,j,V,K,ee,he,fe,ke)}catch(qe){if(ue(Ye),qe!==qe+0)throw qe;de(1,0)}},D:function(x,A,k,M,j,V,K,ee,he,fe,ke,Ye,qe,q,be,Pe){var et=le();try{ye(x)(A,k,M,j,V,K,ee,he,fe,ke,Ye,qe,q,be,Pe)}catch(dt){if(ue(et),dt!==dt+0)throw dt;de(1,0)}},fa:function(x,A,k,M,j,V,K,ee){var he=le();try{nn(x,A,k,M,j,V,K,ee)}catch(fe){if(ue(he),fe!==fe+0)throw fe;de(1,0)}},da:function(x,A,k,M,j,V,K,ee,he,fe,ke,Ye){var qe=le();try{on(x,A,k,M,j,V,K,ee,he,fe,ke,Ye)}catch(q){if(ue(qe),q!==q+0)throw q;de(1,0)}},ea:function(x,A,k,M,j,V){var K=le();try{rn(x,A,k,M,j,V)}catch(ee){if(ue(K),ee!==ee+0)throw ee;de(1,0)}},o:function(x){return x},a:X||t.wasmMemory,G:function(x){Re=x},la:Vt,z:function(x,A,k,M){return Vt(x,A,k,M)}};(function(){function x(j,V){t.asm=j.exports,re.qc.push(t.asm.sb),je=t.asm.ub,Ue.unshift(t.asm.Va),te=V,I||(Fe--,t.monitorRunDependencies&&t.monitorRunDependencies(Fe),Fe==0&&Xe&&(j=Xe,Xe=null,j()))}function A(j){x(j.instance,j.module)}function k(j){return function(){if(!H&&(O||E)){if(typeof fetch=="function"&&!Se.startsWith("file://"))return fetch(Se,{credentials:"same-origin"}).then(function(V){if(!V.ok)throw"failed to load wasm binary file at '"+Se+"'";return V.arrayBuffer()}).catch(function(){return ut()});if(c)return new Promise(function(V,K){c(Se,function(ee){V(new Uint8Array(ee))},K)})}return Promise.resolve().then(function(){return ut()})}().then(function(V){return WebAssembly.instantiate(V,M)}).then(function(V){return V}).then(j,function(V){z("failed to asynchronously prepare wasm: "+V),pe(V)})}var M={a:pn};if(I||(Fe++,t.monitorRunDependencies&&t.monitorRunDependencies(Fe)),t.instantiateWasm)try{return t.instantiateWasm(M,x)}catch(j){return z("Module.instantiateWasm callback failed with error: "+j),!1}(H||typeof WebAssembly.instantiateStreaming!="function"||ht()||Se.startsWith("file://")||T||typeof fetch!="function"?k(A):fetch(Se,{credentials:"same-origin"}).then(function(j){return WebAssembly.instantiateStreaming(j,M).then(A,function(V){return z("wasm streaming compile failed: "+V),z("falling back to ArrayBuffer instantiation"),k(A)})})).catch(r)})(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Va).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.Wa).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.Xa).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.Ya).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.Za).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm._a).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.$a).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.ab).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.bb).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.cb).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm.db).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.eb).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.fb).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.gb).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.hb).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.ib).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.jb).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.kb).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.lb).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.mb).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.nb).apply(null,arguments)};var Dt=t._pthread_self=function(){return(Dt=t._pthread_self=t.asm.ob).apply(null,arguments)},Lt=t._malloc=function(){return(Lt=t._malloc=t.asm.pb).apply(null,arguments)},Gt=t._free=function(){return(Gt=t._free=t.asm.qb).apply(null,arguments)},qt=t._fflush=function(){return(qt=t._fflush=t.asm.rb).apply(null,arguments)};t.__emscripten_tls_init=function(){return(t.__emscripten_tls_init=t.asm.sb).apply(null,arguments)};var Wt=t.___funcs_on_exit=function(){return(Wt=t.___funcs_on_exit=t.asm.tb).apply(null,arguments)},Ht=t.__emscripten_thread_init=function(){return(Ht=t.__emscripten_thread_init=t.asm.vb).apply(null,arguments)};t.__emscripten_thread_crashed=function(){return(t.__emscripten_thread_crashed=t.asm.wb).apply(null,arguments)};var Mt,Xt=t._emscripten_run_in_main_runtime_thread_js=function(){return(Xt=t._emscripten_run_in_main_runtime_thread_js=t.asm.xb).apply(null,arguments)},Yt=t.__emscripten_proxy_execute_task_queue=function(){return(Yt=t.__emscripten_proxy_execute_task_queue=t.asm.yb).apply(null,arguments)},Ft=t.__emscripten_thread_free_data=function(){return(Ft=t.__emscripten_thread_free_data=t.asm.zb).apply(null,arguments)},Kt=t.__emscripten_thread_exit=function(){return(Kt=t.__emscripten_thread_exit=t.asm.Ab).apply(null,arguments)},de=t._setThrew=function(){return(de=t._setThrew=t.asm.Bb).apply(null,arguments)},Zt=t._emscripten_stack_set_limits=function(){return(Zt=t._emscripten_stack_set_limits=t.asm.Cb).apply(null,arguments)},le=t.stackSave=function(){return(le=t.stackSave=t.asm.Db).apply(null,arguments)},ue=t.stackRestore=function(){return(ue=t.stackRestore=t.asm.Eb).apply(null,arguments)},Rt=t.stackAlloc=function(){return(Rt=t.stackAlloc=t.asm.Fb).apply(null,arguments)},$t=t.___cxa_can_catch=function(){return($t=t.___cxa_can_catch=t.asm.Gb).apply(null,arguments)},Qt=t.___cxa_is_pointer_type=function(){return(Qt=t.___cxa_is_pointer_type=t.asm.Hb).apply(null,arguments)},Jt=t.dynCall_j=function(){return(Jt=t.dynCall_j=t.asm.Ib).apply(null,arguments)},en=t.dynCall_iiiiij=function(){return(en=t.dynCall_iiiiij=t.asm.Jb).apply(null,arguments)},tn=t.dynCall_jii=function(){return(tn=t.dynCall_jii=t.asm.Kb).apply(null,arguments)},nn=t.dynCall_viiiiij=function(){return(nn=t.dynCall_viiiiij=t.asm.Lb).apply(null,arguments)},rn=t.dynCall_vjji=function(){return(rn=t.dynCall_vjji=t.asm.Mb).apply(null,arguments)},on=t.dynCall_viiijjjii=function(){return(on=t.dynCall_viiijjjii=t.asm.Nb).apply(null,arguments)},sn=t.dynCall_iij=function(){return(sn=t.dynCall_iij=t.asm.Ob).apply(null,arguments)},an=t.dynCall_ji=function(){return(an=t.dynCall_ji=t.asm.Pb).apply(null,arguments)},un=t.dynCall_iiiiiij=function(){return(un=t.dynCall_iiiiiij=t.asm.Qb).apply(null,arguments)},ln=t.dynCall_iiij=function(){return(ln=t.dynCall_iiij=t.asm.Rb).apply(null,arguments)};function cn(){function x(){if(!Mt&&(Mt=!0,t.calledRun=!0,!_e)&&(I||nt(Ue),e(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),!I)){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;){var A=t.postRun.shift();Ke.unshift(A)}nt(Ke)}}if(!(0{var d,l=(d=(d=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(p){var s,h,f;p=p||{},s||(s=p!==void 0?p:{}),s.ready=new Promise(function(P,D){h=P,f=D});var a,o,t,e,r,i,c=Object.assign({},s),g="./this.program",m=(P,D)=>{throw D},b=typeof window=="object",_=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",v="";w?(v=_?u(908).dirname(v)+"/":"//",i=()=>{r||(e=u(1384),r=u(908))},a=function(P,D){return i(),P=r.normalize(P),e.readFileSync(P,D?void 0:"utf8")},t=P=>((P=a(P,!0)).buffer||(P=new Uint8Array(P)),P),o=(P,D,L)=>{i(),P=r.normalize(P),e.readFile(P,function(R,U){R?L(R):D(U.buffer)})},1{if(T||0{var D=new XMLHttpRequest;return D.open("GET",P,!1),D.send(null),D.responseText},_&&(t=P=>{var D=new XMLHttpRequest;return D.open("GET",P,!1),D.responseType="arraybuffer",D.send(null),new Uint8Array(D.response)}),o=(P,D,L)=>{var R=new XMLHttpRequest;R.open("GET",P,!0),R.responseType="arraybuffer",R.onload=()=>{R.status==200||R.status==0&&R.response?D(R.response):L()},R.onerror=L,R.send(null)});var S,O=s.print||console.log.bind(console),E=s.printErr||console.warn.bind(console);Object.assign(s,c),c=null,s.thisProgram&&(g=s.thisProgram),s.quit&&(m=s.quit),s.wasmBinary&&(S=s.wasmBinary);var T=s.noExitRuntime||!1;typeof WebAssembly!="object"&&Ee("no native wasm support detected");var I,C,B,F,N,H,$=!1,z=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Q(P,D,L){var R=(D>>>=0)+L;for(L=D;P[L]&&!(L>=R);)++L;if(16(U=(240&U)==224?(15&U)<<12|W<<6|Y:(7&U)<<18|W<<12|Y<<6|63&P[D++])?R+=String.fromCharCode(U):(U-=65536,R+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else R+=String.fromCharCode(U)}return R}function X(P,D){return(P>>>=0)?Q(F,P,D):""}function te(P,D,L,R){if(!(0>>=0;R=L+R-1;for(var W=0;W=Y&&(Y=65536+((1023&Y)<<10)|1023&P.charCodeAt(++W)),127>=Y){if(L>=R)break;D[L++>>>0]=Y}else{if(2047>=Y){if(L+1>=R)break;D[L++>>>0]=192|Y>>6}else{if(65535>=Y){if(L+2>=R)break;D[L++>>>0]=224|Y>>12}else{if(L+3>=R)break;D[L++>>>0]=240|Y>>18,D[L++>>>0]=128|Y>>12&63}D[L++>>>0]=128|Y>>6&63}D[L++>>>0]=128|63&Y}}return D[L>>>0]=0,L-U}function ne(P){for(var D=0,L=0;L=R?D++:2047>=R?D+=2:55296<=R&&57343>=R?(D+=4,++L):D+=3}return D}function me(){var P=I.buffer;C=P,s.HEAP8=B=new Int8Array(P),s.HEAP16=new Int16Array(P),s.HEAP32=N=new Int32Array(P),s.HEAPU8=F=new Uint8Array(P),s.HEAPU16=new Uint16Array(P),s.HEAPU32=H=new Uint32Array(P),s.HEAPF32=new Float32Array(P),s.HEAPF64=new Float64Array(P)}var Ie,Oe=[],ce=[],Te=[],_e=[],Le=0;function We(){var P=s.preRun.shift();Oe.unshift(P)}var Ae,Ce=0,Me=null;function Ee(P){throw s.onAbort&&s.onAbort(P),E(P="Aborted("+P+")"),$=!0,P=new WebAssembly.RuntimeError(P+". Build with -sASSERTIONS for more info."),f(P),P}function ve(){return Ae.startsWith("data:application/octet-stream;base64,")}if(Ae="ort-wasm.wasm",!ve()){var je=Ae;Ae=s.locateFile?s.locateFile(je,v):v+je}function ze(){var P=Ae;try{if(P==Ae&&S)return new Uint8Array(S);if(t)return t(P);throw"both async and sync fetching of the wasm failed"}catch(D){Ee(D)}}function Ue(P){this.name="ExitStatus",this.message="Program terminated with exit("+P+")",this.status=P}function He(P){for(;0>2>>>0]=D},this.Eb=function(){return H[this.zb+4>>2>>>0]},this.Sb=function(D){H[this.zb+8>>2>>>0]=D},this.Wb=function(){return H[this.zb+8>>2>>>0]},this.Tb=function(){N[this.zb>>2>>>0]=0},this.Ib=function(D){B[this.zb+12>>0>>>0]=D?1:0},this.Pb=function(){return B[this.zb+12>>0>>>0]!=0},this.Jb=function(D){B[this.zb+13>>0>>>0]=D?1:0},this.Lb=function(){return B[this.zb+13>>0>>>0]!=0},this.Rb=function(D,L){this.Fb(0),this.Ub(D),this.Sb(L),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){N[this.zb>>2>>>0]+=1},this.Xb=function(){var D=N[this.zb>>2>>>0];return N[this.zb>>2>>>0]=D-1,D===1},this.Fb=function(D){H[this.zb+16>>2>>>0]=D},this.Ob=function(){return H[this.zb+16>>2>>>0]},this.Qb=function(){if(gt(this.Eb()))return H[this.Db>>2>>>0];var D=this.Ob();return D!==0?D:this.Db}}function Fe(P){return it(new Se(P).zb)}var Xe=[];function pe(P){var D=Xe[P];return D||(P>=Xe.length&&(Xe.length=P+1),Xe[P]=D=Ie.get(P)),D}function ht(P){var D=ne(P)+1,L=ye(D);return L&&te(P,B,L,D),L}var ut={};function Et(){if(!Ze){var P,D={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:g||"./this.program"};for(P in ut)ut[P]===void 0?delete D[P]:D[P]=ut[P];var L=[];for(P in D)L.push(P+"="+D[P]);Ze=L}return Ze}var Ze,lt=[null,[],[]];function ct(P,D){var L=lt[P];D===0||D===10?((P===1?O:E)(Q(L,0)),L.length=0):L.push(D)}var Ne=0;function rt(P){return P%4==0&&(P%100!=0||P%400==0)}var re=[31,29,31,30,31,30,31,31,30,31,30,31],nt=[31,28,31,30,31,30,31,31,30,31,30,31];function Pt(P,D,L,R){function U(G,ge,xe){for(G=typeof G=="number"?G.toString():G||"";G.lengthJe?-1:0Ge-G.getDate())){G.setDate(G.getDate()+ge);break}ge-=Ge-G.getDate()+1,G.setDate(1),11>xe?G.setMonth(xe+1):(G.setMonth(0),G.setFullYear(G.getFullYear()+1))}return xe=new Date(G.getFullYear()+1,0,4),ge=J(new Date(G.getFullYear(),0,4)),xe=J(xe),0>=Y(ge,G)?0>=Y(xe,G)?G.getFullYear()+1:G.getFullYear():G.getFullYear()-1}var ae=N[R+40>>2>>>0];for(var we in R={$b:N[R>>2>>>0],Zb:N[R+4>>2>>>0],Gb:N[R+8>>2>>>0],Kb:N[R+12>>2>>>0],Hb:N[R+16>>2>>>0],Cb:N[R+20>>2>>>0],Ab:N[R+24>>2>>>0],Bb:N[R+28>>2>>>0],bc:N[R+32>>2>>>0],Yb:N[R+36>>2>>>0],ac:ae?X(ae):""},L=X(L),ae={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})L=L.replace(new RegExp(we,"g"),ae[we]);var $e="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),De="January February March April May June July August September October November December".split(" ");for(we in ae={"%a":function(G){return $e[G.Ab].substring(0,3)},"%A":function(G){return $e[G.Ab]},"%b":function(G){return De[G.Hb].substring(0,3)},"%B":function(G){return De[G.Hb]},"%C":function(G){return W((G.Cb+1900)/100|0,2)},"%d":function(G){return W(G.Kb,2)},"%e":function(G){return U(G.Kb,2," ")},"%g":function(G){return Z(G).toString().substring(2)},"%G":function(G){return Z(G)},"%H":function(G){return W(G.Gb,2)},"%I":function(G){return(G=G.Gb)==0?G=12:12G.Gb?"AM":"PM"},"%S":function(G){return W(G.$b,2)},"%t":function(){return" "},"%u":function(G){return G.Ab||7},"%U":function(G){return W(Math.floor((G.Bb+7-G.Ab)/7),2)},"%V":function(G){var ge=Math.floor((G.Bb+7-(G.Ab+6)%7)/7);if(2>=(G.Ab+371-G.Bb-2)%7&&ge++,ge)ge==53&&((xe=(G.Ab+371-G.Bb)%7)==4||xe==3&&rt(G.Cb)||(ge=1));else{ge=52;var xe=(G.Ab+7-G.Bb-1)%7;(xe==4||xe==5&&rt(G.Cb%400-1))&&ge++}return W(ge,2)},"%w":function(G){return G.Ab},"%W":function(G){return W(Math.floor((G.Bb+7-(G.Ab+6)%7)/7),2)},"%y":function(G){return(G.Cb+1900).toString().substring(2)},"%Y":function(G){return G.Cb+1900},"%z":function(G){var ge=0<=(G=G.Yb);return G=Math.abs(G)/60,(ge?"+":"-")+("0000"+(G/60*100+G%60)).slice(-4)},"%Z":function(G){return G.ac},"%%":function(){return"%"}},L=L.replace(/%%/g,"\0\0"),ae)L.includes(we)&&(L=L.replace(new RegExp(we,"g"),ae[we](R)));return we=function(G){var ge=Array(ne(G)+1);return te(G,ge,0,ge.length),ge}(L=L.replace(/\0\0/g,"%")),we.length>D?0:(B.set(we,P>>>0),we.length-1)}var It={a:function(P){return ye(P+24)+24},m:function(P){return(P=new Se(P)).Pb()||(P.Ib(!0),Ve--),P.Jb(!1),Ke.push(P),P.Nb(),P.Qb()},ia:function(P){throw E("Unexpected exception thrown, this is not properly supported - aborting"),$=!0,P},w:function(){se(0);var P=Ke.pop();if(P.Xb()&&!P.Lb()){var D=P.Wb();D&&pe(D)(P.Db),Fe(P.Db)}Be=0},d:function(){var P=Be;if(!P)return Ne=0;var D=new Se(P);D.Fb(P);var L=D.Eb();if(!L)return Ne=0,P;for(var R=Array.prototype.slice.call(arguments),U=0;U>>2]+4294967296*N[P+4>>>2])),N[D>>2>>>0]=P.getUTCSeconds(),N[D+4>>2>>>0]=P.getUTCMinutes(),N[D+8>>2>>>0]=P.getUTCHours(),N[D+12>>2>>>0]=P.getUTCDate(),N[D+16>>2>>>0]=P.getUTCMonth(),N[D+20>>2>>>0]=P.getUTCFullYear()-1900,N[D+24>>2>>>0]=P.getUTCDay(),N[D+28>>2>>>0]=(P.getTime()-Date.UTC(P.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(P,D){P=new Date(1e3*(H[P>>>2]+4294967296*N[P+4>>>2])),N[D>>2>>>0]=P.getSeconds(),N[D+4>>2>>>0]=P.getMinutes(),N[D+8>>2>>>0]=P.getHours(),N[D+12>>2>>>0]=P.getDate(),N[D+16>>2>>>0]=P.getMonth(),N[D+20>>2>>>0]=P.getFullYear()-1900,N[D+24>>2>>>0]=P.getDay();var L=new Date(P.getFullYear(),0,1);N[D+28>>2>>>0]=(P.getTime()-L.getTime())/864e5|0,N[D+36>>2>>>0]=-60*P.getTimezoneOffset();var R=new Date(P.getFullYear(),6,1).getTimezoneOffset();L=L.getTimezoneOffset(),N[D+32>>2>>>0]=0|(R!=L&&P.getTimezoneOffset()==Math.min(L,R))},Fa:function(P){var D=new Date(N[P+20>>2>>>0]+1900,N[P+16>>2>>>0],N[P+12>>2>>>0],N[P+8>>2>>>0],N[P+4>>2>>>0],N[P>>2>>>0],0),L=N[P+32>>2>>>0],R=D.getTimezoneOffset(),U=new Date(D.getFullYear(),0,1),W=new Date(D.getFullYear(),6,1).getTimezoneOffset(),Y=U.getTimezoneOffset(),J=Math.min(Y,W);return 0>L?N[P+32>>2>>>0]=+(W!=Y&&J==R):0>2>>>0]=D.getDay(),N[P+28>>2>>>0]=(D.getTime()-U.getTime())/864e5|0,N[P>>2>>>0]=D.getSeconds(),N[P+4>>2>>>0]=D.getMinutes(),N[P+8>>2>>>0]=D.getHours(),N[P+12>>2>>>0]=D.getDate(),N[P+16>>2>>>0]=D.getMonth(),D.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function P(D,L,R){P.Vb||(P.Vb=!0,function(U,W,Y){function J(De){return(De=De.toTimeString().match(/\(([A-Za-z ]+)\)$/))?De[1]:"GMT"}var Z=new Date().getFullYear(),ae=new Date(Z,0,1),we=new Date(Z,6,1);Z=ae.getTimezoneOffset();var $e=we.getTimezoneOffset();N[U>>2>>>0]=60*Math.max(Z,$e),N[W>>2>>>0]=+(Z!=$e),U=J(ae),W=J(we),U=ht(U),W=ht(W),$e>2>>>0]=U,H[Y+4>>2>>>0]=W):(H[Y>>2>>>0]=W,H[Y+4>>2>>>0]=U)}(D,L,R))},B:function(){Ee("")},ma:function(){return 4294901760},I:w?()=>{var P=process.hrtime();return 1e3*P[0]+P[1]/1e6}:()=>performance.now(),xa:function(P,D,L){F.copyWithin(P>>>0,D>>>0,D+L>>>0)},G:function(P){var D=F.length;if(4294901760<(P>>>=0))return!1;for(var L=1;4>=L;L*=2){var R=D*(1+.2/L);R=Math.min(R,P+100663296);var U=Math;R=Math.max(P,R),U=U.min.call(U,4294901760,R+(65536-R%65536)%65536);e:{try{I.grow(U-C.byteLength+65535>>>16),me();var W=1;break e}catch{}W=void 0}if(W)return!0}return!1},va:function(P,D){var L=0;return Et().forEach(function(R,U){var W=D+L;for(U=H[P+4*U>>2>>>0]=W,W=0;W>0>>>0]=R.charCodeAt(W);B[U>>0>>>0]=0,L+=R.length+1}),0},wa:function(P,D){var L=Et();H[P>>2>>>0]=L.length;var R=0;return L.forEach(function(U){R+=U.length+1}),H[D>>2>>>0]=R,0},ba:function(P){T||0>2>>>0],J=H[D+4>>2>>>0];D+=8;for(var Z=0;Z>>0]);U+=J}return H[R>>2>>>0]=U,0},c:function(){return Ne},ja:function P(D,L){P.Mb||(P.Mb=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var U=new Uint8Array(1);return()=>(crypto.getRandomValues(U),U[0])}if(w)try{var W=u(Object(function(){var Y=new Error("Cannot find module 'crypto'");throw Y.code="MODULE_NOT_FOUND",Y}()));return()=>W.randomBytes(1)[0]}catch{}return()=>Ee("randomDevice")}());for(var R=0;R>0>>>0]=P.Mb();return 0},ea:function(P,D,L){var R=ie();try{return pe(P)(D,L)}catch(U){if(oe(R),U!==U+0)throw U;se(1,0)}},fa:function(P,D,L){var R=ie();try{return pe(P)(D,L)}catch(U){if(oe(R),U!==U+0)throw U;se(1,0)}},J:function(P){var D=ie();try{return pe(P)()}catch(L){if(oe(D),L!==L+0)throw L;se(1,0)}},e:function(P,D){var L=ie();try{return pe(P)(D)}catch(R){if(oe(L),R!==R+0)throw R;se(1,0)}},N:function(P,D,L){var R=ie();try{return pe(P)(D,L)}catch(U){if(oe(R),U!==U+0)throw U;se(1,0)}},O:function(P,D,L){var R=ie();try{return pe(P)(D,L)}catch(U){if(oe(R),U!==U+0)throw U;se(1,0)}},j:function(P,D,L){var R=ie();try{return pe(P)(D,L)}catch(U){if(oe(R),U!==U+0)throw U;se(1,0)}},o:function(P,D,L,R){var U=ie();try{return pe(P)(D,L,R)}catch(W){if(oe(U),W!==W+0)throw W;se(1,0)}},p:function(P,D,L,R,U){var W=ie();try{return pe(P)(D,L,R,U)}catch(Y){if(oe(W),Y!==Y+0)throw Y;se(1,0)}},M:function(P,D,L,R,U,W){var Y=ie();try{return pe(P)(D,L,R,U,W)}catch(J){if(oe(Y),J!==J+0)throw J;se(1,0)}},r:function(P,D,L,R,U,W){var Y=ie();try{return pe(P)(D,L,R,U,W)}catch(J){if(oe(Y),J!==J+0)throw J;se(1,0)}},v:function(P,D,L,R,U,W,Y){var J=ie();try{return pe(P)(D,L,R,U,W,Y)}catch(Z){if(oe(J),Z!==Z+0)throw Z;se(1,0)}},K:function(P,D,L,R,U,W,Y,J){var Z=ie();try{return pe(P)(D,L,R,U,W,Y,J)}catch(ae){if(oe(Z),ae!==ae+0)throw ae;se(1,0)}},D:function(P,D,L,R,U,W,Y,J,Z,ae,we,$e){var De=ie();try{return pe(P)(D,L,R,U,W,Y,J,Z,ae,we,$e)}catch(G){if(oe(De),G!==G+0)throw G;se(1,0)}},X:function(P,D,L,R,U,W,Y,J){var Z=ie();try{return St(P,D,L,R,U,W,Y,J)}catch(ae){if(oe(Z),ae!==ae+0)throw ae;se(1,0)}},V:function(P,D,L,R,U,W,Y){var J=ie();try{return bt(P,D,L,R,U,W,Y)}catch(Z){if(oe(J),Z!==Z+0)throw Z;se(1,0)}},U:function(P,D,L,R,U){var W=ie();try{return Ot(P,D,L,R,U)}catch(Y){if(oe(W),Y!==Y+0)throw Y;se(1,0)}},Z:function(P,D,L,R){var U=ie();try{return Tt(P,D,L,R)}catch(W){if(oe(U),W!==W+0)throw W;se(1,0)}},W:function(P){var D=ie();try{return mt(P)}catch(L){if(oe(D),L!==L+0)throw L;se(1,0)}},Y:function(P,D){var L=ie();try{return xt(P,D)}catch(R){if(oe(L),R!==R+0)throw R;se(1,0)}},T:function(P,D,L){var R=ie();try{return yt(P,D,L)}catch(U){if(oe(R),U!==U+0)throw U;se(1,0)}},f:function(P){var D=ie();try{pe(P)()}catch(L){if(oe(D),L!==L+0)throw L;se(1,0)}},q:function(P,D){var L=ie();try{pe(P)(D)}catch(R){if(oe(L),R!==R+0)throw R;se(1,0)}},h:function(P,D,L){var R=ie();try{pe(P)(D,L)}catch(U){if(oe(R),U!==U+0)throw U;se(1,0)}},da:function(P,D,L,R){var U=ie();try{pe(P)(D,L,R)}catch(W){if(oe(U),W!==W+0)throw W;se(1,0)}},l:function(P,D,L,R){var U=ie();try{pe(P)(D,L,R)}catch(W){if(oe(U),W!==W+0)throw W;se(1,0)}},t:function(P,D,L,R,U){var W=ie();try{pe(P)(D,L,R,U)}catch(Y){if(oe(W),Y!==Y+0)throw Y;se(1,0)}},u:function(P,D,L,R,U,W){var Y=ie();try{pe(P)(D,L,R,U,W)}catch(J){if(oe(Y),J!==J+0)throw J;se(1,0)}},x:function(P,D,L,R,U,W,Y){var J=ie();try{pe(P)(D,L,R,U,W,Y)}catch(Z){if(oe(J),Z!==Z+0)throw Z;se(1,0)}},z:function(P,D,L,R,U,W,Y,J){var Z=ie();try{pe(P)(D,L,R,U,W,Y,J)}catch(ae){if(oe(Z),ae!==ae+0)throw ae;se(1,0)}},ga:function(P,D,L,R,U,W,Y,J,Z){var ae=ie();try{pe(P)(D,L,R,U,W,Y,J,Z)}catch(we){if(oe(ae),we!==we+0)throw we;se(1,0)}},A:function(P,D,L,R,U,W,Y,J,Z,ae,we){var $e=ie();try{pe(P)(D,L,R,U,W,Y,J,Z,ae,we)}catch(De){if(oe($e),De!==De+0)throw De;se(1,0)}},C:function(P,D,L,R,U,W,Y,J,Z,ae,we,$e,De,G,ge,xe){var Ge=ie();try{pe(P)(D,L,R,U,W,Y,J,Z,ae,we,$e,De,G,ge,xe)}catch(Je){if(oe(Ge),Je!==Je+0)throw Je;se(1,0)}},aa:function(P,D,L,R,U,W,Y,J){var Z=ie();try{_t(P,D,L,R,U,W,Y,J)}catch(ae){if(oe(Z),ae!==ae+0)throw ae;se(1,0)}},_:function(P,D,L,R,U,W,Y,J,Z,ae,we,$e){var De=ie();try{vt(P,D,L,R,U,W,Y,J,Z,ae,we,$e)}catch(G){if(oe(De),G!==G+0)throw G;se(1,0)}},$:function(P,D,L,R,U,W){var Y=ie();try{wt(P,D,L,R,U,W)}catch(J){if(oe(Y),J!==J+0)throw J;se(1,0)}},n:function(P){return P},F:function(P){Ne=P},ha:Pt,y:function(P,D,L,R){return Pt(P,D,L,R)}};(function(){function P(U){s.asm=U.exports,I=s.asm.Ka,me(),Ie=s.asm.ib,ce.unshift(s.asm.La),Ce--,s.monitorRunDependencies&&s.monitorRunDependencies(Ce),Ce==0&&Me&&(U=Me,Me=null,U())}function D(U){P(U.instance)}function L(U){return function(){if(!S&&(b||_)){if(typeof fetch=="function"&&!Ae.startsWith("file://"))return fetch(Ae,{credentials:"same-origin"}).then(function(W){if(!W.ok)throw"failed to load wasm binary file at '"+Ae+"'";return W.arrayBuffer()}).catch(function(){return ze()});if(o)return new Promise(function(W,Y){o(Ae,function(J){W(new Uint8Array(J))},Y)})}return Promise.resolve().then(function(){return ze()})}().then(function(W){return WebAssembly.instantiate(W,R)}).then(function(W){return W}).then(U,function(W){E("failed to asynchronously prepare wasm: "+W),Ee(W)})}var R={a:It};if(Ce++,s.monitorRunDependencies&&s.monitorRunDependencies(Ce),s.instantiateWasm)try{return s.instantiateWasm(R,P)}catch(U){return E("Module.instantiateWasm callback failed with error: "+U),!1}(S||typeof WebAssembly.instantiateStreaming!="function"||ve()||Ae.startsWith("file://")||w||typeof fetch!="function"?L(D):fetch(Ae,{credentials:"same-origin"}).then(function(U){return WebAssembly.instantiateStreaming(U,R).then(D,function(W){return E("wasm streaming compile failed: "+W),E("falling back to ArrayBuffer instantiation"),L(D)})})).catch(f)})(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.La).apply(null,arguments)},s._OrtInit=function(){return(s._OrtInit=s.asm.Ma).apply(null,arguments)},s._OrtCreateSessionOptions=function(){return(s._OrtCreateSessionOptions=s.asm.Na).apply(null,arguments)},s._OrtAppendExecutionProvider=function(){return(s._OrtAppendExecutionProvider=s.asm.Oa).apply(null,arguments)},s._OrtAddSessionConfigEntry=function(){return(s._OrtAddSessionConfigEntry=s.asm.Pa).apply(null,arguments)},s._OrtReleaseSessionOptions=function(){return(s._OrtReleaseSessionOptions=s.asm.Qa).apply(null,arguments)},s._OrtCreateSession=function(){return(s._OrtCreateSession=s.asm.Ra).apply(null,arguments)},s._OrtReleaseSession=function(){return(s._OrtReleaseSession=s.asm.Sa).apply(null,arguments)},s._OrtGetInputCount=function(){return(s._OrtGetInputCount=s.asm.Ta).apply(null,arguments)},s._OrtGetOutputCount=function(){return(s._OrtGetOutputCount=s.asm.Ua).apply(null,arguments)},s._OrtGetInputName=function(){return(s._OrtGetInputName=s.asm.Va).apply(null,arguments)},s._OrtGetOutputName=function(){return(s._OrtGetOutputName=s.asm.Wa).apply(null,arguments)},s._OrtFree=function(){return(s._OrtFree=s.asm.Xa).apply(null,arguments)},s._OrtCreateTensor=function(){return(s._OrtCreateTensor=s.asm.Ya).apply(null,arguments)},s._OrtGetTensorData=function(){return(s._OrtGetTensorData=s.asm.Za).apply(null,arguments)},s._OrtReleaseTensor=function(){return(s._OrtReleaseTensor=s.asm._a).apply(null,arguments)},s._OrtCreateRunOptions=function(){return(s._OrtCreateRunOptions=s.asm.$a).apply(null,arguments)},s._OrtAddRunConfigEntry=function(){return(s._OrtAddRunConfigEntry=s.asm.ab).apply(null,arguments)},s._OrtReleaseRunOptions=function(){return(s._OrtReleaseRunOptions=s.asm.bb).apply(null,arguments)},s._OrtRun=function(){return(s._OrtRun=s.asm.cb).apply(null,arguments)},s._OrtEndProfiling=function(){return(s._OrtEndProfiling=s.asm.db).apply(null,arguments)};var Qe,ye=s._malloc=function(){return(ye=s._malloc=s.asm.eb).apply(null,arguments)},it=s._free=function(){return(it=s._free=s.asm.fb).apply(null,arguments)},pt=s._fflush=function(){return(pt=s._fflush=s.asm.gb).apply(null,arguments)},ot=s.___funcs_on_exit=function(){return(ot=s.___funcs_on_exit=s.asm.hb).apply(null,arguments)},se=s._setThrew=function(){return(se=s._setThrew=s.asm.jb).apply(null,arguments)},ie=s.stackSave=function(){return(ie=s.stackSave=s.asm.kb).apply(null,arguments)},oe=s.stackRestore=function(){return(oe=s.stackRestore=s.asm.lb).apply(null,arguments)},ft=s.stackAlloc=function(){return(ft=s.stackAlloc=s.asm.mb).apply(null,arguments)},st=s.___cxa_can_catch=function(){return(st=s.___cxa_can_catch=s.asm.nb).apply(null,arguments)},gt=s.___cxa_is_pointer_type=function(){return(gt=s.___cxa_is_pointer_type=s.asm.ob).apply(null,arguments)},mt=s.dynCall_j=function(){return(mt=s.dynCall_j=s.asm.pb).apply(null,arguments)},bt=s.dynCall_iiiiij=function(){return(bt=s.dynCall_iiiiij=s.asm.qb).apply(null,arguments)},yt=s.dynCall_jii=function(){return(yt=s.dynCall_jii=s.asm.rb).apply(null,arguments)},_t=s.dynCall_viiiiij=function(){return(_t=s.dynCall_viiiiij=s.asm.sb).apply(null,arguments)},wt=s.dynCall_vjji=function(){return(wt=s.dynCall_vjji=s.asm.tb).apply(null,arguments)},vt=s.dynCall_viiijjjii=function(){return(vt=s.dynCall_viiijjjii=s.asm.ub).apply(null,arguments)},Tt=s.dynCall_iij=function(){return(Tt=s.dynCall_iij=s.asm.vb).apply(null,arguments)},xt=s.dynCall_ji=function(){return(xt=s.dynCall_ji=s.asm.wb).apply(null,arguments)},St=s.dynCall_iiiiiij=function(){return(St=s.dynCall_iiiiiij=s.asm.xb).apply(null,arguments)},Ot=s.dynCall_iiij=function(){return(Ot=s.dynCall_iiij=s.asm.yb).apply(null,arguments)};function At(){function P(){if(!Qe&&(Qe=!0,s.calledRun=!0,!$)){if(He(ce),h(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;){var D=s.postRun.shift();_e.unshift(D)}He(_e)}}if(!(0{y.exports=function(n,u){for(var d=new Array(arguments.length-1),l=0,p=2,s=!0;p{var u=n;u.length=function(h){var f=h.length;if(!f)return 0;for(var a=0;--f%4>1&&h.charAt(f)==="=";)++a;return Math.ceil(3*h.length)/4-a};for(var d=new Array(64),l=new Array(123),p=0;p<64;)l[d[p]=p<26?p+65:p<52?p+71:p<62?p-4:p-59|43]=p++;u.encode=function(h,f,a){for(var o,t=null,e=[],r=0,i=0;f>2],o=(3&c)<<4,i=1;break;case 1:e[r++]=d[o|c>>4],o=(15&c)<<2,i=2;break;case 2:e[r++]=d[o|c>>6],e[r++]=d[63&c],i=0}r>8191&&((t||(t=[])).push(String.fromCharCode.apply(String,e)),r=0)}return i&&(e[r++]=d[o],e[r++]=61,i===1&&(e[r++]=61)),t?(r&&t.push(String.fromCharCode.apply(String,e.slice(0,r))),t.join("")):String.fromCharCode.apply(String,e.slice(0,r))};var s="invalid encoding";u.decode=function(h,f,a){for(var o,t=a,e=0,r=0;r1)break;if((i=l[i])===void 0)throw Error(s);switch(e){case 0:o=i,e=1;break;case 1:f[a++]=o<<2|(48&i)>>4,o=i,e=2;break;case 2:f[a++]=(15&o)<<4|(60&i)>>2,o=i,e=3;break;case 3:f[a++]=(3&o)<<6|i,e=0}}if(e===1)throw Error(s);return a-t},u.test=function(h){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(h)}},9211:y=>{function n(){this._listeners={}}y.exports=n,n.prototype.on=function(u,d,l){return(this._listeners[u]||(this._listeners[u]=[])).push({fn:d,ctx:l||this}),this},n.prototype.off=function(u,d){if(u===void 0)this._listeners={};else if(d===void 0)this._listeners[u]=[];else for(var l=this._listeners[u],p=0;p{function n(s){return typeof Float32Array<"u"?function(){var h=new Float32Array([-0]),f=new Uint8Array(h.buffer),a=f[3]===128;function o(i,c,g){h[0]=i,c[g]=f[0],c[g+1]=f[1],c[g+2]=f[2],c[g+3]=f[3]}function t(i,c,g){h[0]=i,c[g]=f[3],c[g+1]=f[2],c[g+2]=f[1],c[g+3]=f[0]}function e(i,c){return f[0]=i[c],f[1]=i[c+1],f[2]=i[c+2],f[3]=i[c+3],h[0]}function r(i,c){return f[3]=i[c],f[2]=i[c+1],f[1]=i[c+2],f[0]=i[c+3],h[0]}s.writeFloatLE=a?o:t,s.writeFloatBE=a?t:o,s.readFloatLE=a?e:r,s.readFloatBE=a?r:e}():function(){function h(a,o,t,e){var r=o<0?1:0;if(r&&(o=-o),o===0)a(1/o>0?0:2147483648,t,e);else if(isNaN(o))a(2143289344,t,e);else if(o>34028234663852886e22)a((r<<31|2139095040)>>>0,t,e);else if(o<11754943508222875e-54)a((r<<31|Math.round(o/1401298464324817e-60))>>>0,t,e);else{var i=Math.floor(Math.log(o)/Math.LN2);a((r<<31|i+127<<23|8388607&Math.round(o*Math.pow(2,-i)*8388608))>>>0,t,e)}}function f(a,o,t){var e=a(o,t),r=2*(e>>31)+1,i=e>>>23&255,c=8388607&e;return i===255?c?NaN:r*(1/0):i===0?1401298464324817e-60*r*c:r*Math.pow(2,i-150)*(c+8388608)}s.writeFloatLE=h.bind(null,u),s.writeFloatBE=h.bind(null,d),s.readFloatLE=f.bind(null,l),s.readFloatBE=f.bind(null,p)}(),typeof Float64Array<"u"?function(){var h=new Float64Array([-0]),f=new Uint8Array(h.buffer),a=f[7]===128;function o(i,c,g){h[0]=i,c[g]=f[0],c[g+1]=f[1],c[g+2]=f[2],c[g+3]=f[3],c[g+4]=f[4],c[g+5]=f[5],c[g+6]=f[6],c[g+7]=f[7]}function t(i,c,g){h[0]=i,c[g]=f[7],c[g+1]=f[6],c[g+2]=f[5],c[g+3]=f[4],c[g+4]=f[3],c[g+5]=f[2],c[g+6]=f[1],c[g+7]=f[0]}function e(i,c){return f[0]=i[c],f[1]=i[c+1],f[2]=i[c+2],f[3]=i[c+3],f[4]=i[c+4],f[5]=i[c+5],f[6]=i[c+6],f[7]=i[c+7],h[0]}function r(i,c){return f[7]=i[c],f[6]=i[c+1],f[5]=i[c+2],f[4]=i[c+3],f[3]=i[c+4],f[2]=i[c+5],f[1]=i[c+6],f[0]=i[c+7],h[0]}s.writeDoubleLE=a?o:t,s.writeDoubleBE=a?t:o,s.readDoubleLE=a?e:r,s.readDoubleBE=a?r:e}():function(){function h(a,o,t,e,r,i){var c=e<0?1:0;if(c&&(e=-e),e===0)a(0,r,i+o),a(1/e>0?0:2147483648,r,i+t);else if(isNaN(e))a(0,r,i+o),a(2146959360,r,i+t);else if(e>17976931348623157e292)a(0,r,i+o),a((c<<31|2146435072)>>>0,r,i+t);else{var g;if(e<22250738585072014e-324)a((g=e/5e-324)>>>0,r,i+o),a((c<<31|g/4294967296)>>>0,r,i+t);else{var m=Math.floor(Math.log(e)/Math.LN2);m===1024&&(m=1023),a(4503599627370496*(g=e*Math.pow(2,-m))>>>0,r,i+o),a((c<<31|m+1023<<20|1048576*g&1048575)>>>0,r,i+t)}}}function f(a,o,t,e,r){var i=a(e,r+o),c=a(e,r+t),g=2*(c>>31)+1,m=c>>>20&2047,b=4294967296*(1048575&c)+i;return m===2047?b?NaN:g*(1/0):m===0?5e-324*g*b:g*Math.pow(2,m-1075)*(b+4503599627370496)}s.writeDoubleLE=h.bind(null,u,0,4),s.writeDoubleBE=h.bind(null,d,4,0),s.readDoubleLE=f.bind(null,l,0,4),s.readDoubleBE=f.bind(null,p,4,0)}(),s}function u(s,h,f){h[f]=255&s,h[f+1]=s>>>8&255,h[f+2]=s>>>16&255,h[f+3]=s>>>24}function d(s,h,f){h[f]=s>>>24,h[f+1]=s>>>16&255,h[f+2]=s>>>8&255,h[f+3]=255&s}function l(s,h){return(s[h]|s[h+1]<<8|s[h+2]<<16|s[h+3]<<24)>>>0}function p(s,h){return(s[h]<<24|s[h+1]<<16|s[h+2]<<8|s[h+3])>>>0}y.exports=n(n)},7199:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(y){}return null}module.exports=inquire},6662:y=>{y.exports=function(n,u,d){var l=d||8192,p=l>>>1,s=null,h=l;return function(f){if(f<1||f>p)return n(f);h+f>l&&(s=n(l),h=0);var a=u.call(s,h,h+=f);return 7&h&&(h=1+(7|h)),a}}},4997:(y,n)=>{var u=n;u.length=function(d){for(var l=0,p=0,s=0;s191&&s<224?f[a++]=(31&s)<<6|63&d[l++]:s>239&&s<365?(s=((7&s)<<18|(63&d[l++])<<12|(63&d[l++])<<6|63&d[l++])-65536,f[a++]=55296+(s>>10),f[a++]=56320+(1023&s)):f[a++]=(15&s)<<12|(63&d[l++])<<6|63&d[l++],a>8191&&((h||(h=[])).push(String.fromCharCode.apply(String,f)),a=0);return h?(a&&h.push(String.fromCharCode.apply(String,f.slice(0,a))),h.join("")):String.fromCharCode.apply(String,f.slice(0,a))},u.write=function(d,l,p){for(var s,h,f=p,a=0;a>6|192,l[p++]=63&s|128):(64512&s)==55296&&(64512&(h=d.charCodeAt(a+1)))==56320?(s=65536+((1023&s)<<10)+(1023&h),++a,l[p++]=s>>18|240,l[p++]=s>>12&63|128,l[p++]=s>>6&63|128,l[p++]=63&s|128):(l[p++]=s>>12|224,l[p++]=s>>6&63|128,l[p++]=63&s|128);return p-f}},3442:(y,n)=>{n.__esModule=!0;var u=function(){function d(l){if(!l)throw new TypeError("Invalid argument; `value` has no value.");this.value=d.EMPTY,l&&d.isGuid(l)&&(this.value=l)}return d.isGuid=function(l){var p=l.toString();return l&&(l instanceof d||d.validator.test(p))},d.create=function(){return new d([d.gen(2),d.gen(1),d.gen(1),d.gen(1),d.gen(3)].join("-"))},d.createEmpty=function(){return new d("emptyguid")},d.parse=function(l){return new d(l)},d.raw=function(){return[d.gen(2),d.gen(1),d.gen(1),d.gen(1),d.gen(3)].join("-")},d.gen=function(l){for(var p="",s=0;s{y.exports=u;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function u(T,I,C){this.low=0|T,this.high=0|I,this.unsigned=!!C}function d(T){return(T&&T.__isLong__)===!0}u.prototype.__isLong__,Object.defineProperty(u.prototype,"__isLong__",{value:!0}),u.isLong=d;var l={},p={};function s(T,I){var C,B,F;return I?(F=0<=(T>>>=0)&&T<256)&&(B=p[T])?B:(C=f(T,(0|T)<0?-1:0,!0),F&&(p[T]=C),C):(F=-128<=(T|=0)&&T<128)&&(B=l[T])?B:(C=f(T,T<0?-1:0,!1),F&&(l[T]=C),C)}function h(T,I){if(isNaN(T))return I?m:g;if(I){if(T<0)return m;if(T>=r)return S}else{if(T<=-i)return O;if(T+1>=i)return v}return T<0?h(-T,I).neg():f(T%e|0,T/e|0,I)}function f(T,I,C){return new u(T,I,C)}u.fromInt=s,u.fromNumber=h,u.fromBits=f;var a=Math.pow;function o(T,I,C){if(T.length===0)throw Error("empty string");if(T==="NaN"||T==="Infinity"||T==="+Infinity"||T==="-Infinity")return g;if(typeof I=="number"?(C=I,I=!1):I=!!I,(C=C||10)<2||360)throw Error("interior hyphen");if(B===0)return o(T.substring(1),I,C).neg();for(var F=h(a(C,8)),N=g,H=0;H>>0:this.low},E.toNumber=function(){return this.unsigned?(this.high>>>0)*e+(this.low>>>0):this.high*e+(this.low>>>0)},E.toString=function(T){if((T=T||10)<2||36>>0).toString(T);if((N=$).isZero())return z+H;for(;z.length<6;)z="0"+z;H=""+z+H}},E.getHighBits=function(){return this.high},E.getHighBitsUnsigned=function(){return this.high>>>0},E.getLowBits=function(){return this.low},E.getLowBitsUnsigned=function(){return this.low>>>0},E.getNumBitsAbs=function(){if(this.isNegative())return this.eq(O)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,I=31;I>0&&!(T&1<=0},E.isOdd=function(){return(1&this.low)==1},E.isEven=function(){return(1&this.low)==0},E.equals=function(T){return d(T)||(T=t(T)),(this.unsigned===T.unsigned||this.high>>>31!=1||T.high>>>31!=1)&&this.high===T.high&&this.low===T.low},E.eq=E.equals,E.notEquals=function(T){return!this.eq(T)},E.neq=E.notEquals,E.ne=E.notEquals,E.lessThan=function(T){return this.comp(T)<0},E.lt=E.lessThan,E.lessThanOrEqual=function(T){return this.comp(T)<=0},E.lte=E.lessThanOrEqual,E.le=E.lessThanOrEqual,E.greaterThan=function(T){return this.comp(T)>0},E.gt=E.greaterThan,E.greaterThanOrEqual=function(T){return this.comp(T)>=0},E.gte=E.greaterThanOrEqual,E.ge=E.greaterThanOrEqual,E.compare=function(T){if(d(T)||(T=t(T)),this.eq(T))return 0;var I=this.isNegative(),C=T.isNegative();return I&&!C?-1:!I&&C?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},E.comp=E.compare,E.negate=function(){return!this.unsigned&&this.eq(O)?O:this.not().add(b)},E.neg=E.negate,E.add=function(T){d(T)||(T=t(T));var I=this.high>>>16,C=65535&this.high,B=this.low>>>16,F=65535&this.low,N=T.high>>>16,H=65535&T.high,$=T.low>>>16,z=0,Q=0,X=0,te=0;return X+=(te+=F+(65535&T.low))>>>16,Q+=(X+=B+$)>>>16,z+=(Q+=C+H)>>>16,z+=I+N,f((X&=65535)<<16|(te&=65535),(z&=65535)<<16|(Q&=65535),this.unsigned)},E.subtract=function(T){return d(T)||(T=t(T)),this.add(T.neg())},E.sub=E.subtract,E.multiply=function(T){if(this.isZero())return g;if(d(T)||(T=t(T)),n)return f(n.mul(this.low,this.high,T.low,T.high),n.get_high(),this.unsigned);if(T.isZero())return g;if(this.eq(O))return T.isOdd()?O:g;if(T.eq(O))return this.isOdd()?O:g;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(c)&&T.lt(c))return h(this.toNumber()*T.toNumber(),this.unsigned);var I=this.high>>>16,C=65535&this.high,B=this.low>>>16,F=65535&this.low,N=T.high>>>16,H=65535&T.high,$=T.low>>>16,z=65535&T.low,Q=0,X=0,te=0,ne=0;return te+=(ne+=F*z)>>>16,X+=(te+=B*z)>>>16,te&=65535,X+=(te+=F*$)>>>16,Q+=(X+=C*z)>>>16,X&=65535,Q+=(X+=B*$)>>>16,X&=65535,Q+=(X+=F*H)>>>16,Q+=I*z+C*$+B*H+F*N,f((te&=65535)<<16|(ne&=65535),(Q&=65535)<<16|(X&=65535),this.unsigned)},E.mul=E.multiply,E.divide=function(T){if(d(T)||(T=t(T)),T.isZero())throw Error("division by zero");var I,C,B;if(n)return this.unsigned||this.high!==-2147483648||T.low!==-1||T.high!==-1?f((this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high),n.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?m:g;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return m;if(T.gt(this.shru(1)))return _;B=m}else{if(this.eq(O))return T.eq(b)||T.eq(w)?O:T.eq(O)?b:(I=this.shr(1).div(T).shl(1)).eq(g)?T.isNegative()?b:w:(C=this.sub(T.mul(I)),B=I.add(C.div(T)));if(T.eq(O))return this.unsigned?m:g;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();B=g}for(C=this;C.gte(T);){I=Math.max(1,Math.floor(C.toNumber()/T.toNumber()));for(var F=Math.ceil(Math.log(I)/Math.LN2),N=F<=48?1:a(2,F-48),H=h(I),$=H.mul(T);$.isNegative()||$.gt(C);)$=(H=h(I-=N,this.unsigned)).mul(T);H.isZero()&&(H=b),B=B.add(H),C=C.sub($)}return B},E.div=E.divide,E.modulo=function(T){return d(T)||(T=t(T)),n?f((this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high),n.get_high(),this.unsigned):this.sub(this.div(T).mul(T))},E.mod=E.modulo,E.rem=E.modulo,E.not=function(){return f(~this.low,~this.high,this.unsigned)},E.and=function(T){return d(T)||(T=t(T)),f(this.low&T.low,this.high&T.high,this.unsigned)},E.or=function(T){return d(T)||(T=t(T)),f(this.low|T.low,this.high|T.high,this.unsigned)},E.xor=function(T){return d(T)||(T=t(T)),f(this.low^T.low,this.high^T.high,this.unsigned)},E.shiftLeft=function(T){return d(T)&&(T=T.toInt()),(T&=63)==0?this:T<32?f(this.low<>>32-T,this.unsigned):f(0,this.low<>>T|this.high<<32-T,this.high>>T,this.unsigned):f(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},E.shr=E.shiftRight,E.shiftRightUnsigned=function(T){if(d(T)&&(T=T.toInt()),(T&=63)==0)return this;var I=this.high;return T<32?f(this.low>>>T|I<<32-T,I>>>T,this.unsigned):f(T===32?I:I>>>T-32,0,this.unsigned)},E.shru=E.shiftRightUnsigned,E.shr_u=E.shiftRightUnsigned,E.toSigned=function(){return this.unsigned?f(this.low,this.high,!1):this},E.toUnsigned=function(){return this.unsigned?this:f(this.low,this.high,!0)},E.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},E.toBytesLE=function(){var T=this.high,I=this.low;return[255&I,I>>>8&255,I>>>16&255,I>>>24,255&T,T>>>8&255,T>>>16&255,T>>>24]},E.toBytesBE=function(){var T=this.high,I=this.low;return[T>>>24,T>>>16&255,T>>>8&255,255&T,I>>>24,I>>>16&255,I>>>8&255,255&I]},u.fromBytes=function(T,I,C){return C?u.fromBytesLE(T,I):u.fromBytesBE(T,I)},u.fromBytesLE=function(T,I){return new u(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,I)},u.fromBytesBE=function(T,I){return new u(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],I)}},1446:(y,n,u)=>{var d,l,p,s=u(2100),h=s.Reader,f=s.Writer,a=s.util,o=s.roots.default||(s.roots.default={});o.onnx=((p={}).Version=(d={},(l=Object.create(d))[d[0]="_START_VERSION"]=0,l[d[1]="IR_VERSION_2017_10_10"]=1,l[d[2]="IR_VERSION_2017_10_30"]=2,l[d[3]="IR_VERSION_2017_11_3"]=3,l[d[4]="IR_VERSION_2019_1_22"]=4,l[d[5]="IR_VERSION"]=5,l),p.AttributeProto=function(){function t(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:c.name=e.string();break;case 21:c.refAttrName=e.string();break;case 13:c.docString=e.string();break;case 20:c.type=e.int32();break;case 2:c.f=e.float();break;case 3:c.i=e.int64();break;case 4:c.s=e.bytes();break;case 5:c.t=o.onnx.TensorProto.decode(e,e.uint32());break;case 6:c.g=o.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(c.floats&&c.floats.length||(c.floats=[]),(7&g)==2)for(var m=e.uint32()+e.pos;e.pos>>0,e.i.high>>>0).toNumber())),e.s!=null&&(typeof e.s=="string"?a.base64.decode(e.s,r.s=a.newBuffer(a.base64.length(e.s)),0):e.s.length&&(r.s=e.s)),e.t!=null){if(typeof e.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");r.t=o.onnx.TensorProto.fromObject(e.t)}if(e.g!=null){if(typeof e.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");r.g=o.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");r.floats=[];for(var i=0;i>>0,e.ints[i].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(r.strings=[],i=0;i>>0,e.i.high>>>0).toNumber():e.i),e.s!=null&&e.hasOwnProperty("s")&&(i.s=r.bytes===String?a.base64.encode(e.s,0,e.s.length):r.bytes===Array?Array.prototype.slice.call(e.s):e.s),e.t!=null&&e.hasOwnProperty("t")&&(i.t=o.onnx.TensorProto.toObject(e.t,r)),e.g!=null&&e.hasOwnProperty("g")&&(i.g=o.onnx.GraphProto.toObject(e.g,r)),e.floats&&e.floats.length){i.floats=[];for(var g=0;g>>0,e.ints[g].high>>>0).toNumber():e.ints[g];if(e.strings&&e.strings.length)for(i.strings=[],g=0;g>>3){case 1:c.name=e.string();break;case 2:c.type=o.onnx.TypeProto.decode(e,e.uint32());break;case 3:c.docString=e.string();break;default:e.skipType(7&g)}}return c},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.name!=null&&e.hasOwnProperty("name")&&!a.isString(e.name))return"name: string expected";if(e.type!=null&&e.hasOwnProperty("type")){var r=o.onnx.TypeProto.verify(e.type);if(r)return"type."+r}return e.docString!=null&&e.hasOwnProperty("docString")&&!a.isString(e.docString)?"docString: string expected":null},t.fromObject=function(e){if(e instanceof o.onnx.ValueInfoProto)return e;var r=new o.onnx.ValueInfoProto;if(e.name!=null&&(r.name=String(e.name)),e.type!=null){if(typeof e.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");r.type=o.onnx.TypeProto.fromObject(e.type)}return e.docString!=null&&(r.docString=String(e.docString)),r},t.toObject=function(e,r){r||(r={});var i={};return r.defaults&&(i.name="",i.type=null,i.docString=""),e.name!=null&&e.hasOwnProperty("name")&&(i.name=e.name),e.type!=null&&e.hasOwnProperty("type")&&(i.type=o.onnx.TypeProto.toObject(e.type,r)),e.docString!=null&&e.hasOwnProperty("docString")&&(i.docString=e.docString),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),p.NodeProto=function(){function t(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:c.input&&c.input.length||(c.input=[]),c.input.push(e.string());break;case 2:c.output&&c.output.length||(c.output=[]),c.output.push(e.string());break;case 3:c.name=e.string();break;case 4:c.opType=e.string();break;case 7:c.domain=e.string();break;case 5:c.attribute&&c.attribute.length||(c.attribute=[]),c.attribute.push(o.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:c.docString=e.string();break;default:e.skipType(7&g)}}return c},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.input!=null&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(var r=0;r>>3){case 1:c.irVersion=e.int64();break;case 8:c.opsetImport&&c.opsetImport.length||(c.opsetImport=[]),c.opsetImport.push(o.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:c.producerName=e.string();break;case 3:c.producerVersion=e.string();break;case 4:c.domain=e.string();break;case 5:c.modelVersion=e.int64();break;case 6:c.docString=e.string();break;case 7:c.graph=o.onnx.GraphProto.decode(e,e.uint32());break;case 14:c.metadataProps&&c.metadataProps.length||(c.metadataProps=[]),c.metadataProps.push(o.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return c},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.irVersion!=null&&e.hasOwnProperty("irVersion")&&!(a.isInteger(e.irVersion)||e.irVersion&&a.isInteger(e.irVersion.low)&&a.isInteger(e.irVersion.high)))return"irVersion: integer|Long expected";if(e.opsetImport!=null&&e.hasOwnProperty("opsetImport")){if(!Array.isArray(e.opsetImport))return"opsetImport: array expected";for(var r=0;r>>0,e.irVersion.high>>>0).toNumber())),e.opsetImport){if(!Array.isArray(e.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");r.opsetImport=[];for(var i=0;i>>0,e.modelVersion.high>>>0).toNumber())),e.docString!=null&&(r.docString=String(e.docString)),e.graph!=null){if(typeof e.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");r.graph=o.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(r.metadataProps=[],i=0;i>>0,e.irVersion.high>>>0).toNumber():e.irVersion),e.producerName!=null&&e.hasOwnProperty("producerName")&&(i.producerName=e.producerName),e.producerVersion!=null&&e.hasOwnProperty("producerVersion")&&(i.producerVersion=e.producerVersion),e.domain!=null&&e.hasOwnProperty("domain")&&(i.domain=e.domain),e.modelVersion!=null&&e.hasOwnProperty("modelVersion")&&(typeof e.modelVersion=="number"?i.modelVersion=r.longs===String?String(e.modelVersion):e.modelVersion:i.modelVersion=r.longs===String?a.Long.prototype.toString.call(e.modelVersion):r.longs===Number?new a.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber():e.modelVersion),e.docString!=null&&e.hasOwnProperty("docString")&&(i.docString=e.docString),e.graph!=null&&e.hasOwnProperty("graph")&&(i.graph=o.onnx.GraphProto.toObject(e.graph,r)),e.opsetImport&&e.opsetImport.length){i.opsetImport=[];for(var g=0;g>>3){case 1:c.key=e.string();break;case 2:c.value=e.string();break;default:e.skipType(7&g)}}return c},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){return typeof e!="object"||e===null?"object expected":e.key!=null&&e.hasOwnProperty("key")&&!a.isString(e.key)?"key: string expected":e.value!=null&&e.hasOwnProperty("value")&&!a.isString(e.value)?"value: string expected":null},t.fromObject=function(e){if(e instanceof o.onnx.StringStringEntryProto)return e;var r=new o.onnx.StringStringEntryProto;return e.key!=null&&(r.key=String(e.key)),e.value!=null&&(r.value=String(e.value)),r},t.toObject=function(e,r){r||(r={});var i={};return r.defaults&&(i.key="",i.value=""),e.key!=null&&e.hasOwnProperty("key")&&(i.key=e.key),e.value!=null&&e.hasOwnProperty("value")&&(i.value=e.value),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),p.TensorAnnotation=function(){function t(e){if(this.quantParameterTensorNames=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:c.tensorName=e.string();break;case 2:c.quantParameterTensorNames&&c.quantParameterTensorNames.length||(c.quantParameterTensorNames=[]),c.quantParameterTensorNames.push(o.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return c},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.tensorName!=null&&e.hasOwnProperty("tensorName")&&!a.isString(e.tensorName))return"tensorName: string expected";if(e.quantParameterTensorNames!=null&&e.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(e.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var r=0;r>>3){case 1:c.node&&c.node.length||(c.node=[]),c.node.push(o.onnx.NodeProto.decode(e,e.uint32()));break;case 2:c.name=e.string();break;case 5:c.initializer&&c.initializer.length||(c.initializer=[]),c.initializer.push(o.onnx.TensorProto.decode(e,e.uint32()));break;case 10:c.docString=e.string();break;case 11:c.input&&c.input.length||(c.input=[]),c.input.push(o.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:c.output&&c.output.length||(c.output=[]),c.output.push(o.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:c.valueInfo&&c.valueInfo.length||(c.valueInfo=[]),c.valueInfo.push(o.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:c.quantizationAnnotation&&c.quantizationAnnotation.length||(c.quantizationAnnotation=[]),c.quantizationAnnotation.push(o.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return c},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.node!=null&&e.hasOwnProperty("node")){if(!Array.isArray(e.node))return"node: array expected";for(var r=0;r>>3){case 1:if(c.dims&&c.dims.length||(c.dims=[]),(7&g)==2)for(var m=e.uint32()+e.pos;e.pos>>0,e.dims[i].high>>>0).toNumber())}if(e.dataType!=null&&(r.dataType=0|e.dataType),e.segment!=null){if(typeof e.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");r.segment=o.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(r.floatData=[],i=0;i>>0,e.int64Data[i].high>>>0).toNumber())}if(e.name!=null&&(r.name=String(e.name)),e.docString!=null&&(r.docString=String(e.docString)),e.rawData!=null&&(typeof e.rawData=="string"?a.base64.decode(e.rawData,r.rawData=a.newBuffer(a.base64.length(e.rawData)),0):e.rawData.length&&(r.rawData=e.rawData)),e.externalData){if(!Array.isArray(e.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(r.externalData=[],i=0;i>>0,e.uint64Data[i].high>>>0).toNumber(!0))}return r},t.toObject=function(e,r){r||(r={});var i={};if((r.arrays||r.defaults)&&(i.dims=[],i.floatData=[],i.int32Data=[],i.stringData=[],i.int64Data=[],i.doubleData=[],i.uint64Data=[],i.externalData=[]),r.defaults&&(i.dataType=0,i.segment=null,i.name="",r.bytes===String?i.rawData="":(i.rawData=[],r.bytes!==Array&&(i.rawData=a.newBuffer(i.rawData))),i.docString="",i.dataLocation=r.enums===String?"DEFAULT":0),e.dims&&e.dims.length){i.dims=[];for(var c=0;c>>0,e.dims[c].high>>>0).toNumber():e.dims[c]}if(e.dataType!=null&&e.hasOwnProperty("dataType")&&(i.dataType=e.dataType),e.segment!=null&&e.hasOwnProperty("segment")&&(i.segment=o.onnx.TensorProto.Segment.toObject(e.segment,r)),e.floatData&&e.floatData.length)for(i.floatData=[],c=0;c>>0,e.int64Data[c].high>>>0).toNumber():e.int64Data[c];if(e.name!=null&&e.hasOwnProperty("name")&&(i.name=e.name),e.rawData!=null&&e.hasOwnProperty("rawData")&&(i.rawData=r.bytes===String?a.base64.encode(e.rawData,0,e.rawData.length):r.bytes===Array?Array.prototype.slice.call(e.rawData):e.rawData),e.doubleData&&e.doubleData.length)for(i.doubleData=[],c=0;c>>0,e.uint64Data[c].high>>>0).toNumber(!0):e.uint64Data[c];if(e.docString!=null&&e.hasOwnProperty("docString")&&(i.docString=e.docString),e.externalData&&e.externalData.length)for(i.externalData=[],c=0;c>>3){case 1:g.begin=r.int64();break;case 2:g.end=r.int64();break;default:r.skipType(7&m)}}return g},e.decodeDelimited=function(r){return r instanceof h||(r=new h(r)),this.decode(r,r.uint32())},e.verify=function(r){return typeof r!="object"||r===null?"object expected":r.begin!=null&&r.hasOwnProperty("begin")&&!(a.isInteger(r.begin)||r.begin&&a.isInteger(r.begin.low)&&a.isInteger(r.begin.high))?"begin: integer|Long expected":r.end!=null&&r.hasOwnProperty("end")&&!(a.isInteger(r.end)||r.end&&a.isInteger(r.end.low)&&a.isInteger(r.end.high))?"end: integer|Long expected":null},e.fromObject=function(r){if(r instanceof o.onnx.TensorProto.Segment)return r;var i=new o.onnx.TensorProto.Segment;return r.begin!=null&&(a.Long?(i.begin=a.Long.fromValue(r.begin)).unsigned=!1:typeof r.begin=="string"?i.begin=parseInt(r.begin,10):typeof r.begin=="number"?i.begin=r.begin:typeof r.begin=="object"&&(i.begin=new a.LongBits(r.begin.low>>>0,r.begin.high>>>0).toNumber())),r.end!=null&&(a.Long?(i.end=a.Long.fromValue(r.end)).unsigned=!1:typeof r.end=="string"?i.end=parseInt(r.end,10):typeof r.end=="number"?i.end=r.end:typeof r.end=="object"&&(i.end=new a.LongBits(r.end.low>>>0,r.end.high>>>0).toNumber())),i},e.toObject=function(r,i){i||(i={});var c={};if(i.defaults){if(a.Long){var g=new a.Long(0,0,!1);c.begin=i.longs===String?g.toString():i.longs===Number?g.toNumber():g}else c.begin=i.longs===String?"0":0;a.Long?(g=new a.Long(0,0,!1),c.end=i.longs===String?g.toString():i.longs===Number?g.toNumber():g):c.end=i.longs===String?"0":0}return r.begin!=null&&r.hasOwnProperty("begin")&&(typeof r.begin=="number"?c.begin=i.longs===String?String(r.begin):r.begin:c.begin=i.longs===String?a.Long.prototype.toString.call(r.begin):i.longs===Number?new a.LongBits(r.begin.low>>>0,r.begin.high>>>0).toNumber():r.begin),r.end!=null&&r.hasOwnProperty("end")&&(typeof r.end=="number"?c.end=i.longs===String?String(r.end):r.end:c.end=i.longs===String?a.Long.prototype.toString.call(r.end):i.longs===Number?new a.LongBits(r.end.low>>>0,r.end.high>>>0).toNumber():r.end),c},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),t.DataLocation=function(){var e={},r=Object.create(e);return r[e[0]="DEFAULT"]=0,r[e[1]="EXTERNAL"]=1,r}(),t}(),p.TensorShapeProto=function(){function t(e){if(this.dim=[],e)for(var r=Object.keys(e),i=0;i>>3==1?(c.dim&&c.dim.length||(c.dim=[]),c.dim.push(o.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&g)}return c},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.dim!=null&&e.hasOwnProperty("dim")){if(!Array.isArray(e.dim))return"dim: array expected";for(var r=0;r>>3){case 1:m.dimValue=i.int64();break;case 2:m.dimParam=i.string();break;case 3:m.denotation=i.string();break;default:i.skipType(7&b)}}return m},e.decodeDelimited=function(i){return i instanceof h||(i=new h(i)),this.decode(i,i.uint32())},e.verify=function(i){if(typeof i!="object"||i===null)return"object expected";var c={};if(i.dimValue!=null&&i.hasOwnProperty("dimValue")&&(c.value=1,!(a.isInteger(i.dimValue)||i.dimValue&&a.isInteger(i.dimValue.low)&&a.isInteger(i.dimValue.high))))return"dimValue: integer|Long expected";if(i.dimParam!=null&&i.hasOwnProperty("dimParam")){if(c.value===1)return"value: multiple values";if(c.value=1,!a.isString(i.dimParam))return"dimParam: string expected"}return i.denotation!=null&&i.hasOwnProperty("denotation")&&!a.isString(i.denotation)?"denotation: string expected":null},e.fromObject=function(i){if(i instanceof o.onnx.TensorShapeProto.Dimension)return i;var c=new o.onnx.TensorShapeProto.Dimension;return i.dimValue!=null&&(a.Long?(c.dimValue=a.Long.fromValue(i.dimValue)).unsigned=!1:typeof i.dimValue=="string"?c.dimValue=parseInt(i.dimValue,10):typeof i.dimValue=="number"?c.dimValue=i.dimValue:typeof i.dimValue=="object"&&(c.dimValue=new a.LongBits(i.dimValue.low>>>0,i.dimValue.high>>>0).toNumber())),i.dimParam!=null&&(c.dimParam=String(i.dimParam)),i.denotation!=null&&(c.denotation=String(i.denotation)),c},e.toObject=function(i,c){c||(c={});var g={};return c.defaults&&(g.denotation=""),i.dimValue!=null&&i.hasOwnProperty("dimValue")&&(typeof i.dimValue=="number"?g.dimValue=c.longs===String?String(i.dimValue):i.dimValue:g.dimValue=c.longs===String?a.Long.prototype.toString.call(i.dimValue):c.longs===Number?new a.LongBits(i.dimValue.low>>>0,i.dimValue.high>>>0).toNumber():i.dimValue,c.oneofs&&(g.value="dimValue")),i.dimParam!=null&&i.hasOwnProperty("dimParam")&&(g.dimParam=i.dimParam,c.oneofs&&(g.value="dimParam")),i.denotation!=null&&i.hasOwnProperty("denotation")&&(g.denotation=i.denotation),g},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),t}(),p.TypeProto=function(){function t(r){if(r)for(var i=Object.keys(r),c=0;c>>3){case 1:g.tensorType=o.onnx.TypeProto.Tensor.decode(r,r.uint32());break;case 6:g.denotation=r.string();break;default:r.skipType(7&m)}}return g},t.decodeDelimited=function(r){return r instanceof h||(r=new h(r)),this.decode(r,r.uint32())},t.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorType!=null&&r.hasOwnProperty("tensorType")){var i=o.onnx.TypeProto.Tensor.verify(r.tensorType);if(i)return"tensorType."+i}return r.denotation!=null&&r.hasOwnProperty("denotation")&&!a.isString(r.denotation)?"denotation: string expected":null},t.fromObject=function(r){if(r instanceof o.onnx.TypeProto)return r;var i=new o.onnx.TypeProto;if(r.tensorType!=null){if(typeof r.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");i.tensorType=o.onnx.TypeProto.Tensor.fromObject(r.tensorType)}return r.denotation!=null&&(i.denotation=String(r.denotation)),i},t.toObject=function(r,i){i||(i={});var c={};return i.defaults&&(c.denotation=""),r.tensorType!=null&&r.hasOwnProperty("tensorType")&&(c.tensorType=o.onnx.TypeProto.Tensor.toObject(r.tensorType,i),i.oneofs&&(c.value="tensorType")),r.denotation!=null&&r.hasOwnProperty("denotation")&&(c.denotation=r.denotation),c},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t.Tensor=function(){function r(i){if(i)for(var c=Object.keys(i),g=0;g>>3){case 1:m.elemType=i.int32();break;case 2:m.shape=o.onnx.TensorShapeProto.decode(i,i.uint32());break;default:i.skipType(7&b)}}return m},r.decodeDelimited=function(i){return i instanceof h||(i=new h(i)),this.decode(i,i.uint32())},r.verify=function(i){if(typeof i!="object"||i===null)return"object expected";if(i.elemType!=null&&i.hasOwnProperty("elemType")&&!a.isInteger(i.elemType))return"elemType: integer expected";if(i.shape!=null&&i.hasOwnProperty("shape")){var c=o.onnx.TensorShapeProto.verify(i.shape);if(c)return"shape."+c}return null},r.fromObject=function(i){if(i instanceof o.onnx.TypeProto.Tensor)return i;var c=new o.onnx.TypeProto.Tensor;if(i.elemType!=null&&(c.elemType=0|i.elemType),i.shape!=null){if(typeof i.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");c.shape=o.onnx.TensorShapeProto.fromObject(i.shape)}return c},r.toObject=function(i,c){c||(c={});var g={};return c.defaults&&(g.elemType=0,g.shape=null),i.elemType!=null&&i.hasOwnProperty("elemType")&&(g.elemType=i.elemType),i.shape!=null&&i.hasOwnProperty("shape")&&(g.shape=o.onnx.TensorShapeProto.toObject(i.shape,c)),g},r.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},r}(),t}(),p.OperatorSetIdProto=function(){function t(e){if(e)for(var r=Object.keys(e),i=0;i>>3){case 1:c.domain=e.string();break;case 2:c.version=e.int64();break;default:e.skipType(7&g)}}return c},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){return typeof e!="object"||e===null?"object expected":e.domain!=null&&e.hasOwnProperty("domain")&&!a.isString(e.domain)?"domain: string expected":e.version!=null&&e.hasOwnProperty("version")&&!(a.isInteger(e.version)||e.version&&a.isInteger(e.version.low)&&a.isInteger(e.version.high))?"version: integer|Long expected":null},t.fromObject=function(e){if(e instanceof o.onnx.OperatorSetIdProto)return e;var r=new o.onnx.OperatorSetIdProto;return e.domain!=null&&(r.domain=String(e.domain)),e.version!=null&&(a.Long?(r.version=a.Long.fromValue(e.version)).unsigned=!1:typeof e.version=="string"?r.version=parseInt(e.version,10):typeof e.version=="number"?r.version=e.version:typeof e.version=="object"&&(r.version=new a.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber())),r},t.toObject=function(e,r){r||(r={});var i={};if(r.defaults)if(i.domain="",a.Long){var c=new a.Long(0,0,!1);i.version=r.longs===String?c.toString():r.longs===Number?c.toNumber():c}else i.version=r.longs===String?"0":0;return e.domain!=null&&e.hasOwnProperty("domain")&&(i.domain=e.domain),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?i.version=r.longs===String?String(e.version):e.version:i.version=r.longs===String?a.Long.prototype.toString.call(e.version):r.longs===Number?new a.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber():e.version),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),p),y.exports=o},2100:(y,n,u)=>{y.exports=u(9482)},9482:(y,n,u)=>{var d=n;function l(){d.util._configure(),d.Writer._configure(d.BufferWriter),d.Reader._configure(d.BufferReader)}d.build="minimal",d.Writer=u(1173),d.BufferWriter=u(3155),d.Reader=u(1408),d.BufferReader=u(593),d.util=u(9693),d.rpc=u(5994),d.roots=u(5054),d.configure=l,l()},1408:(y,n,u)=>{y.exports=f;var d,l=u(9693),p=l.LongBits,s=l.utf8;function h(c,g){return RangeError("index out of range: "+c.pos+" + "+(g||1)+" > "+c.len)}function f(c){this.buf=c,this.pos=0,this.len=c.length}var a,o=typeof Uint8Array<"u"?function(c){if(c instanceof Uint8Array||Array.isArray(c))return new f(c);throw Error("illegal buffer")}:function(c){if(Array.isArray(c))return new f(c);throw Error("illegal buffer")},t=function(){return l.Buffer?function(c){return(f.create=function(g){return l.Buffer.isBuffer(g)?new d(g):o(g)})(c)}:o};function e(){var c=new p(0,0),g=0;if(!(this.len-this.pos>4)){for(;g<3;++g){if(this.pos>=this.len)throw h(this);if(c.lo=(c.lo|(127&this.buf[this.pos])<<7*g)>>>0,this.buf[this.pos++]<128)return c}return c.lo=(c.lo|(127&this.buf[this.pos++])<<7*g)>>>0,c}for(;g<4;++g)if(c.lo=(c.lo|(127&this.buf[this.pos])<<7*g)>>>0,this.buf[this.pos++]<128)return c;if(c.lo=(c.lo|(127&this.buf[this.pos])<<28)>>>0,c.hi=(c.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return c;if(g=0,this.len-this.pos>4){for(;g<5;++g)if(c.hi=(c.hi|(127&this.buf[this.pos])<<7*g+3)>>>0,this.buf[this.pos++]<128)return c}else for(;g<5;++g){if(this.pos>=this.len)throw h(this);if(c.hi=(c.hi|(127&this.buf[this.pos])<<7*g+3)>>>0,this.buf[this.pos++]<128)return c}throw Error("invalid varint encoding")}function r(c,g){return(c[g-4]|c[g-3]<<8|c[g-2]<<16|c[g-1]<<24)>>>0}function i(){if(this.pos+8>this.len)throw h(this,8);return new p(r(this.buf,this.pos+=4),r(this.buf,this.pos+=4))}f.create=t(),f.prototype._slice=l.Array.prototype.subarray||l.Array.prototype.slice,f.prototype.uint32=(a=4294967295,function(){if(a=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(a=(a|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(a=(a|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(a=(a|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(a=(a|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return a;if((this.pos+=5)>this.len)throw this.pos=this.len,h(this,10);return a}),f.prototype.int32=function(){return 0|this.uint32()},f.prototype.sint32=function(){var c=this.uint32();return c>>>1^-(1&c)|0},f.prototype.bool=function(){return this.uint32()!==0},f.prototype.fixed32=function(){if(this.pos+4>this.len)throw h(this,4);return r(this.buf,this.pos+=4)},f.prototype.sfixed32=function(){if(this.pos+4>this.len)throw h(this,4);return 0|r(this.buf,this.pos+=4)},f.prototype.float=function(){if(this.pos+4>this.len)throw h(this,4);var c=l.float.readFloatLE(this.buf,this.pos);return this.pos+=4,c},f.prototype.double=function(){if(this.pos+8>this.len)throw h(this,4);var c=l.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,c},f.prototype.bytes=function(){var c=this.uint32(),g=this.pos,m=this.pos+c;if(m>this.len)throw h(this,c);return this.pos+=c,Array.isArray(this.buf)?this.buf.slice(g,m):g===m?new this.buf.constructor(0):this._slice.call(this.buf,g,m)},f.prototype.string=function(){var c=this.bytes();return s.read(c,0,c.length)},f.prototype.skip=function(c){if(typeof c=="number"){if(this.pos+c>this.len)throw h(this,c);this.pos+=c}else do if(this.pos>=this.len)throw h(this);while(128&this.buf[this.pos++]);return this},f.prototype.skipType=function(c){switch(c){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(c=7&this.uint32())!=4;)this.skipType(c);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+c+" at offset "+this.pos)}return this},f._configure=function(c){d=c,f.create=t(),d._configure();var g=l.Long?"toLong":"toNumber";l.merge(f.prototype,{int64:function(){return e.call(this)[g](!1)},uint64:function(){return e.call(this)[g](!0)},sint64:function(){return e.call(this).zzDecode()[g](!1)},fixed64:function(){return i.call(this)[g](!0)},sfixed64:function(){return i.call(this)[g](!1)}})}},593:(y,n,u)=>{y.exports=p;var d=u(1408);(p.prototype=Object.create(d.prototype)).constructor=p;var l=u(9693);function p(s){d.call(this,s)}p._configure=function(){l.Buffer&&(p.prototype._slice=l.Buffer.prototype.slice)},p.prototype.string=function(){var s=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+s,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+s,this.len))},p._configure()},5054:y=>{y.exports={}},5994:(y,n,u)=>{n.Service=u(7948)},7948:(y,n,u)=>{y.exports=l;var d=u(9693);function l(p,s,h){if(typeof p!="function")throw TypeError("rpcImpl must be a function");d.EventEmitter.call(this),this.rpcImpl=p,this.requestDelimited=!!s,this.responseDelimited=!!h}(l.prototype=Object.create(d.EventEmitter.prototype)).constructor=l,l.prototype.rpcCall=function p(s,h,f,a,o){if(!a)throw TypeError("request must be specified");var t=this;if(!o)return d.asPromise(p,t,s,h,f,a);if(t.rpcImpl)try{return t.rpcImpl(s,h[t.requestDelimited?"encodeDelimited":"encode"](a).finish(),function(e,r){if(e)return t.emit("error",e,s),o(e);if(r!==null){if(!(r instanceof f))try{r=f[t.responseDelimited?"decodeDelimited":"decode"](r)}catch(i){return t.emit("error",i,s),o(i)}return t.emit("data",r,s),o(null,r)}t.end(!0)})}catch(e){return t.emit("error",e,s),void setTimeout(function(){o(e)},0)}else setTimeout(function(){o(Error("already ended"))},0)},l.prototype.end=function(p){return this.rpcImpl&&(p||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(y,n,u)=>{y.exports=l;var d=u(9693);function l(f,a){this.lo=f>>>0,this.hi=a>>>0}var p=l.zero=new l(0,0);p.toNumber=function(){return 0},p.zzEncode=p.zzDecode=function(){return this},p.length=function(){return 1};var s=l.zeroHash="\0\0\0\0\0\0\0\0";l.fromNumber=function(f){if(f===0)return p;var a=f<0;a&&(f=-f);var o=f>>>0,t=(f-o)/4294967296>>>0;return a&&(t=~t>>>0,o=~o>>>0,++o>4294967295&&(o=0,++t>4294967295&&(t=0))),new l(o,t)},l.from=function(f){if(typeof f=="number")return l.fromNumber(f);if(d.isString(f)){if(!d.Long)return l.fromNumber(parseInt(f,10));f=d.Long.fromString(f)}return f.low||f.high?new l(f.low>>>0,f.high>>>0):p},l.prototype.toNumber=function(f){if(!f&&this.hi>>>31){var a=1+~this.lo>>>0,o=~this.hi>>>0;return a||(o=o+1>>>0),-(a+4294967296*o)}return this.lo+4294967296*this.hi},l.prototype.toLong=function(f){return d.Long?new d.Long(0|this.lo,0|this.hi,!!f):{low:0|this.lo,high:0|this.hi,unsigned:!!f}};var h=String.prototype.charCodeAt;l.fromHash=function(f){return f===s?p:new l((h.call(f,0)|h.call(f,1)<<8|h.call(f,2)<<16|h.call(f,3)<<24)>>>0,(h.call(f,4)|h.call(f,5)<<8|h.call(f,6)<<16|h.call(f,7)<<24)>>>0)},l.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},l.prototype.zzEncode=function(){var f=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^f)>>>0,this.lo=(this.lo<<1^f)>>>0,this},l.prototype.zzDecode=function(){var f=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^f)>>>0,this.hi=(this.hi>>>1^f)>>>0,this},l.prototype.length=function(){var f=this.lo,a=(this.lo>>>28|this.hi<<4)>>>0,o=this.hi>>>24;return o===0?a===0?f<16384?f<128?1:2:f<2097152?3:4:a<16384?a<128?5:6:a<2097152?7:8:o<128?9:10}},9693:function(y,n,u){var d=n;function l(s,h,f){for(var a=Object.keys(h),o=0;o0)},d.Buffer=function(){try{var s=d.inquire("buffer").Buffer;return s.prototype.utf8Write?s:null}catch{return null}}(),d._Buffer_from=null,d._Buffer_allocUnsafe=null,d.newBuffer=function(s){return typeof s=="number"?d.Buffer?d._Buffer_allocUnsafe(s):new d.Array(s):d.Buffer?d._Buffer_from(s):typeof Uint8Array>"u"?s:new Uint8Array(s)},d.Array=typeof Uint8Array<"u"?Uint8Array:Array,d.Long=d.global.dcodeIO&&d.global.dcodeIO.Long||d.global.Long||d.inquire("long"),d.key2Re=/^true|false|0|1$/,d.key32Re=/^-?(?:0|[1-9][0-9]*)$/,d.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,d.longToHash=function(s){return s?d.LongBits.from(s).toHash():d.LongBits.zeroHash},d.longFromHash=function(s,h){var f=d.LongBits.fromHash(s);return d.Long?d.Long.fromBits(f.lo,f.hi,h):f.toNumber(!!h)},d.merge=l,d.lcFirst=function(s){return s.charAt(0).toLowerCase()+s.substring(1)},d.newError=p,d.ProtocolError=p("ProtocolError"),d.oneOfGetter=function(s){for(var h={},f=0;f-1;--o)if(h[a[o]]===1&&this[a[o]]!==void 0&&this[a[o]]!==null)return a[o]}},d.oneOfSetter=function(s){return function(h){for(var f=0;f{y.exports=t;var d,l=u(9693),p=l.LongBits,s=l.base64,h=l.utf8;function f(b,_,w){this.fn=b,this.len=_,this.next=void 0,this.val=w}function a(){}function o(b){this.head=b.head,this.tail=b.tail,this.len=b.len,this.next=b.states}function t(){this.len=0,this.head=new f(a,0,0),this.tail=this.head,this.states=null}var e=function(){return l.Buffer?function(){return(t.create=function(){return new d})()}:function(){return new t}};function r(b,_,w){_[w]=255&b}function i(b,_){this.len=b,this.next=void 0,this.val=_}function c(b,_,w){for(;b.hi;)_[w++]=127&b.lo|128,b.lo=(b.lo>>>7|b.hi<<25)>>>0,b.hi>>>=7;for(;b.lo>127;)_[w++]=127&b.lo|128,b.lo=b.lo>>>7;_[w++]=b.lo}function g(b,_,w){_[w]=255&b,_[w+1]=b>>>8&255,_[w+2]=b>>>16&255,_[w+3]=b>>>24}t.create=e(),t.alloc=function(b){return new l.Array(b)},l.Array!==Array&&(t.alloc=l.pool(t.alloc,l.Array.prototype.subarray)),t.prototype._push=function(b,_,w){return this.tail=this.tail.next=new f(b,_,w),this.len+=_,this},i.prototype=Object.create(f.prototype),i.prototype.fn=function(b,_,w){for(;b>127;)_[w++]=127&b|128,b>>>=7;_[w]=b},t.prototype.uint32=function(b){return this.len+=(this.tail=this.tail.next=new i((b>>>=0)<128?1:b<16384?2:b<2097152?3:b<268435456?4:5,b)).len,this},t.prototype.int32=function(b){return b<0?this._push(c,10,p.fromNumber(b)):this.uint32(b)},t.prototype.sint32=function(b){return this.uint32((b<<1^b>>31)>>>0)},t.prototype.uint64=function(b){var _=p.from(b);return this._push(c,_.length(),_)},t.prototype.int64=t.prototype.uint64,t.prototype.sint64=function(b){var _=p.from(b).zzEncode();return this._push(c,_.length(),_)},t.prototype.bool=function(b){return this._push(r,1,b?1:0)},t.prototype.fixed32=function(b){return this._push(g,4,b>>>0)},t.prototype.sfixed32=t.prototype.fixed32,t.prototype.fixed64=function(b){var _=p.from(b);return this._push(g,4,_.lo)._push(g,4,_.hi)},t.prototype.sfixed64=t.prototype.fixed64,t.prototype.float=function(b){return this._push(l.float.writeFloatLE,4,b)},t.prototype.double=function(b){return this._push(l.float.writeDoubleLE,8,b)};var m=l.Array.prototype.set?function(b,_,w){_.set(b,w)}:function(b,_,w){for(var v=0;v>>0;if(!_)return this._push(r,1,0);if(l.isString(b)){var w=t.alloc(_=s.length(b));s.decode(b,w,0),b=w}return this.uint32(_)._push(m,_,b)},t.prototype.string=function(b){var _=h.length(b);return _?this.uint32(_)._push(h.write,_,b):this._push(r,1,0)},t.prototype.fork=function(){return this.states=new o(this),this.head=this.tail=new f(a,0,0),this.len=0,this},t.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new f(a,0,0),this.len=0),this},t.prototype.ldelim=function(){var b=this.head,_=this.tail,w=this.len;return this.reset().uint32(w),w&&(this.tail.next=b.next,this.tail=_,this.len+=w),this},t.prototype.finish=function(){for(var b=this.head.next,_=this.constructor.alloc(this.len),w=0;b;)b.fn(b.val,_,w),w+=b.len,b=b.next;return _},t._configure=function(b){d=b,t.create=e(),d._configure()}},3155:(y,n,u)=>{y.exports=p;var d=u(1173);(p.prototype=Object.create(d.prototype)).constructor=p;var l=u(9693);function p(){d.call(this)}function s(h,f,a){h.length<40?l.utf8.write(h,f,a):f.utf8Write?f.utf8Write(h,a):f.write(h,a)}p._configure=function(){p.alloc=l._Buffer_allocUnsafe,p.writeBytesBuffer=l.Buffer&&l.Buffer.prototype instanceof Uint8Array&&l.Buffer.prototype.set.name==="set"?function(h,f,a){f.set(h,a)}:function(h,f,a){if(h.copy)h.copy(f,a,0,h.length);else for(var o=0;o>>0;return this.uint32(f),f&&this._push(p.writeBytesBuffer,f,h),this},p.prototype.string=function(h){var f=l.Buffer.byteLength(h);return this.uint32(f),f&&this._push(s,f,h),this},p._configure()},7714:(y,n,u)=>{n.R=void 0;const d=u(6919),l=u(7448);n.R=new class{async init(){}async createSessionHandler(p,s){const h=new d.Session(s);return await h.loadModel(p),new l.OnnxjsSessionHandler(h)}}},4200:(y,n,u)=>{n.c8=n.rX=void 0;const d=u(1670),l=u(5381),p=u(2157),s=u(2306);n.rX=()=>{if((typeof d.env.wasm.initTimeout!="number"||d.env.wasm.initTimeout<0)&&(d.env.wasm.initTimeout=0),typeof d.env.wasm.simd!="boolean"&&(d.env.wasm.simd=!0),typeof d.env.wasm.proxy!="boolean"&&(d.env.wasm.proxy=!1),typeof d.env.wasm.numThreads!="number"||!Number.isInteger(d.env.wasm.numThreads)||d.env.wasm.numThreads<=0){const h=typeof navigator>"u"?(0,l.cpus)().length:navigator.hardwareConcurrency;d.env.wasm.numThreads=Math.min(4,Math.ceil((h||1)/2))}},n.c8=new class{async init(){(0,n.rX)(),await(0,p.initWasm)()}async createSessionHandler(h,f){const a=new s.OnnxruntimeWebAssemblySessionHandler;return await a.loadModel(h,f),Promise.resolve(a)}}},6018:function(y,n,u){var d=this&&this.__createBinding||(Object.create?function(s,h,f,a){a===void 0&&(a=f);var o=Object.getOwnPropertyDescriptor(h,f);o&&!("get"in o?!h.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return h[f]}}),Object.defineProperty(s,a,o)}:function(s,h,f,a){a===void 0&&(a=f),s[a]=h[f]}),l=this&&this.__exportStar||function(s,h){for(var f in s)f==="default"||Object.prototype.hasOwnProperty.call(h,f)||d(h,s,f)};Object.defineProperty(n,"__esModule",{value:!0}),l(u(1670),n);const p=u(1670);{const s=u(7714).R;(0,p.registerBackend)("webgl",s,-10)}{const s=u(4200).c8;(0,p.registerBackend)("cpu",s,10),(0,p.registerBackend)("wasm",s,10),(0,p.registerBackend)("xnnpack",s,9)}},246:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createAttributeWithCacheKey=void 0;class u{constructor(l){Object.assign(this,l)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map(l=>`${this[l]}`).join(";")),this._cacheKey}}n.createAttributeWithCacheKey=d=>new u(d)},7778:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Attribute=void 0;const d=u(1446),l=u(9395),p=u(9162),s=u(2517);var h=l.onnxruntime.experimental.fbs;class f{constructor(o){if(this._attributes=new Map,o!=null){for(const t of o)t instanceof d.onnx.AttributeProto?this._attributes.set(t.name,[f.getValue(t),f.getType(t)]):t instanceof h.Attribute&&this._attributes.set(t.name(),[f.getValue(t),f.getType(t)]);if(this._attributes.sizep.Tensor.fromProto(r));if(o instanceof h.Attribute)return e.map(r=>p.Tensor.fromOrtTensor(r))}if(t===d.onnx.AttributeProto.AttributeType.STRING&&o instanceof d.onnx.AttributeProto){const r=e;return(0,s.decodeUtf8String)(r)}return t===d.onnx.AttributeProto.AttributeType.STRINGS&&o instanceof d.onnx.AttributeProto?e.map(s.decodeUtf8String):e}static getValueNoCheck(o){return o instanceof d.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(o):this.getValueNoCheckFromOrtFormat(o)}static getValueNoCheckFromOnnxFormat(o){switch(o.type){case d.onnx.AttributeProto.AttributeType.FLOAT:return o.f;case d.onnx.AttributeProto.AttributeType.INT:return o.i;case d.onnx.AttributeProto.AttributeType.STRING:return o.s;case d.onnx.AttributeProto.AttributeType.TENSOR:return o.t;case d.onnx.AttributeProto.AttributeType.GRAPH:return o.g;case d.onnx.AttributeProto.AttributeType.FLOATS:return o.floats;case d.onnx.AttributeProto.AttributeType.INTS:return o.ints;case d.onnx.AttributeProto.AttributeType.STRINGS:return o.strings;case d.onnx.AttributeProto.AttributeType.TENSORS:return o.tensors;case d.onnx.AttributeProto.AttributeType.GRAPHS:return o.graphs;default:throw new Error(`unsupported attribute type: ${d.onnx.AttributeProto.AttributeType[o.type]}`)}}static getValueNoCheckFromOrtFormat(o){switch(o.type()){case h.AttributeType.FLOAT:return o.f();case h.AttributeType.INT:return o.i();case h.AttributeType.STRING:return o.s();case h.AttributeType.TENSOR:return o.t();case h.AttributeType.GRAPH:return o.g();case h.AttributeType.FLOATS:return o.floatsArray();case h.AttributeType.INTS:{const t=[];for(let e=0;e{Object.defineProperty(n,"__esModule",{value:!0}),n.resolveBackend=n.backend=void 0;const d=u(5038),l=new Map;async function p(s){const h=n.backend;if(h[s]!==void 0&&function(f){const a=f;return"initialize"in a&&typeof a.initialize=="function"&&"createSessionHandler"in a&&typeof a.createSessionHandler=="function"&&"dispose"in a&&typeof a.dispose=="function"}(h[s])){const f=h[s];let a=f.initialize();if(typeof a=="object"&&"then"in a&&(a=await a),a)return l.set(s,f),f}}n.backend={webgl:new d.WebGLBackend},n.resolveBackend=async function s(h){if(!h)return s(["webgl"]);{const f=typeof h=="string"?[h]:h;for(const a of f){const o=l.get(a);if(o)return o;const t=await p(a);if(t)return t}}throw new Error("no available backend to use")}},5038:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLBackend=void 0;const d=u(1670),l=u(6231),p=u(6416),s=u(7305);n.WebGLBackend=class{get contextId(){return d.env.webgl.contextId}set contextId(h){d.env.webgl.contextId=h}get matmulMaxBatchSize(){return d.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(h){d.env.webgl.matmulMaxBatchSize=h}get textureCacheMode(){return d.env.webgl.textureCacheMode}set textureCacheMode(h){d.env.webgl.textureCacheMode=h}get pack(){return d.env.webgl.pack}set pack(h){d.env.webgl.pack=h}get async(){return d.env.webgl.async}set async(h){d.env.webgl.async=h}initialize(){try{return this.glContext=(0,s.createWebGLContext)(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),l.Logger.setWithEnv(d.env),l.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(h){return l.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${h}`),!1}}createSessionHandler(h){return new p.WebGLSessionHandler(this,h)}dispose(){this.glContext.dispose()}}},5107:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoordsGlslLib=void 0;const d=u(2517),l=u(8520),p=u(5060),s=u(7859),h=u(9390);class f extends l.GlslLib{constructor(o){super(o)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new l.GlslLibRoutine(` - vec2 offsetToCoords(int offset, int width, int height) { - int t = offset / width; - int s = offset - t*width; - vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height); - return coords; - } - `)}}coordsToOffset(){return{coordsToOffset:new l.GlslLibRoutine(` - int coordsToOffset(vec2 coords, int width, int height) { - float s = coords.s * float(width); - float t = coords.t * float(height); - int offset = int(t) * width + int(s); - return offset; - } - `)}}getOutputSamplingSnippet(){const o=this.context.outputTextureLayout;return o.isPacked?this.getPackedOutputSamplingSnippet(o):this.getUnpackedOutputSamplingSnippet(o)}getPackedOutputSamplingSnippet(o){const t=o.unpackedShape,e=[o.width,o.height],r={},i="getOutputCoords";switch(t.length){case 0:r[i]=this.getOutputScalarCoords();break;case 1:r[i]=this.getOutputPacked1DCoords(t,e);break;case 2:r[i]=this.getOutputPacked2DCoords(t,e);break;case 3:r[i]=this.getOutputPacked3DCoords(t,e);break;default:r[i]=this.getOutputPackedNDCoords(t,e)}const c=` - void setOutput(vec4 val) { - ${(0,p.getGlsl)(this.context.glContext.version).output} = val; - } - `;return r.floatTextureSetRGBA=new l.GlslLibRoutine(c),r}getUnpackedOutputSamplingSnippet(o){const t=o.unpackedShape,e=[o.width,o.height],r={},i="getOutputCoords";switch(t.length){case 0:r[i]=this.getOutputScalarCoords();break;case 1:r[i]=this.getOutputUnpacked1DCoords(t,e);break;case 2:r[i]=this.getOutputUnpacked2DCoords(t,e);break;case 3:r[i]=this.getOutputUnpacked3DCoords(t,e);break;case 4:r[i]=this.getOutputUnpacked4DCoords(t,e);break;case 5:r[i]=this.getOutputUnpacked5DCoords(t,e);break;case 6:r[i]=this.getOutputUnpacked6DCoords(t,e);break;default:throw new Error(`Unsupported output dimensionality: ${t.length}`)}const c=` - void setOutput(float val) { - ${(0,p.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0); - } - `;return r.floatTextureSetR=new l.GlslLibRoutine(c),r}getOutputScalarCoords(){return new l.GlslLibRoutine(` - int getOutputCoords() { - return 0; - } - `)}getOutputPacked1DCoords(o,t){const e=t;let r="";return e[0]===1?(r=` - int getOutputCoords() { - return 2 * int(TexCoords.y * ${e[1]}.0); - } - `,new l.GlslLibRoutine(r)):e[1]===1?(r=` - int getOutputCoords() { - return 2 * int(TexCoords.x * ${e[0]}.0); - } - `,new l.GlslLibRoutine(r)):(r=` - int getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - return 2 * (resTexRC.y * ${e[0]} + resTexRC.x); - } - `,new l.GlslLibRoutine(r))}getOutputPacked2DCoords(o,t){let e="";if(d.ArrayUtil.arraysEqual(o,t))return e=` - ivec2 getOutputCoords() { - return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); - } - `,new l.GlslLibRoutine(e);const r=t,i=Math.ceil(o[1]/2);return e=` - ivec2 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${r[0]}, ${r[1]})); - - int index = resTexRC.y * ${r[0]} + resTexRC.x; - - // reverse r and c order for packed texture - int r = imod(index, ${i}) * 2; - int c = 2 * (index / ${i}); - - return ivec2(r, c); - } - `,new l.GlslLibRoutine(e)}getOutputPacked3DCoords(o,t){const e=[t[0],t[1]],r=Math.ceil(o[2]/2),i=r*Math.ceil(o[1]/2),c=` - ivec3 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - int index = resTexRC.y * ${e[0]} + resTexRC.x; - - int b = index / ${i}; - index -= b * ${i}; - - // reverse r and c order for packed texture - int r = imod(index, ${r}) * 2; - int c = 2 * (index / ${r}); - - return ivec3(b, r, c); - } - `;return new l.GlslLibRoutine(c)}getOutputPackedNDCoords(o,t){const e=[t[0],t[1]],r=Math.ceil(o[o.length-1]/2),i=r*Math.ceil(o[o.length-2]/2);let c=i,g="",m="b, r, c";for(let _=2;_=0;--m)i[m]=i[m+1]*o[m+1];const c=["r","c","d"],g=i.map((m,b)=>`int ${c[b]} = index / ${m}; ${b===i.length-1?`int ${c[b+1]} = index - ${c[b]} * ${m}`:`index -= ${c[b]} * ${m}`};`).join("");return e=` - ivec3 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${t[0]}, ${t[1]})); - int index = resTexRC.y * ${t[0]} + resTexRC.x; - ${g} - return ivec3(r, c, d); - } - `,new l.GlslLibRoutine(e)}getOutputUnpacked4DCoords(o,t){let e="";const r=o.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=o[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*o[m+1];const c=["r","c","d","d2"],g=i.map((m,b)=>`int ${c[b]} = index / ${m}; ${b===i.length-1?`int ${c[b+1]} = index - ${c[b]} * ${m}`:`index -= ${c[b]} * ${m}`};`).join("");return e=` - ivec4 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${t[0]}, ${t[1]})); - int index = resTexRC.y * ${t[0]} + resTexRC.x; - ${g} - return ivec4(r, c, d, d2); - } - `,new l.GlslLibRoutine(e)}getOutputUnpacked5DCoords(o,t){let e="";const r=o.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=o[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*o[m+1];const c=["r","c","d","d2","d3"],g=i.map((m,b)=>`int ${c[b]} = index / ${m}; ${b===i.length-1?`int ${c[b+1]} = index - ${c[b]} * ${m}`:`index -= ${c[b]} * ${m}`};`).join("");return e=` - ivec5 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${t[0]}, ${t[1]})); - int index = resTexRC.y * ${t[0]} + resTexRC.x; - ${g} - return ivec5(r, c, d, d2, d3); - } - `,new l.GlslLibRoutine(e)}getOutputUnpacked6DCoords(o,t){let e="";const r=o.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=o[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*o[m+1];const c=["r","c","d","d2","d3","d4"],g=i.map((m,b)=>`int ${c[b]} = index / ${m}; ${b===i.length-1?`int ${c[b+1]} = index - ${c[b]} * ${m}`:`index -= ${c[b]} * ${m}`};`).join("");return e=` - ivec6 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${t[0]}, ${t[1]})); - int index = resTexRC.y * ${t[0]} + resTexRC.x; - ${g} - return ivec6(r, c, d, d2, d3, d4); - } - `,new l.GlslLibRoutine(e)}getCommonUtilFuncs(){const o={};let t="uvFromFlat";o[t]=new l.GlslLibRoutine(` - vec2 uvFromFlat(int texNumR, int texNumC, int index) { - int texC = index / texNumR; - int texR = index - texC * texNumR; - // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to - // v. - return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC); - } - `),t="packedUVfrom1D",o[t]=new l.GlslLibRoutine(` - vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { - int texelIndex = index / 2; - int texR = texelIndex / texNumC; - int texC = texelIndex - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `),t="packedUVfrom2D",o[t]=new l.GlslLibRoutine(` - vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) { - int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); - int texR = texelIndex / texNumC; - int texC = texelIndex - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `),t="packedUVfrom3D",o[t]=new l.GlslLibRoutine(` - vec2 packedUVfrom3D(int texNumR, int texNumC, - int texelsInBatch, int texelsInLogicalRow, int b, - int row, int col) { - int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); - int texR = index / texNumC; - int texC = index - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `),t="sampleTexture";const e=(0,p.getGlsl)(this.context.glContext.version);return o[t]=new l.GlslLibRoutine(` - float sampleTexture(sampler2D textureSampler, vec2 uv) { - return ${e.texture2D}(textureSampler, uv).r; - }`),o}getInputsSamplingSnippets(){const o={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((e,r)=>{const i=this.context.inputTextureLayouts[r],c=(0,h.generateShaderFuncNameFromInputSamplerName)(e);i.isPacked?o[c]=this.getPackedSamplerFromInput(c,e,i):o[c]=this.getUnpackedSamplerFromInput(c,e,i);const g=(0,h.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(e);i.unpackedShape.length<=t.unpackedShape.length&&(i.isPacked?o[g]=this.getPackedSamplerAtOutputCoords(g,i,t,e):o[g]=this.getUnpackedSamplerAtOutputCoords(g,i,t,e))}),o}getPackedSamplerAtOutputCoords(o,t,e,r){const i=t.unpackedShape,c=e.unpackedShape,g=r,m=(0,h.generateShaderFuncNameFromInputSamplerName)(g),b=i.length,_=c.length,w=d.BroadcastUtil.getBroadcastDims(i,c),v=(0,h.getCoordsDataType)(_),S=_-b;let O;const E=(0,h.getGlChannels)();O=b===0?"":_<2&&w.length>=1?"coords = 0;":w.map(N=>`coords.${E[N+S]} = 0;`).join(` -`);let T="";T=_<2&&b>0?"coords":i.map((N,H)=>`coords.${E[H+S]}`).join(", ");let I="return outputValue;";const C=d.ShapeUtil.size(i)===1,B=d.ShapeUtil.size(c)===1;if(b!==1||C||B){if(C&&!B)I=_===1?` - return vec4(outputValue.x, outputValue.x, 0., 0.); - `:` - return vec4(outputValue.x); - `;else if(w.length){const N=b-2,H=b-1;w.indexOf(N)>-1&&w.indexOf(H)>-1?I="return vec4(outputValue.x);":w.indexOf(N)>-1?I="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":w.indexOf(H)>-1&&(I="return vec4(outputValue.xx, outputValue.zz);")}}else I=` - return vec4(outputValue.xy, outputValue.xy); - `;const F=` - vec4 ${o}() { - ${v} coords = getOutputCoords(); - - int lastDim = coords.${E[_-1]}; - coords.${E[_-1]} = coords.${E[_-2]}; - coords.${E[_-2]} = lastDim; - - ${O} - vec4 outputValue = ${m}(${T}); - ${I} - } - `;return new l.GlslLibRoutine(F,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(o,t,e,r){const i=[e.width,e.height],c=[t.width,t.height],g=t.unpackedShape.length,m=e.unpackedShape.length,b=t.unpackedShape,_=e.unpackedShape,w=(0,h.generateShaderFuncNameFromInputSamplerName)(r);if(g===m&&d.ArrayUtil.arraysEqual(c,i)){const B=` - float ${o}() { - return sampleTexture(${r}, TexCoords); - } - `;return new l.GlslLibRoutine(B,["coordinates.sampleTexture"])}const v=(0,h.getCoordsDataType)(m),S=d.BroadcastUtil.getBroadcastDims(b,_),O=m-g;let E;const T=(0,h.getGlChannels)();E=g===0?"":m<2&&S.length>=1?"coords = 0;":S.map(B=>`coords.${T[B+O]} = 0;`).join(` -`);let I="";I=m<2&&g>0?"coords":t.unpackedShape.map((B,F)=>`coords.${T[F+O]}`).join(", ");const C=` - float ${o}() { - ${v} coords = getOutputCoords(); - ${E} - return ${w}(${I}); - } - `;return new l.GlslLibRoutine(C,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(o,t,e){switch(e.unpackedShape.length){case 0:return this.getPackedSamplerScalar(o,t);case 1:return this.getPackedSampler1D(o,t,e);case 2:return this.getPackedSampler2D(o,t,e);case 3:return this.getPackedSampler3D(o,t,e);default:return this.getPackedSamplerND(o,t,e)}}getUnpackedSamplerFromInput(o,t,e){const r=e.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(o,t,e);case 1:return this.getUnpackedSampler1D(o,t,e);case 2:return this.getUnpackedSampler2D(o,t,e);case 3:return this.getUnpackedSampler3D(o,t,e);case 4:return this.getUnpackedSampler4D(o,t,e);case 5:return this.getUnpackedSampler5D(o,t,e);case 6:return this.getUnpackedSampler6D(o,t,e);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(o,t){const e=` - vec4 ${o}() { - return ${(0,p.getGlsl)(this.context.glContext.version).texture2D}(${t}, halfCR); - } - `;return new l.GlslLibRoutine(e)}getPackedSampler1D(o,t,e){const r=[e.width,e.height],i=[r[1],r[0]],c=(0,p.getGlsl)(this.context.glContext.version),g=`vec4 ${o}(int index) { - vec2 uv = packedUVfrom1D( - ${i[0]}, ${i[1]}, index); - return ${c.texture2D}(${t}, uv); - }`;return new l.GlslLibRoutine(g,["coordinates.packedUVfrom1D"])}getPackedSampler2D(o,t,e){const r=e.unpackedShape,i=[e.width,e.height],c=(0,p.getGlsl)(this.context.glContext.version),g=i[0],m=i[1];if(i!=null&&d.ArrayUtil.arraysEqual(r,i)){const v=`vec4 ${o}(int row, int col) { - vec2 uv = (vec2(col, row) + halfCR) / vec2(${m}.0, ${g}.0); - return ${c.texture2D}(${t}, uv); - }`;return new l.GlslLibRoutine(v)}const b=i,_=Math.ceil(r[1]/2),w=`vec4 ${o}(int row, int col) { - vec2 uv = packedUVfrom2D(${b[1]}, ${b[0]}, ${_}, row, col); - return ${c.texture2D}(${t}, uv); - }`;return new l.GlslLibRoutine(w,["coordinates.packedUVfrom2D"])}getPackedSampler3D(o,t,e){const r=e.unpackedShape,i=[e.width,e.height],c=[i[0],i[1]],g=(0,p.getGlsl)(this.context.glContext.version);if(r[0]===1){const v=r.slice(1),S=[1,2],O=(0,h.squeezeInputShape)(r,v),E=["b","row","col"],T=JSON.parse(JSON.stringify(e));T.unpackedShape=O;const I=this.getPackedSamplerFromInput(o,t,T),C=`${I.routineBody} - vec4 ${o}(int b, int row, int col) { - return ${o}(${(0,h.getSqueezedParams)(E,S)}); - } `;return new l.GlslLibRoutine(C,I.dependencies)}const m=c[0],b=c[1],_=Math.ceil(r[2]/2),w=`vec4 ${o}(int b, int row, int col) { - vec2 uv = packedUVfrom3D( - ${b}, ${m}, ${_*Math.ceil(r[1]/2)}, ${_}, b, row, col); - return ${g.texture2D}(${t}, uv);}`;return new l.GlslLibRoutine(w,["coordinates.packedUVfrom3D"])}getPackedSamplerND(o,t,e){const r=e.unpackedShape,i=r.length,c=[e.width,e.height],g=(0,p.getGlsl)(this.context.glContext.version),m=[c[0],c[1]],b=m[1],_=m[0],w=Math.ceil(r[i-1]/2);let v=w*Math.ceil(r[i-2]/2),S="int b, int row, int col",O=`b * ${v} + (row / 2) * ${w} + (col / 2)`;for(let T=2;T{const r=this.context.inputTextureLayouts[e],i=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let c=`_${t}`;o[c]=new l.GlslLibRoutine(this.getValueFromSingle(t,i,r.width,r.height,!1),[`shapeUtils.indicesToOffset${c}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),c+="_T",o[c]=new l.GlslLibRoutine(this.getValueFromSingle(t,i,r.width,r.height,!0),[`shapeUtils.indicesToOffset${c}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),o}getValueFromSingle(o,t,e,r,i){let c=`_${o}`;return i&&(c+="_T"),` - float ${c}(int m[${t}]) { - int offset = indicesToOffset${c}(m); - vec2 coords = offsetToCoords(offset, ${e}, ${r}); - float value = getColorAsFloat(${(0,p.getGlsl)(this.context.glContext.version).texture2D}(${o}, coords)); - return value; - } - `}getPackedValueFrom(o,t,e,r,i){let c=`_${o}_Pack`;return i&&(c+="_T"),` - vec4 ${c}(int m[${t}]) { - int offset = indicesToOffset_${o}(m); - vec2 coords = offsetToCoords(offset, ${e}, ${r}); - return ${(0,p.getGlsl)(this.context.glContext.version).texture2D}(${o}, coords); - } - `}}n.CoordsGlslLib=f},8520:(y,n)=>{var u;Object.defineProperty(n,"__esModule",{value:!0}),n.TopologicalSortGlslRoutines=n.GlslLibRoutineNode=n.GlslLibRoutine=n.GlslLib=n.GlslContext=n.FunctionType=void 0,(u=n.FunctionType||(n.FunctionType={}))[u.ValueBased=0]="ValueBased",u[u.Positional=1]="Positional",n.GlslContext=class{constructor(d,l,p,s){this.glContext=d,this.programInfo=l,this.inputTextureLayouts=p,this.outputTextureLayout=s}},n.GlslLib=class{constructor(d){this.context=d}},n.GlslLibRoutine=class{constructor(d,l){this.routineBody=d,this.dependencies=l}},n.GlslLibRoutineNode=class{constructor(d,l,p){this.name=d,this.dependencies=p||[],l&&(this.routineBody=l)}addDependency(d){d&&this.dependencies.push(d)}},n.TopologicalSortGlslRoutines=class{static returnOrderedNodes(d){if(!d||d.length===0)return[];if(d.length===1)return d;const l=new Set,p=new Set,s=new Array;return this.createOrderedNodes(d,l,p,s),s}static createOrderedNodes(d,l,p,s){for(let h=0;h0)for(let f=0;f{Object.defineProperty(n,"__esModule",{value:!0}),n.EncodingGlslLib=void 0;const d=u(8520);class l extends d.GlslLib{constructor(s){super(s)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new d.GlslLibRoutine(`highp vec4 encode(highp float f) { - return vec4(f, 0.0, 0.0, 0.0); - } - `)}}decodeFloat32(){return{decode:new d.GlslLibRoutine(`highp float decode(highp vec4 rgba) { - return rgba.r; - } - `)}}encodeUint8(){const s=l.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new d.GlslLibRoutine(` - highp vec4 encode(highp float f) { - highp float F = abs(f); - highp float Sign = step(0.0,-f); - highp float Exponent = floor(log2(F)); - highp float Mantissa = (exp2(- Exponent) * F); - Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); - highp vec4 rgba; - rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); - rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); - rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); - rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); - ${s} - rgba = rgba / 255.0; // values need to be normalized to [0,1] - return rgba; - } - `)}}decodeUint8(){const s=l.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new d.GlslLibRoutine(` - highp float decode(highp vec4 rgba) { - rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] - ${s} - highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; - highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; - highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); - highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); - return Result; - } - `)}}static isLittleEndian(){const s=new ArrayBuffer(4),h=new Uint32Array(s),f=new Uint8Array(s);if(h[0]=3735928559,f[0]===239)return!0;if(f[0]===222)return!1;throw new Error("unknown endianness")}}n.EncodingGlslLib=l},9894:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.FragColorGlslLib=void 0;const d=u(8520),l=u(5060);class p extends d.GlslLib{constructor(h){super(h)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const h=(0,l.getGlsl)(this.context.glContext.version);return{setFragColor:new d.GlslLibRoutine(` - void setFragColor(float value) { - ${h.output} = encode(value); - } - `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new d.GlslLibRoutine(` - float getColorAsFloat(vec4 color) { - return decode(color); - } - `,["encoding.decode"])}}}n.FragColorGlslLib=p},2848:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.replaceInlines=void 0;const u=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;n.replaceInlines=function(d){const l={};let p;for(;(p=u.exec(d))!==null;){const s=p[3].split(",").map(h=>{const f=h.trim().split(" ");return f&&f.length===2?{type:f[0],name:f[1]}:null}).filter(h=>h!==null);l[p[2]]={params:s,body:p[4]}}for(const s in l){const h="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",s),f=new RegExp(h,"gm");for(;(p=f.exec(d))!==null;){const a=p[1],o=p[2],t=p[3].split(","),e=a?`${a} ${o};`:"";let r=l[s].body,i="";l[s].params.forEach((g,m)=>{g&&(i+=`${g.type} ${g.name} = ${t[m]}; -`)}),r=`${i} - ${r}`,r=r.replace("return",`${o} = `);const c=` - ${e} - { - ${r} - } - `;d=d.replace(p[0],c)}}return d.replace(u,"")}},8879:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.GlslPreprocessor=void 0;const d=u(8520),l=u(2848),p=u(5483),s=u(5060);n.GlslPreprocessor=class{constructor(h,f,a,o){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new d.GlslContext(h,f,a,o),Object.keys(p.glslRegistry).forEach(e=>{const r=new p.glslRegistry[e](this.context);this.libs[e]=r});const t=this.glslLibRoutineDependencyGraph;for(const e in this.libs){const r=this.libs[e].getFunctions();for(const i in r){const c=e+"."+i;let g;t[c]?(g=t[c],g.routineBody=r[i].routineBody):(g=new d.GlslLibRoutineNode(c,r[i].routineBody),t[c]=g);const m=r[i].dependencies;if(m)for(let b=0;b{const o=a.split(".")[1];h.indexOf(o)!==-1&&f.push(this.glslLibRoutineDependencyGraph[a])}),d.TopologicalSortGlslRoutines.returnOrderedNodes(f)}getUniforms(h,f){const a=[];if(h)for(const o of h)a.push(`uniform sampler2D ${o};`);if(f)for(const o of f)a.push(`uniform ${o.type} ${o.name}${o.arrayLength?`[${o.arrayLength}]`:""};`);return a.join(` -`)}}},5483:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.glslRegistry=void 0;const d=u(5107),l=u(7341),p=u(9894),s=u(2655),h=u(3891);n.glslRegistry={encoding:l.EncodingGlslLib,fragcolor:p.FragColorGlslLib,vec:h.VecGlslLib,shapeUtils:s.ShapeUtilsGlslLib,coordinates:d.CoordsGlslLib}},2655:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ShapeUtilsGlslLib=void 0;const d=u(8520);class l extends d.GlslLib{constructor(s){super(s)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const s=this.context.outputTextureLayout.shape.length,h={};return this.context.programInfo.inputNames.forEach((f,a)=>{const o=this.context.inputTextureLayouts[a].unpackedShape;if(o.length<=s){const t=o.length,e=s-t,r=`bcastIndices_${f}`;let i="";for(let g=0;g{const o=this.context.inputTextureLayouts[a].shape;if(!(o.length<2||o.length>s)){const t=o.length,e=s-t,r=`bcastMatmulIndices_${f}`;let i="";for(let g=0;g{const a=this.context.inputTextureLayouts[f].shape,o=this.context.inputTextureLayouts[f].strides,t=a.length;let e=`indicesToOffset_${h}`;s[e]=new d.GlslLibRoutine(l.indexToOffsetSingle(e,t,o)),e=`indicesToOffset_${h}_T`,s[e]=new d.GlslLibRoutine(l.indexToOffsetSingle(e,t,o.slice().reverse()))}),s}static indexToOffsetSingle(s,h,f){let a="";for(let o=h-1;o>=0;--o)a+=` - offset += indices[${o}] * ${f[o]}; - `;return` - int ${s}(int indices[${h}]) { - int offset = 0; - ${a} - return offset; - } - `}offsetToIndices(){const s={};return this.context.programInfo.inputNames.forEach((h,f)=>{const a=this.context.inputTextureLayouts[f].shape,o=this.context.inputTextureLayouts[f].strides,t=a.length;let e=`offsetToIndices_${h}`;s[e]=new d.GlslLibRoutine(l.offsetToIndicesSingle(e,t,o)),e=`offsetToIndices_${h}_T`,s[e]=new d.GlslLibRoutine(l.offsetToIndicesSingle(e,t,o.slice().reverse()))}),s}static offsetToIndicesSingle(s,h,f){const a=[];for(let o=0;o{const a=this.context.inputTextureLayouts[f].shape,o=a.length,t=`incrementIndices_${h}`;let e="";for(let i=0;i= 0; --i) { - if(i > axis) continue; - indices[i] += 1; - if(indices[i] < shape[i]) { - break; - } - indices[i] = 0; - } - } - `;s[t]=new d.GlslLibRoutine(r)}),s}}n.ShapeUtilsGlslLib=l},5060:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultFragShaderMain=n.getFragShaderPreamble=n.getVertexShaderSource=n.getGlsl=void 0;const u={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},d={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function l(p){return p===1?u:d}n.getGlsl=l,n.getVertexShaderSource=function(p){const s=l(p);return`${s.version} - precision highp float; - ${s.attribute} vec3 position; - ${s.attribute} vec2 textureCoord; - - ${s.varyingVertex} vec2 TexCoords; - - void main() - { - gl_Position = vec4(position, 1.0); - TexCoords = textureCoord; - }`},n.getFragShaderPreamble=function(p){const s=l(p);return`${s.version} - precision highp float; - precision highp int; - precision highp sampler2D; - ${s.varyingFrag} vec2 TexCoords; - ${s.outputDeclaration} - const vec2 halfCR = vec2(0.5, 0.5); - - // Custom vector types to handle higher dimenalities. - struct ivec5 - { - int x; - int y; - int z; - int w; - int u; - }; - - struct ivec6 - { - int x; - int y; - int z; - int w; - int u; - int v; - }; - - int imod(int x, int y) { - return x - y * (x / y); - } - - `},n.getDefaultFragShaderMain=function(p,s){return` - void main() { - int indices[${s}]; - toVec(TexCoords, indices); - vec4 result = vec4(process(indices)); - ${l(p).output} = result; - } - `}},3891:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.VecGlslLib=void 0;const d=u(8520);class l extends d.GlslLib{constructor(s){super(s)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const s=this.context.outputTextureLayout.shape.length,h={add:"+=",sub:"-=",mul:"*=",div:"/="},f={};for(const a in h){const o=`${a}Vec`;let t="";for(let r=0;r{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLInferenceHandler=void 0;const d=u(6231),l=u(9162),p=u(2517),s=u(2403),h=u(7019),f=u(8710),a=u(5611),o=u(4057),t=u(2039);n.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,r){return(0,o.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,r)}executeProgram(e,r){if(r.length{const S=v.map(E=>`${E.unpackedShape.join(",")};${E.width}x${E.height}`).join("_");let O=w.name;return w.cacheHint&&(O+="["+w.cacheHint+"]"),O+=":"+S,O})(e,i);let g=this.session.programManager.getArtifact(c);const m=g?g.programInfo:typeof e.get=="function"?e.get():e,b=(0,o.createTextureLayoutFromTextureType)(this.session.layoutStrategy,m.output.dims,m.output.textureType),_=this.createTextureData(b,m.output.type);return g||(g=this.session.programManager.build(m,i,_),this.session.programManager.setArtifact(c,g)),this.runProgram(g,i,_),_}run(e,r){return this.executeProgram(e,r).tensor}runProgram(e,r,i){for(let c=0;cthis.readTexture(m),async b=>this.readTextureAsync(m),void 0,g),texture:i});return this.setTextureData(m.tensor.dataId,m,e.isPacked),m}getTextureData(e,r=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,r):r?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,r,i=!1){this.session.isInitializer(e)?this.session.setTextureData(e,r,i):(i?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,r)}isTextureLayoutCached(e,r=!1){return!!this.getTextureData(e.dataId,r)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,f.encodeAsUint8)(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,f.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,s.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,a.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},1640:function(y,n,u){var d=this&&this.__createBinding||(Object.create?function(X,te,ne,me){me===void 0&&(me=ne);var Ie=Object.getOwnPropertyDescriptor(te,ne);Ie&&!("get"in Ie?!te.__esModule:Ie.writable||Ie.configurable)||(Ie={enumerable:!0,get:function(){return te[ne]}}),Object.defineProperty(X,me,Ie)}:function(X,te,ne,me){me===void 0&&(me=ne),X[me]=te[ne]}),l=this&&this.__setModuleDefault||(Object.create?function(X,te){Object.defineProperty(X,"default",{enumerable:!0,value:te})}:function(X,te){X.default=te}),p=this&&this.__importStar||function(X){if(X&&X.__esModule)return X;var te={};if(X!=null)for(var ne in X)ne!=="default"&&Object.prototype.hasOwnProperty.call(X,ne)&&d(te,X,ne);return l(te,X),te};Object.defineProperty(n,"__esModule",{value:!0}),n.WEBGL_OP_RESOLVE_RULES=void 0;const s=u(2898),h=p(u(7839)),f=u(4196),a=u(2069),o=u(8138),t=u(9663),e=u(5193),r=u(7992),i=u(1253),c=u(4776),g=u(6572),m=u(3346),b=u(5623),_=u(2870),w=u(2143),v=u(4939),S=u(718),O=u(2268),E=u(8117),T=u(2278),I=u(5524),C=u(5975),B=u(3933),F=u(6558),N=u(5723),H=u(3738),$=p(u(4909)),z=u(8428),Q=u(9793);n.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",$.abs],["Acos","","7+",$.acos],["Add","","7+",h.add],["And","","7+",h.and],["Asin","","7+",$.asin],["Atan","","7+",$.atan],["AveragePool","","7+",w.averagePool,w.parseAveragePoolAttributes],["BatchNormalization","","7+",s.batchNormalization,s.parseBatchNormalizationAttributes],["Cast","","6+",f.cast,f.parseCastAttributes],["Ceil","","6+",$.ceil],["Clip","","6-10",$.clip,$.parseClipAttributes],["Clip","","11+",$.clipV11],["Concat","","4+",a.concat,a.parseConcatAttributes],["Conv","","1+",o.conv,o.parseConvAttributes],["ConvTranspose","","1+",t.convTranspose,t.parseConvTransposeAttributes],["Cos","","7+",$.cos],["Div","","7+",h.div],["Dropout","","7+",$.identity],["DepthToSpace","","1+",e.depthToSpace,e.parseDepthToSpaceAttributes],["Equal","","7+",h.equal],["Elu","","6+",$.elu,$.parseEluAttributes],["Exp","","6+",$.exp],["Flatten","","1+",r.flatten,r.parseFlattenAttributes],["Floor","","6+",$.floor],["FusedConv","com.microsoft","1+",o.conv,o.parseConvAttributes],["Gather","","1+",i.gather,i.parseGatherAttributes],["Gemm","","7-10",c.gemm,c.parseGemmAttributesV7],["Gemm","","11+",c.gemm,c.parseGemmAttributesV11],["GlobalAveragePool","","1+",w.globalAveragePool,w.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",w.globalMaxPool],["Greater","","7+",h.greater],["Identity","","1+",$.identity],["ImageScaler","","1+",g.imageScaler,g.parseImageScalerAttributes],["InstanceNormalization","","6+",m.instanceNormalization,m.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",$.leakyRelu,$.parseLeakyReluAttributes],["Less","","7+",h.less],["Log","","6+",$.log],["MatMul","","1+",b.matMul,b.parseMatMulAttributes],["MaxPool","","1+",w.maxPool,w.parseMaxPoolAttributes],["Mul","","7+",h.mul],["Neg","","6+",$.neg],["Not","","1+",$.not],["Or","","7+",h.or],["Pad","","2-10",_.padV2,_.parsePadAttributesV2],["Pad","","11+",_.padV11,_.parsePadAttributesV11],["Pow","","7+",h.pow],["PRelu","","7+",h.pRelu],["ReduceLogSum","","1+",v.reduceLogSum,v.parseReduceAttributes],["ReduceMax","","1+",v.reduceMax,v.parseReduceAttributes],["ReduceMean","","1+",v.reduceMean,v.parseReduceAttributes],["ReduceMin","","1+",v.reduceMin,v.parseReduceAttributes],["ReduceProd","","1+",v.reduceProd,v.parseReduceAttributes],["ReduceSum","","1-12",v.reduceSum,v.parseReduceAttributes],["ReduceSumSquare","","1+",v.reduceLogSumSquare,v.parseReduceAttributes],["Relu","","6+",$.relu],["Reshape","","5+",S.reshape],["Resize","","10",O.resize,O.parseResizeAttributesV10],["Resize","","11+",O.resize,O.parseResizeAttributesV11],["Shape","","1+",E.shape],["Sigmoid","","6+",$.sigmoid],["Sin","","7+",$.sin],["Slice","","10+",T.sliceV10],["Slice","","1-9",T.slice,T.parseSliceAttributes],["Softmax","","1-12",I.softmax,I.parseSoftmaxAttributes],["Softmax","","13+",I.softmaxV13,I.parseSoftmaxAttributesV13],["Split","","2-12",C.split,C.parseSplitAttributes],["Sqrt","","6+",$.sqrt],["Squeeze","","1-12",B.squeeze,B.parseSqueezeAttributes],["Squeeze","","13+",B.squeezeV13],["Sub","","7+",h.sub],["Sum","","6+",F.sum],["Tan","","7+",$.tan],["Tanh","","6+",$.tanh],["Tile","","6+",N.tile],["Transpose","","1+",H.transpose,H.parseTransposeAttributes],["Upsample","","7-8",Q.upsample,Q.parseUpsampleAttributesV7],["Upsample","","9",Q.upsample,Q.parseUpsampleAttributesV9],["Unsqueeze","","1-12",z.unsqueeze,z.parseUnsqueezeAttributes],["Unsqueeze","","13+",z.unsqueezeV13],["Xor","","7+",h.xor]]},2898:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseBatchNormalizationAttributes=n.batchNormalization=void 0;const d=u(246),l=u(5060),p=u(2039),s={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[p.TextureType.unpacked,p.TextureType.unpacked,p.TextureType.unpacked,p.TextureType.unpacked,p.TextureType.unpacked]};n.batchNormalization=(a,o,t)=>(f(o),[a.run(Object.assign(Object.assign({},s),{cacheHint:t.cacheKey,get:()=>h(a,o,t)}),o)]),n.parseBatchNormalizationAttributes=a=>{const o=a.attributes.getFloat("epsilon",1e-5),t=a.attributes.getFloat("momentum",.9),e=a.attributes.getInt("spatial",1);return(0,d.createAttributeWithCacheKey)({epsilon:o,momentum:t,spatial:e})};const h=(a,o,t)=>{const e=(0,l.getGlsl)(a.session.backend.glContext.version),r=o[0].dims.length,[i,c]=a.calculateTextureWidthAndHeight(o[1].dims,p.TextureType.unpacked),g=` - float process(int[${r}] indices) { - vec2 position = offsetToCoords(indices[1], ${i}, ${c}); - float scale = getColorAsFloat(${e.texture2D}(Scale, position)); - float mean = getColorAsFloat(${e.texture2D}(Mean, position)); - float variance = getColorAsFloat(${e.texture2D}(Variance, position)); - float b = getColorAsFloat(${e.texture2D}(B, position)); - - return scale * ( (_A(indices) - mean) / sqrt(variance + float(${t.epsilon})) ) + b; - }`;return Object.assign(Object.assign({},s),{output:{dims:o[0].dims,type:o[0].type,textureType:p.TextureType.unpacked},shaderSource:g})},f=a=>{if(!a||a.length!==5)throw new Error("BatchNormalization requires 5 inputs.");const o=a[0],t=a[1],e=a[2],r=a[3],i=a[4];if(o.dims.length<3||t.dims.length!==1||e.dims.length!==1||r.dims.length!==1||i.dims.length!==1)throw new Error("invalid input shape.");if(t.dims[0]!==o.dims[1]||e.dims[0]!==o.dims[1]||r.dims[0]!==o.dims[1]||i.dims[0]!==o.dims[1])throw new Error("invalid input shape.");if(o.type!=="float32"&&o.type!=="float64"||t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64"||i.type!=="float32"&&i.type!=="float64")throw new Error("invalid input tensor types.")}},7839:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.xor=n.sub=n.pRelu=n.pow=n.or=n.mul=n.less=n.greater=n.equal=n.div=n.and=n.add=n.glslPRelu=n.glslPow=n.glslXor=n.glslOr=n.glslAnd=n.glslLess=n.glslGreater=n.glslEqual=n.glslSub=n.glslMul=n.glslDiv=n.glslAdd=void 0;const d=u(2517),l=u(8520),p=u(5060),s=u(2039);function h(){const v="add_";return{body:` - float ${v}(float a, float b) { - return a + b; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return v1 + v2; - } - `,name:v,type:l.FunctionType.ValueBased}}function f(){const v="div_";return{body:` - float ${v}(float a, float b) { - return a / b; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return v1 / v2; - } - `,name:v,type:l.FunctionType.ValueBased}}function a(){const v="mul_";return{body:` - float ${v}(float a, float b) { - return a * b; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return v1 * v2; - } - `,name:v,type:l.FunctionType.ValueBased}}function o(){const v="sub_";return{body:` - float ${v}(float a, float b) { - return a - b; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return v1 - v2; - } - `,name:v,type:l.FunctionType.ValueBased}}function t(){const v="equal_";return{body:` - float ${v}(float a, float b) { - return float(a == b); - } - vec4 ${v}(vec4 v1, vec4 v2) { - return vec4(equal(v1, v2)); - } - `,name:v,type:l.FunctionType.ValueBased}}function e(){const v="greater_";return{body:` - float ${v}(float a, float b) { - return float(a > b); - } - vec4 ${v}(vec4 v1, vec4 v2) { - return vec4( v1.r > v2.r , - v1.g > v2.g, - v1.b > v2.b, - v1.a > v2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function r(){const v="less_";return{body:` - float ${v}(float a, float b) { - return float(a < b); - } - vec4 ${v}(vec4 v1, vec4 v2) { - return vec4( v1.r < v2.r , - v1.g < v2.g, - v1.b < v2.b, - v1.a < v2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function i(){const v="and_";return{body:` - float ${v}(float a, float b) { - return float( bool(a) && bool(b) ); - } - vec4 ${v}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r && b2.r , - b1.g && b2.g, - b1.b && b2.b, - b1.a && b2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function c(){const v="or_";return{body:` - float ${v}(float a, float b) { - return float( bool(a) || bool(b) ); - } - vec4 ${v}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r || b2.r , - b1.g || b2.g, - b1.b || b2.b, - b1.a || b2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function g(){const v="xor_";return{body:` - float ${v}(float a, float b) { - return float( bool(a) ^^ bool(b) ); - } - vec4 ${v}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r ^^ b2.r , - b1.g ^^ b2.g, - b1.b ^^ b2.b, - b1.a ^^ b2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function m(){return function(v){const S=`${v}_`;return{body:` - float ${S}(float a, float b) { - return ${v}(a, b); - } - vec4 ${S}(vec4 v1, vec4 v2) { - return ${v}(v1, v2); - } - `,name:S,type:l.FunctionType.ValueBased}}("pow")}function b(){const v="prelu_";return{body:` - float ${v}(float a, float b) { - return a < 0.0 ? a * b: a; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return vec4( - v1.r < 0.0 ? v1.r * v2.r: v1.r, - v1.g < 0.0 ? v1.g * v2.g: v1.g, - v1.b < 0.0 ? v1.b * v2.b: v1.b, - v1.a < 0.0 ? v1.a * v2.a: v1.a - ); - } - `,name:v,type:l.FunctionType.ValueBased}}n.glslAdd=h,n.glslDiv=f,n.glslMul=a,n.glslSub=o,n.glslEqual=t,n.glslGreater=e,n.glslLess=r,n.glslAnd=i,n.glslOr=c,n.glslXor=g,n.glslPow=m,n.glslPRelu=b;const _=(v,S,O,E=S[0].type,T)=>{const I=v.session.pack?s.TextureType.packed:s.TextureType.unpacked;return{name:O.name,inputNames:["A","B"],inputTypes:[I,I],cacheHint:T,get:()=>w(v,S,O,E)}},w=(v,S,O,E=S[0].type)=>{const T=v.session.pack?s.TextureType.packed:s.TextureType.unpacked,I=!d.ShapeUtil.areEqual(S[0].dims,S[1].dims);let C=S[0].dims;const B=v.session.pack;if(I){const H=d.BroadcastUtil.calcShape(S[0].dims,S[1].dims,!1);if(!H)throw new Error("Can't perform binary op on the given tensors");C=H;const $=C.length,z=S[0].dims.length!==0?S[0].dims.length:1,Q=S[1].dims.length!==0?S[1].dims.length:1,X=S[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",te=S[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",ne=(0,p.getGlsl)(v.session.backend.glContext.version),me=B?` - ${O.body} - void main() { - vec4 a = getAAtOutCoords(); - vec4 b = getBAtOutCoords(); - vec4 result = ${O.name}(a, b); - ${ne.output} = result; - }`:` - ${O.body} - float process(int indices[${$}]) { - int aindices[${z}]; - int bindices[${Q}]; - ${X} - ${te} - return ${O.name}(_A(aindices), _B(bindices)); - }`;return{name:O.name,inputNames:["A","B"],inputTypes:[T,T],output:{dims:C,type:E,textureType:T},shaderSource:me,hasMain:B}}const F=(0,p.getGlsl)(v.session.backend.glContext.version),N=` - ${O.body} - void main() { - vec4 v1 = ${F.texture2D}(A, TexCoords); - vec4 v2 = ${F.texture2D}(B, TexCoords); - vec4 result = ${O.name}(v1, v2); - ${F.output} = result; - } - `;return{name:O.name,inputNames:["A","B"],inputTypes:[T,T],output:{dims:S[0].dims,type:E,textureType:T},shaderSource:N,hasMain:!0}};n.add=(v,S)=>[v.run(_(v,S,h()),S)],n.and=(v,S)=>[v.run(_(v,S,i(),"bool"),S)],n.div=(v,S)=>[v.run(_(v,S,f()),S)],n.equal=(v,S)=>[v.run(_(v,S,t(),"bool"),S)],n.greater=(v,S)=>[v.run(_(v,S,e(),"bool"),S)],n.less=(v,S)=>[v.run(_(v,S,r(),"bool"),S)],n.mul=(v,S)=>[v.run(_(v,S,a()),S)],n.or=(v,S)=>[v.run(_(v,S,c(),"bool"),S)],n.pow=(v,S)=>[v.run(_(v,S,m()),S)],n.pRelu=(v,S)=>[v.run(_(v,S,b()),S)],n.sub=(v,S)=>[v.run(_(v,S,o()),S)],n.xor=(v,S)=>[v.run(_(v,S,g(),"bool"),S)]},4196:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseCastAttributes=n.cast=void 0;const d=u(2517);n.cast=(p,s,h)=>(l(s),[p.cast(s[0],h)]),n.parseCastAttributes=p=>d.ProtoUtil.tensorDataTypeFromProto(p.attributes.getInt("to"));const l=p=>{if(!p||p.length!==1)throw new Error("Cast requires 1 input.");if(p[0].type==="string")throw new Error("Invalid input type.")}},1163:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedConcatProgramInfoLoader=void 0;const d=u(5060),l=u(2039),p=u(9390),s=u(2827);n.createPackedConcatProgramInfoLoader=(f,a,o)=>{const t=(e=a.length,r=o.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:e},(i,c)=>`X${c}`),inputTypes:Array(e).fill(l.TextureType.packed),cacheHint:r});var e,r;return Object.assign(Object.assign({},t),{get:()=>((i,c,g,m)=>{const b=g[0].dims.slice();if(m>=b.length||m<-1*b.length)throw new Error("axis specified for concat doesn't match input dimensionality");m<0&&(m=b.length+m);const _=b.slice(0);for(let X=1;XX.dims),T=(0,p.getGlChannels)(w),I=new Array(E.length-1);I[0]=E[0][m];for(let X=1;X= ${I[X-1]}) { - return getChannel( - getX${X}(${h(T,C,te)}), - vec2(${h(B,C,te)})); - }`}const H=I.length,$=I[I.length-1];N+=` - return getChannel( - getX${H}(${h(T,C,$)}), - vec2(${h(B,C,$)}));`;const z=(0,d.getGlsl)(i.session.backend.glContext.version),Q=` - ${O} - float getValue(${T.map(X=>"int "+X)}) { - ${N} - } - - void main() { - ${S} coords = getOutputCoords(); - int lastDim = coords.${T[w-1]}; - coords.${T[w-1]} = coords.${T[w-2]}; - coords.${T[w-2]} = lastDim; - - vec4 result = vec4(getValue(${v}), 0., 0., 0.); - - ${v[w-1]} = ${v[w-1]} + 1; - if (${v[w-1]} < ${_[w-1]}) { - result.g = getValue(${v}); - } - - ${v[w-2]} = ${v[w-2]} + 1; - if (${v[w-2]} < ${_[w-2]}) { - result.a = getValue(${v}); - } - - ${v[w-1]} = ${v[w-1]} - 1; - if (${v[w-2]} < ${_[w-2]} && - ${v[w-1]} < ${_[w-1]}) { - result.b = getValue(${v}); - } - ${z.output} = result; - } - `;return Object.assign(Object.assign({},c),{output:{dims:_,type:g[0].type,textureType:l.TextureType.packed},shaderSource:Q,hasMain:!0})})(f,t,a,o.axis)})};const h=(f,a,o)=>{const t=f.indexOf(a);return f.map((e,r)=>r===t?`${e} - ${o}`:e).join()}},2069:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConcatAttributes=n.concat=void 0;const d=u(246),l=u(2039),p=u(1163);n.concat=(e,r,i)=>(t(r),e.session.pack&&r[0].dims.length>1?[e.run((0,p.createPackedConcatProgramInfoLoader)(e,r,i),r)]:[e.run(s(e,r,i),r)]);const s=(e,r,i)=>{const c=(g=r.length,m=i.cacheKey,{name:"Concat",inputNames:Array.from({length:g},(b,_)=>`X${_}`),inputTypes:Array(g).fill(l.TextureType.unpacked),cacheHint:m});var g,m;return Object.assign(Object.assign({},c),{get:()=>((b,_,w,v)=>{const S=w[0].dims.slice();if(v>=S.length||v<-1*S.length)throw new Error("axis specified for concat doesn't match input dimensionality");v<0&&(v=S.length+v);const O=S.slice(0);for(let F=1;F`int getTextureWhereDataResides(int index) { - ${e.map((r,i)=>`if(index<${r}) {return ${i};} -`).join("")} - }`,f=e=>h(e),a=(e,r)=>{const i=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${r}]) {`];for(let c=0;c{const r=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let i=0;i(0,d.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const t=e=>{if(!e||e.length<1)throw new Error("too few inputs");const r=e[0].type,i=e[0].dims.length;if(r==="string")throw new Error("string tensor is not supported yet");for(const c of e){if(c.type!==r)throw new Error("input tensors should be one type");if(c.dims.length!==i)throw new Error("input tensors should have the same shape")}}},4770:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createUnpackedGroupedConvProgramInfoLoader=void 0;const d=u(6231),l=u(5060),p=u(2039),s=u(8138),h=u(2823);n.createUnpackedGroupedConvProgramInfoLoader=(f,a,o)=>{const t=(e=a.length>2,r=o.cacheKey,{name:"GroupedConv",inputNames:e?["X","W","Bias"]:["X","W"],inputTypes:e?[p.TextureType.unpacked,p.TextureType.unpacked,p.TextureType.unpacked]:[p.TextureType.unpacked,p.TextureType.unpacked],cacheHint:r});var e,r;return Object.assign(Object.assign({},t),{get:()=>((i,c,g,m)=>{const b=c.length>2?"value += getBias(output_channel);":"",_=c[0].dims.slice(),w=c[1].dims.slice(),v=w[0]/m.group;d.Logger.verbose("GroupedConv",`autpPad:${m.autoPad}, dilations:${m.dilations}, group:${m.group}, kernelShape:${m.kernelShape}, pads:${m.pads}, strides:${m.strides}`);const S=(0,s.calculateOutputShape)(_,w,m.dilations,m.pads,m.strides),O=(0,l.getGlsl)(i.session.backend.glContext.version),{activationFunction:E,applyActivation:T}=(0,h.getActivationSnippet)(m),I=` - const ivec2 strides = ivec2(${m.strides[0]}, ${m.strides[1]}); - const ivec2 pads = ivec2(${m.pads[0]}, ${m.pads[1]}); - ${E} - void main() { - ivec4 coords = getOutputCoords(); - int batch = coords.x; - int output_channel = coords.y; - ivec2 xRCCorner = coords.zw * strides - pads; - int group_id = output_channel / ${v}; - - float value = 0.0; - for (int wInChannel = 0; wInChannel < ${w[1]}; wInChannel++) { - int input_channel = group_id * ${w[1]} + wInChannel; - for (int wHeight = 0; wHeight < ${w[2]}; wHeight++) { - int xHeight = xRCCorner.x + wHeight * ${m.dilations[0]}; - - if (xHeight < 0 || xHeight >= ${_[2]}) { - continue; - } - - for (int wWidth = 0; wWidth < ${w[3]}; wWidth++) { - int xWidth = xRCCorner.y + wWidth * ${m.dilations[1]}; - if (xWidth < 0 || xWidth >= ${_[3]}) { - continue; - } - - float xVal = getX(batch, input_channel, xWidth, xHeight); - float wVal = getW(output_channel, wInChannel, wWidth, wHeight); - value += xVal*wVal; - } - } - } - ${b} - ${T} - ${O.output} = vec4(value, .0, .0, .0); - } -`;return Object.assign(Object.assign({},g),{output:{dims:S,type:c[0].type,textureType:p.TextureType.unpacked},shaderSource:I,hasMain:!0})})(f,a,t,o)})}},1386:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.conv2DPacked=n.conv2DPackedPointwise=void 0;const d=u(8138),l=u(8555),p=u(708);n.conv2DPackedPointwise=(s,h,f)=>{const a=h[0].dims,o=h[1].dims,t=(0,d.calculateOutputShape)(a,o,f.dilations,f.pads,f.strides),e=s.reshapePacked(h[0],[a[1],a[2]*a[3]]),r=s.reshapePacked(h[1],[o[0],o[1]]),i=h.length>2?[r,e,h[2]]:[r,e],c=s.run((0,p.createPackedMatmulProgramInfoLoader)(s,i,f),i);return s.reshapePacked(c,t)},n.conv2DPacked=(s,h,f)=>{const a=h[0].dims,o=h[1].dims,t=(0,d.calculateOutputShape)(a,o,f.dilations,f.pads,f.strides),e=s.run((0,l.createPackedIm2ColProgramInfoLoader)(s,h[0],h[1],t,f),[h[0]]),r=s.reshapePacked(h[1],[o[0],o[1]*o[2]*o[3]]),i=h.length===3?[r,e,h[2]]:[r,e],c=s.run((0,p.createPackedMatmulProgramInfoLoader)(s,i,f),i);return s.reshapePacked(c,t)}},9663:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConvTransposeAttributes=n.convTranspose=void 0;const d=u(246),l=u(5060),p=u(2039),s=u(2823),h=(r,i,c,g,m,b)=>(r-1)*i+c+(g-1)*m+1-b,f=(r,i,c,g,m)=>{const b=Math.floor(r/2);i==="SAME_UPPER"?(c[g]=b,c[m]=r-b):i==="SAME_LOWER"&&(c[g]=r-b,c[m]=b)};n.convTranspose=(r,i,c)=>(e(i,c),a(r,i,c));const a=(r,i,c)=>{const g=t(c,i);return[o(r,i,g)]},o=(r,i,c)=>r.run(((g,m,b)=>{const _=(w=m.length>2,v=b.cacheKey,{name:"ConvTranspose",inputNames:w?["X","W","B"]:["X","W"],inputTypes:w?[p.TextureType.unpacked,p.TextureType.unpacked,p.TextureType.unpacked]:[p.TextureType.unpacked,p.TextureType.unpacked],cacheHint:v});var w,v;return Object.assign(Object.assign({},_),{get:()=>((S,O,E,T)=>{const I=O.length>2?"getB(output_channel)":"0.0",C=O[0].dims,B=O[1].dims,F=B[1],N=B[0]/T.group,H=[O[0].dims[0],O[1].dims[1]*T.group,...T.outputShape],$=(0,l.getGlsl)(S.session.backend.glContext.version),{activationFunction:z,applyActivation:Q}=(0,s.getActivationSnippet)(T),X=` - const ivec2 strides = ivec2(${T.strides[0]}, ${T.strides[1]}); - const ivec2 pads = ivec2(${T.pads[0]}, ${T.pads[1]}); - ${z} - void main() { - ivec4 coords = getOutputCoords(); - int batch = coords.x; - int output_channel = coords.y; - - ivec2 loc = coords.zw + pads; - - int group_id = output_channel / ${F}; - int wOutChannel = output_channel - group_id * ${F}; - - float value = ${I}; - for (int inChannelOffset = 0; inChannelOffset < ${N}; inChannelOffset++) { - int input_channel = group_id * ${N} + inChannelOffset; - for (int wWOff = 0; wWOff < ${B[2]}; wWOff++) { - for (int wHOff = 0; wHOff < ${B[3]}; wHOff++) { - ivec2 wOff = ivec2(wWOff * ${T.dilations[0]}, wHOff * ${T.dilations[1]}); - ivec2 wLoc = loc - wOff; - ivec2 wLocIn = wLoc / strides; - if ( - wLocIn * strides == wLoc && - wLocIn.x >= 0 && wLocIn.x < ${C[2]} && - wLocIn.y >= 0 && wLocIn.y < ${C[3]} - ) { - float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); - float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); - value += xVal * wVal; - } - } - } - } - ${Q} - ${$.output} = vec4(value, .0, .0, .0); - } -`;return Object.assign(Object.assign({},E),{output:{dims:H,type:O[0].type,textureType:p.TextureType.unpacked},shaderSource:X,hasMain:!0})})(g,m,_,b)})})(r,i,c),i),t=(r,i)=>{const c=r.kernelShape.slice();if(r.kernelShape.length===0)for(let _=2;_{const C=_.length-2,B=I.length===0;for(let F=0;F{const i=r.attributes,c=(0,s.parseInternalActivationAttributes)(i),g=i.getString("auto_pad","NOTSET"),m=i.getInts("dilations",[1,1]),b=i.getInt("group",1),_=i.getInts("kernel_shape",[]),w=i.getInts("output_padding",[0,0]),v=i.getInts("output_shape",[]),S=i.getInts("pads",[0,0,0,0]),O=i.getInts("strides",[1,1]);return(0,d.createAttributeWithCacheKey)(Object.assign({autoPad:g,dilations:m,group:b,kernelShape:_,outputPadding:w,outputShape:v,pads:S,strides:O},c))};const e=(r,i)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length!==4||r[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(r[0].dims[1]!==r[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const c=r[1].dims[1]*i.group;if(r.length===3&&(r[2].dims.length!==1||r[2].dims[0]!==c))throw new Error("invalid bias");const g=r[0].dims.length-2;if(i.dilations.length!==g)throw new Error(`dilations should be ${g}D`);if(i.strides.length!==g)throw new Error(`strides should be ${g}D`);if(i.pads.length!==2*g)throw new Error(`pads should be ${2*g}D`);if(i.outputPadding.length!==g)throw new Error(`output_padding should be ${g}D`);if(i.kernelShape.length!==0&&i.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.outputShape.length!==r[0].dims.length-2)throw new Error("invalid output shape");if(r[0].type!=="float32"||r[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(r.length===3&&r[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConvAttributes=n.conv=n.calculateOutputShape=void 0;const d=u(246),l=u(2517),p=u(4770),s=u(1386),h=u(9828),f=u(2823),a=u(3248),o=u(5623);n.calculateOutputShape=(g,m,b,_,w)=>{const v=g[0],S=g.slice(2),O=S.length,E=m[0],T=m.slice(2).map((C,B)=>C+(C-1)*(b[B]-1)),I=S.map((C,B)=>C+_[B]+_[B+O]).map((C,B)=>Math.floor((C-T[B]+w[B])/w[B]));return[v,E].concat(...I)},n.conv=(g,m,b)=>(c(m,b),t(g,m,b));const t=(g,m,b)=>{const _=i(b,m),w=g.session.pack,v=_.kernelShape[0]===1&&_.kernelShape[1]===1;return _.group>1?[g.run((0,p.createUnpackedGroupedConvProgramInfoLoader)(g,m,_),m)]:v&&w?[e(g,m,_)]:w&&m[0].dims.length===4&&m[0].dims[0]===1&&!v?[(0,s.conv2DPacked)(g,m,_)]:[r(g,m,_)]},e=(g,m,b)=>{const _=m[0].dims,w=m[1].dims,v=(0,n.calculateOutputShape)(_,w,b.dilations,b.pads,b.strides),S=g.reshapeUnpacked(m[0],[_[1],_[2]*_[3]]),O=g.reshapeUnpacked(m[1],[w[0],w[1]]),E=m.length>2?[O,S,m[2]]:[O,S],T=g.run((0,o.createMatmulProgramInfoLoader)(E,b),E);return g.reshapeUnpacked(T,v)},r=(g,m,b)=>{const _=m[0].dims,w=m[1].dims,v=(0,n.calculateOutputShape)(_,w,b.dilations,b.pads,b.strides),S=g.run((0,a.createIm2ColProgramInfoLoader)(g,m[0],m[1],v,b),[m[0]]),O=m.length===3?[S,m[1],m[2]]:[S,m[1]];return g.run((0,h.createDotProductProgramInfoLoader)(g,m,v,b),O)},i=(g,m)=>{const b=g.kernelShape.slice();if(g.kernelShape.length===0)for(let v=2;v{const m=g.attributes,b=(0,f.parseInternalActivationAttributes)(m),_=m.getString("auto_pad","NOTSET"),w=m.getInts("dilations",[1,1]),v=m.getInt("group",1),S=m.getInts("kernel_shape",[]),O=m.getInts("pads",[0,0,0,0]),E=m.getInts("strides",[1,1]);return(0,d.createAttributeWithCacheKey)(Object.assign({autoPad:_,dilations:w,group:v,kernelShape:S,pads:O,strides:E},b))};const c=(g,m)=>{if(!g||g.length!==2&&g.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(g[0].dims.length!==4||g[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(g[0].dims[1]!==g[1].dims[1]*m.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(g.length===3&&(g[2].dims.length!==1||g[1].dims[0]!==g[2].dims[0]))throw new Error("invalid bias");const b=g[0].dims.length-2;if(m.dilations.length!==b)throw new Error(`dilations should be ${b}D`);if(m.strides.length!==b)throw new Error(`strides should be ${b}D`);if(m.pads.length!==2*b)throw new Error(`pads should be ${2*b}D`);if(m.kernelShape.length!==0&&m.kernelShape.length!==g[1].dims.length-2)throw new Error("invalid kernel shape");if(g[0].type!=="float32"||g[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(g.length===3&&g[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}},5193:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseDepthToSpaceAttributes=n.depthToSpace=void 0;const d=u(3738);n.depthToSpace=(p,s,h)=>{l(s);const f=h.blocksize,a=f*f,o=h.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],t=h.mode==="DCR"?[s[0].dims[0],f,f,s[0].dims[1]/a,s[0].dims[2],s[0].dims[3]]:[s[0].dims[0],s[0].dims[1]/a,f,f,s[0].dims[2],s[0].dims[3]],e=p.reshapeUnpacked(s[0],t),r={perm:o,cacheKey:`${o}`},[i]=(0,d.transpose)(p,[e],r),c=[s[0].dims[0],s[0].dims[1]/a,s[0].dims[2]*f,s[0].dims[3]*f];return[p.reshapeUnpacked(i,c)]},n.parseDepthToSpaceAttributes=p=>{const s=p.attributes.getInt("blocksize");if(s<1)throw new Error(`blocksize must be >= 1, but got : ${s} for DepthToSpace`);const h=p.attributes.getString("mode","DCR");if(h!=="DCR"&&h!=="CRD")throw new Error(`unrecognized mode: ${h} for DepthToSpace`);return{mode:h,blocksize:s}};const l=p=>{if(p.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${p.length}`);if(p[0].type==="string"||p[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createDotProductProgramInfoLoader=void 0;const d=u(2517),l=u(5060),p=u(2039),s=u(2823),h=u(3248);n.createDotProductProgramInfoLoader=(f,a,o,t)=>{const e=((r,i)=>({name:"ConvDotProduct",inputNames:r?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:r?[p.TextureType.unpacked,p.TextureType.packedLastDimension,p.TextureType.unpacked]:[p.TextureType.unpacked,p.TextureType.packedLastDimension],cacheKey:i.activationCacheKey}))(a.length>2,t);return Object.assign(Object.assign({},e),{get:()=>((r,i,c,g,m)=>{const b=c[0].dims,_=c[1].dims,w=[_[0],Math.ceil(b[1]*_[2]*_[3]/4)],v=(0,h.calculateIm2ColDims)(b,_,g),[S,O]=r.calculateTextureWidthAndHeight(w,p.TextureType.packedLastDimension),E=d.ShapeUtil.computeStrides(v),[T,I]=r.calculateTextureWidthAndHeight(v,p.TextureType.packedLastDimension),C=g.length,B=c.length<3?"0.0":"_B(b)",F=Math.ceil(b[1]*_[2]*_[3]/4),{activationFunction:N,applyActivation:H}=(0,s.getActivationSnippet)(m),$=(0,l.getGlsl)(r.session.backend.glContext.version),z=` -${N} -float process(int indices[${C}]) { - int b[1]; - b[0] = indices[1]; - int im2col[4]; - im2col[0] = indices[0]; - im2col[1] = indices[2]; - im2col[2] = indices[3]; - int im2colOffset = im2col[0] * ${E[0]} + im2col[1] * ${E[1]} + im2col[2] * ${E[2]}; - int kernelOffset = indices[1] * ${w[1]}; - float value = ${B}; - for (int i = 0; i < ${F}; ++i) { - vec2 im2colCoords = offsetToCoords(im2colOffset, ${T}, ${I}); - vec2 kernelCoords = offsetToCoords(kernelOffset, ${S}, ${O}); - value += dot(${$.texture2D}(Im2Col, im2colCoords), ${$.texture2D}(K, kernelCoords)); - ++im2colOffset; - ++kernelOffset; - } - ${H} - return value; -}`;return Object.assign(Object.assign({},i),{output:{dims:g,type:c[0].type,textureType:p.TextureType.unpacked},shaderSource:z})})(f,e,a,o,t)})}},7992:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseFlattenAttributes=n.flatten=void 0;const d=u(2517);n.flatten=(p,s,h)=>{l(s,h);const f=d.ShapeUtil.flattenShape(s[0].dims,h);return[p.reshapeUnpacked(s[0],f)]},n.parseFlattenAttributes=p=>p.attributes.getInt("axis",1);const l=(p,s)=>{if(!p||p.length!==1)throw new Error("Flatten requires 1 input.");const h=p[0].dims.length;if(h===0)throw new Error("scalar tensor is not supported.");if(s<-h||s>h)throw new Error("Invalid axis");if(p[0].type==="string")throw new Error("string tensor is not supported.")}},2823:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseInternalActivationAttributes=n.getActivationSnippet=void 0;const d=u(2517),l=u(4909);n.getActivationSnippet=function(p){let s;switch(p.activation){case"Relu":s=(0,l.glslRelu)();break;case"Sigmoid":s=(0,l.glslSigmoid)();break;case"Clip":s=(0,l.glslClip)(p.clipMin,p.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const h=s.name;return{activationFunction:s.body,applyActivation:`value = ${h}_(value);`}},n.parseInternalActivationAttributes=p=>{const s=p.getString("activation","");if(s==="Clip"){const[h,f]=p.getFloats("activation_params",[d.MIN_CLIP,d.MAX_CLIP]);return{activation:s,clipMax:f,clipMin:h,activationCacheKey:`${s}:${h},${f}`}}return{activation:s,activationCacheKey:s}}},1253:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseGatherAttributes=n.gather=void 0;const d=u(246),l=u(782),p=u(2517),s=u(2039);n.gather=(o,t,e)=>(a(t,e.axis),[o.run(f(o,t,e),t)]),n.parseGatherAttributes=o=>(0,d.createAttributeWithCacheKey)({axis:o.attributes.getInt("axis",0)});const h={name:"Gather",inputNames:["A","B"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},f=(o,t,e)=>{const r=Object.assign(Object.assign({},h),{cacheHint:e.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((i,c,g,m)=>{const b=g[0].dims.slice(),_=g[1].dims.slice(),w=new Array(b.length+_.length-1);m=p.ShapeUtil.normalizeAxis(m,b.length);const v=[];for(let O=0;O{if(!o||o.length!==2)throw new Error("Gather requires 2 inputs.");const e=o[0].dims.length;if(e<1)throw new Error("Invalid input shape.");if(t<-e||t>e-1)throw new Error("Invalid axis.");if(l.NUMBER_TYPES.indexOf(o[0].type)===-1)throw new Error("Invaid input type.");if(o[1].type!=="int32"&&o[1].type!=="int16")throw new Error("Invaid input type.")}},4776:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseGemmAttributesV11=n.parseGemmAttributesV7=n.gemm=void 0;const d=u(246),l=u(2517),p=u(2039);n.gemm=(o,t,e)=>(a(t,e),[o.run(h(t,e),t)]);const s=(o,t)=>{const e=o.attributes.getInt("transA",0)!==0,r=o.attributes.getInt("transB",0)!==0,i=o.attributes.getFloat("alpha",1),c=o.attributes.getFloat("beta",1);return(0,d.createAttributeWithCacheKey)({transA:e,transB:r,alpha:i,beta:c,isOptionalC:t})};n.parseGemmAttributesV7=o=>s(o,!1),n.parseGemmAttributesV11=o=>s(o,!0);const h=(o,t)=>{const e={name:"Gemm",inputNames:o.length===3?["A","B","C"]:["A","B"],inputTypes:o.length===3?[p.TextureType.unpacked,p.TextureType.unpacked,p.TextureType.unpacked]:[p.TextureType.unpacked,p.TextureType.unpacked],key:t.cacheKey};return Object.assign(Object.assign({},e),{get:()=>f(e,o,t)})},f=(o,t,e)=>{const r=t[0].dims.slice(),i=t[1].dims.slice(),[c,g]=l.GemmUtil.getShapeOfGemmResult(r,e.transA,i,e.transB,t.length===3?t[2].dims:void 0),m=[c,g];if(!m)throw new Error("Can't use gemm on the given tensors");let b=r[r.length-1],_="";e.transA&&(b=r[0]),e.transA&&e.transB?_="value += _A_T(a) * _B_T(b);":e.transA&&!e.transB?_="value += _A_T(a) * _B(b);":!e.transA&&e.transB?_="value += _A(a) * _B_T(b);":e.transA||e.transB||(_="value += _A(a) * _B(b);");const w=m.length,v=` - float process(int indices[${w}]) { - int a[${w}]; - int b[${w}]; - ${t.length===3?`int c[${t[2].dims.length}];`:""} - - copyVec(indices, a); - copyVec(indices, b); - ${t.length===3?"bcastIndices_C(indices, c);":""} - - float value = 0.0; - for (int k=0; k<${b}; ++k) { - a[${w-1}] = k; - b[${w-2}] = k; - ${_} - } - - value = value * alpha; - ${t.length===3?"value += beta * _C(c);":""} - return value; - }`;return Object.assign(Object.assign({},o),{output:{dims:m,type:t[0].type,textureType:p.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:e.alpha},{name:"beta",type:"float",data:e.beta}],shaderSource:v})},a=(o,t)=>{if(!o)throw new Error("Input is missing");if(t.isOptionalC&&(o.length<2||o.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&o.length!==3)throw new Error("Gemm requires 3 inputs");if(o.length===3&&o[2].dims.length!==1&&o[2].dims.length!==2)throw new Error("Invalid input shape of C");if(o[0].type!=="float32"&&o[0].type!=="float64"||o[1].type!=="float32"&&o[1].type!=="float64"||o.length===3&&o[2].type!=="float32"&&o[2].type!=="float64")throw new Error("Invalid input type.");if(o[0].type!==o[1].type||o.length===3&&o[0].type!==o[2].type)throw new Error("Input types are mismatched")}},8555:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedIm2ColProgramInfoLoader=void 0;const d=u(5060),l=u(2039),p=u(2827);n.createPackedIm2ColProgramInfoLoader=(s,h,f,a,o)=>{const t=(e=o.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[l.TextureType.packed],cacheHint:e});var e;return Object.assign(Object.assign({},t),{get:()=>((r,i,c,g,m,b)=>{const _=c.dims,w=g.dims,v=m.length,S=[w[1]*w[2]*w[3],m[2]*m[3]],O=w[2]*w[3],E=(0,p.unpackFromChannel)(),T=(0,d.getGlsl)(r.session.backend.glContext.version);let I="";for(let B=0;B<=1;B++)for(let F=0;F<=1;F++)I+=` - blockIndex = rc.x + ${F}; - pos = rc.y + ${B}; - - if(blockIndex < ${S[1]} && pos < ${S[0]}) { - offsetY = int(blockIndex / (${m[v-1]})) * ${b.strides[0]} - - ${b.pads[0]}; - d0 = offsetY + ${b.dilations[0]} * (imod(pos, ${O}) / ${w[2]}); - - if(d0 < ${_[2]} && d0 >= 0) { - offsetX = imod(blockIndex, ${m[v-1]}) * ${b.strides[1]} - - ${b.pads[1]}; - d1 = offsetX + ${b.dilations[1]} * imod(imod(pos, ${O}), ${w[2]}); - - if(d1 < ${_[3]} && d1 >= 0) { - - ch = int(float(pos)/ ${O}.); - innerDims = vec2(d0, d1); - result[${2*B+F}] = getChannel( - getA(0, ch, int(innerDims.x), - int(innerDims.y)), innerDims); - } - } - } - - `;const C=` - ${E} - - void main() { - ivec2 rc = getOutputCoords(); - vec4 result = vec4(0.0); - int blockIndex, pos, offsetY, d0, offsetX, d1, ch; - vec2 innerDims; - ${I} - ${T.output} = result; - } - `;return Object.assign(Object.assign({},i),{output:{dims:S,type:c.type,textureType:l.TextureType.packed},shaderSource:C,hasMain:!0})})(s,t,h,f,a,o)})}},3248:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.calculateIm2ColDims=n.createIm2ColProgramInfoLoader=void 0;const d=u(2039);n.createIm2ColProgramInfoLoader=(l,p,s,h,f)=>{const a=(o=f.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[d.TextureType.unpacked],cacheHint:o});var o;return Object.assign(Object.assign({},a),{get:()=>((t,e,r,i,c,g)=>{const m=r.dims,b=i.dims,_=c.length,w=(0,n.calculateIm2ColDims)(m,b,c,4),v=` - const int XC = ${m[1]}; - const int XH = ${m[2]}; - const int XW = ${m[3]}; - const int KH = ${g.kernelShape[0]}; - const int KW = ${g.kernelShape[1]}; - const int dilationH = ${g.dilations[0]}; - const int dilationW = ${g.dilations[1]}; - const int strideH = ${g.strides[0]}; - const int strideW = ${g.strides[1]}; - const int padH = ${g.pads[0]}; - const int padW = ${g.pads[1]}; - const int KHKW = KH*KW; - const int XCKHKW = XC * KHKW; - const int outputChannels = 4; - vec4 process(int indices[${_}]) { - int b = indices[0]; // batch size - int oh = indices[1] * strideH - padH; //output height - int ow = indices[2] * strideW - padW; //output width - int p = indices[3] * outputChannels; //patch - vec4 value = vec4(0.0); - for(int i=0; i < outputChannels; ++i) { - if(p < XCKHKW) { - int patchC = p / KHKW; - int patchH = (p - patchC*KHKW) / KW; - int patchW = (p - patchC*KHKW) - patchH * KW; - int xh2 = oh + patchH * dilationH; - int xw2 = ow + patchW * dilationW; - int x[${m.length}]; - x[0] = b; - x[1] = patchC; - x[2] = xh2; - x[3] = xw2; - if(xh2 >= 0 && - xh2 < XH && - xw2 >= 0 && - xw2 < XW) { - value[i] = _X(x); - } - } - ++p; - } - return value; - } - `;return Object.assign(Object.assign({},e),{output:{dims:w,type:r.type,textureType:d.TextureType.packedLastDimension},shaderSource:v})})(0,a,p,s,h,f)})},n.calculateIm2ColDims=(l,p,s,h=4)=>[s[0],s[2],s[3],Math.ceil(l[1]*p[2]*p[3]/h)]},6572:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseImageScalerAttributes=n.imageScaler=void 0;const d=u(246),l=u(2039);n.imageScaler=(a,o,t)=>(f(o),[a.run(s(a,o,t),o)]),n.parseImageScalerAttributes=a=>{const o=a.attributes.getFloat("scale"),t=a.attributes.getFloats("bias");return(0,d.createAttributeWithCacheKey)({scale:o,bias:t})};const p={name:"ImageScaler",inputNames:["X"],inputTypes:[l.TextureType.unpacked]},s=(a,o,t)=>{const e=Object.assign(Object.assign({},p),{cacheHint:t.cacheKey});return Object.assign(Object.assign({},e),{get:()=>((r,i,c,g)=>{const m=c[0].dims.slice(),b=m.length,_=` - ${h(g.bias.length)} - float process(int indices[${b}]) { - return _X(indices) * scale + getBias(bias, indices[1]); - }`;return Object.assign(Object.assign({},i),{output:{dims:m,type:c[0].type,textureType:l.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:g.bias.length,data:g.bias},{name:"scale",type:"float",data:g.scale}],shaderSource:_})})(0,e,o,t)})},h=a=>{const o=[`float getBias(float bias[${a}], int channel) {`];for(let t=0;t{if(!a||a.length!==1)throw new Error("ImageScaler requires 1 input.");if(a[0].dims.length!==4)throw new Error("Invalid input shape.");if(a[0].type!=="float32"&&a[0].type!=="float64")throw new Error("Invalid input type.")}},3346:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseInstanceNormalizationAttributes=n.instanceNormalization=void 0;const d=u(5060),l=u(2039);n.instanceNormalization=(o,t,e)=>{a(t);const r=o.run(s(t[0]),t);return[o.run(f(o,t[0],e,r.dims),[t[0],r,t[1],t[2]])]},n.parseInstanceNormalizationAttributes=o=>o.attributes.getFloat("epsilon",1e-5);const p={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[l.TextureType.unpacked]},s=o=>Object.assign(Object.assign({},p),{get:()=>((t,e)=>{const r=e.dims.slice(),i=r[1],c=r[2]*r[3],g=[r[0],i],m=` - vec4 process(int[2] indices) { - vec4 v = vec4(0.0); - int a[4]; - a[0] = indices[0]; - a[1] = indices[1]; - float temp = 0.0; - for(int a2=0; a2<${r[2]}; a2++) { - a[2] = a2; - for(int a3=0; a3<${r[3]}; a3++) { - a[3] = a3; - float x = _X(a); - temp += x; - } - } - float mean = temp / float(${c}); - temp = 0.0; - for(int a2=0; a2<${r[2]}; a2++) { - a[2] = a2; - for(int a3=0; a3<${r[3]}; a3++) { - a[3] = a3; - float x = _X(a); - temp += (x - mean) * (x - mean); - } - } - v.r = mean; - v.g = temp / float(${c}); - - return v; - }`;return Object.assign(Object.assign({},t),{output:{dims:g,type:e.type,textureType:l.TextureType.packedLastDimension},shaderSource:m})})(p,o)}),h={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[l.TextureType.unpacked,l.TextureType.packedLastDimension,l.TextureType.unpacked,l.TextureType.unpacked]},f=(o,t,e,r)=>{const i=Object.assign(Object.assign({},h),{cacheHint:`${e}`});return Object.assign(Object.assign({},i),{get:()=>((c,g,m,b,_)=>{const w=(0,d.getGlsl)(c.session.backend.glContext.version),[v,S]=c.calculateTextureWidthAndHeight(_,l.TextureType.packedLastDimension),[O,E]=[v/4,S],T=` - vec4 get_MeanAndVariance(int[2] mv) { - int offset = indicesToOffset_MeanAndVariance(mv); - vec2 coords = offsetToCoords(offset, ${O}, ${E}); - return ${w.texture2D}(MeanAndVariance, coords); - } - - float process(int[4] indices) { - int mv[2]; - mv[0] = indices[0]; - mv[1] = indices[1]; - vec4 mean_and_variance = get_MeanAndVariance(mv); - float mean = mean_and_variance.r; - float variance = mean_and_variance.g; - - int sb[1]; - sb[0] = indices[1]; - float scale = _Scale(sb); - float b = _B(sb); - - return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; - }`;return Object.assign(Object.assign({},g),{output:{dims:m.dims,type:m.type,textureType:l.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:b}],shaderSource:T})})(o,i,t,e,r)})},a=o=>{if(!o||o.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");const t=o[0],e=o[1],r=o[2];if(t.dims.length<3||e.dims.length!==1||r.dims.length!==1)throw new Error("Invalid input shape.");if(e.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if(t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64")throw new Error("Invalid input type.");if(o[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}},708:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedMatmulProgramInfoLoader=void 0;const d=u(2517),l=u(5060),p=u(2039),s=u(9390),h=u(2823),f=u(5623);n.createPackedMatmulProgramInfoLoader=(a,o,t)=>{const e=(r=o.length>2,i=t.activationCacheKey,{name:"MatMul (packed)",inputNames:r?["A","B","Bias"]:["A","B"],inputTypes:r?[p.TextureType.packed,p.TextureType.packed,p.TextureType.packed]:[p.TextureType.packed,p.TextureType.packed],cacheHint:i});var r,i;return Object.assign(Object.assign({},e),{get:()=>((c,g,m,b)=>{const _=m.length>2,w=_?"value += getBiasForMatmul();":"",v=m[0].dims,S=m[1].dims,O=d.BroadcastUtil.calcShape(v,S,!0),E=!d.ShapeUtil.areEqual(m[0].dims,m[1].dims);if(!O)throw new Error("Can't use matmul on the given tensors");const T=v[v.length-1],I=Math.ceil(T/2),C=v.length,B=S.length,F=(0,l.getGlsl)(c.session.backend.glContext.version),N=(0,s.getCoordsDataType)(O.length),H=O.length,$=(0,s.getGlChannels)(),{activationFunction:z,applyActivation:Q}=(0,h.getActivationSnippet)(b),X=_?`${(0,f.getBiasForMatmul)(N,$,m[2].dims,O,!0)}`:"",te=E?`${function(Oe,ce,Te,_e){let Le=[],We=[];const Ae=Te[0].dims,Ce=Te[1].dims,Me=Ae.length,Ee=Ce.length,ve=_e.length,je=ve-Me,ze=ve-Ee;Le=Ae.map((Se,Fe)=>`coords.${ce[Fe+je]}`),Le[Me-1]="i*2",Le.join(", "),We=Ce.map((Se,Fe)=>`coords.${ce[Fe+ze]}`),We[Ee-2]="i*2",We.join(", ");const Ue=d.BroadcastUtil.getBroadcastDims(Ae,_e),He=d.BroadcastUtil.getBroadcastDims(Ce,_e),Ke=Ue.map(Se=>`coords.${ce[Se+je]} = 0;`).join(` -`),Ve=He.map(Se=>`coords.${ce[Se+ze]} = 0;`).join(` -`),Be=`int lastDim = coords.${ce[ve-1]}; - coords.${ce[ve-1]} = coords.${ce[ve-2]}; - coords.${ce[ve-2]} = lastDim;`;return` -vec4 getAAtOutCoordsMatmul(int i) { - ${Oe} coords = getOutputCoords(); - ${Be} - ${Ke} - vec4 outputValue = getA(${Le}); - return outputValue; -} - -vec4 getBAtOutCoordsMatmul(int i) { - ${Oe} coords = getOutputCoords(); - ${Be} - ${Ve} - vec4 outputValue = getB(${We}); - return outputValue; -}`}(N,$,m,O)}`:"",ne=E?"getAAtOutCoordsMatmul(i)":`getA(${function(Oe,ce){let Te="";for(let _e=0;_e{Object.defineProperty(n,"__esModule",{value:!0}),n.getBiasForMatmul=n.createMatmulProgramInfoLoader=n.parseMatMulAttributes=n.matMul=void 0;const d=u(2517),l=u(2039),p=u(9390),s=u(2823),h=u(708);function f(t,e){const r=(i=t.length>2,c=e.activationCacheKey,{name:"MatMul",inputNames:i?["A","B","Bias"]:["A","B"],inputTypes:i?[l.TextureType.unpacked,l.TextureType.unpacked,l.TextureType.unpacked]:[l.TextureType.unpacked,l.TextureType.unpacked],cacheHint:c});var i,c;return Object.assign(Object.assign({},r),{get:()=>function(g,m,b){const _=m[0].dims,w=m[1].dims,v=d.BroadcastUtil.calcShape(_,w,!0);if(!v)throw new Error("Can't use matmul on the given tensors");const S=(0,p.getCoordsDataType)(v.length),O=(0,p.getGlChannels)(),{activationFunction:E,applyActivation:T}=(0,s.getActivationSnippet)(b),I=m.length>2,C=I?"value += getBiasForMatmul();":"",B=I?`${o(S,O,m[2].dims,v,!1)}`:"",F=v.length,N=_.length,H=w.length,$=` - ${E} - ${B} - float process(int indices[${F}]) { - int a[${N}]; - int b[${H}]; - bcastMatmulIndices_A(indices, a); - bcastMatmulIndices_B(indices, b); - - float value; - for (int k=0; k<${_[_.length-1]}; ++k) { - a[${N-1}] = k; - b[${H-2}] = k; - value += _A(a) * _B(b); - } - ${C} - ${T} - return value; - }`;return Object.assign(Object.assign({},g),{output:{dims:v,type:m[0].type,textureType:l.TextureType.unpacked},shaderSource:$})}(r,t,e)})}n.matMul=(t,e,r)=>(a(e),t.session.pack?[t.run((0,h.createPackedMatmulProgramInfoLoader)(t,e,r),e)]:[t.run(f(e,r),e)]),n.parseMatMulAttributes=t=>(0,s.parseInternalActivationAttributes)(t.attributes),n.createMatmulProgramInfoLoader=f;const a=t=>{if(!t||t.length!==2)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64")throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function o(t,e,r,i,c){let g="";const m=r.length,b=i.length,_=b-m;g=b<2&&m>0?"coords":r.map((S,O)=>`coords.${e[O+_]}`).join(", ");const w=d.BroadcastUtil.getBroadcastDims(r,i).map(S=>`coords.${e[S+_]} = 0;`).join(` -`);let v="vec4(outputValue.xx, outputValue.yy)";return d.ShapeUtil.size(r)===1&&(v="vec4(outputValue.x)"),c?` -vec4 getBiasForMatmul() { - ${t} coords = getOutputCoords(); - ${w} - vec4 outputValue = getBias(${g}); - return ${v}; -}`:` -float getBiasForMatmul() { - ${t} coords = getOutputCoords(); - ${w} - return getBias(coords.x); -}`}n.getBiasForMatmul=o},2403:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackProgramInfoLoader=void 0;const d=u(5060),l=u(2039),p=u(9390),s=u(2827),h={name:"pack",inputNames:["A"],inputTypes:[l.TextureType.unpackedReversed]};n.createPackProgramInfoLoader=(f,a)=>Object.assign(Object.assign({},h),{get:()=>((o,t)=>{const e=(0,d.getGlsl)(o.session.backend.glContext.version),r=t.dims,i=r.length,c=t.dims.length,g=(0,p.getCoordsDataType)(c),m=(0,s.getChannels)("rc",c),b=(_=c,w=m,v=r[r.length-2],S=r[r.length-1],_===0||_===1?"":` - int r = ${w[_-2]}; - int c = ${w[_-1]}; - int rp1 = ${w[_-2]} + 1; - int cp1 = ${w[_-1]} + 1; - bool rEdge = rp1 >= ${S}; - bool cEdge = cp1 >= ${v}; - `);var _,w,v,S;let O;O=i===0?[1,1]:i===1?[r[0],1]:[r[c-1],r[c-2]];const E=function(C,B,F){if(C===0)return"false";if(C===1)return`rc > ${B[0]}`;let N="";for(let H=C-2;H= ${B[H-C+2]}`,H= ${C[0]} ? 0. : getA(rc + 1), - 0, 0`;let N="";if(F>2)for(let H=0;H{Object.defineProperty(n,"__esModule",{value:!0}),n.unpackFromChannel=n.getChannels=n.getVecChannels=void 0;const d=u(9390);function l(p,s){return(0,d.getGlChannels)(s).map(h=>`${p}.${h}`)}n.getVecChannels=l,n.getChannels=function(p,s){return s===1?[p]:l(p,s)},n.unpackFromChannel=function(){return` - float getChannel(vec4 frag, int dim) { - int modCoord = imod(dim, 2); - return modCoord == 0 ? frag.r : frag.g; - } - - float getChannel(vec4 frag, vec2 innerDims) { - vec2 modCoord = mod(innerDims, 2.); - return modCoord.x == 0. ? - (modCoord.y == 0. ? frag.r : frag.g) : - (modCoord.y == 0. ? frag.b : frag.a); - } - `}},2870:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parsePadAttributesV11=n.padV11=n.parsePadAttributesV2=n.padV2=void 0;const d=u(246),l=u(2517),p=u(5060),s=u(2039),h={name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};n.padV2=(g,m,b)=>(o(m),[g.run(Object.assign(Object.assign({},h),{cacheHint:b.cacheKey,get:()=>a(g,m[0],b)}),m)]),n.parsePadAttributesV2=g=>{const m=g.attributes.getString("mode","constant"),b=g.attributes.getFloat("value",0),_=g.attributes.getInts("pads");return(0,d.createAttributeWithCacheKey)({mode:m,value:b,pads:_})},n.padV11=(g,m,b)=>{t(m);const _=f(g,m,b);return(0,n.padV2)(g,[m[0]],_)},n.parsePadAttributesV11=g=>g.attributes.getString("mode","constant");const f=(g,m,b)=>{if(!g.session.isInitializer(m[1].dataId)||m.length>=3&&!g.session.isInitializer(m[2].dataId))throw new Error("dynamic pad attributes are not allowed");const _=Array.from(m[1].integerData),w=m.length>=3?m[2].floatData[0]:0;return(0,d.createAttributeWithCacheKey)({mode:b,pads:_,value:w})},a=(g,m,b)=>{const _=l.ShapeUtil.padShape(m.dims.slice(),b.pads),w=_.length,v=` - ${e(g,m,b)} - float process(int[${w}] indices) { - return padA(indices); - }`;return{name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked],output:{dims:_,type:m.type,textureType:s.TextureType.unpacked},shaderSource:v}},o=g=>{if(!g||g.length!==1)throw new Error("Pad requires 1 input");if(g[0].type!=="float32"&&g[0].type!=="float64")throw new Error("Invalid input type.")},t=g=>{if(!g||g.length!==2&&g.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(g[1].type!=="int32")throw new Error("Invalid input type.");if(g.length>=3&&g[2].type==="string")throw new Error("Invalid input type.")},e=(g,m,b)=>{const _=(0,p.getGlsl)(g.session.backend.glContext.version),[w,v]=g.calculateTextureWidthAndHeight(m.dims,s.TextureType.unpacked),S=l.ShapeUtil.computeStrides(m.dims);switch(b.mode){case"constant":return r(_,m.dims,S,w,v,b.pads,b.value);case"reflect":return i(_,m.dims,S,w,v,b.pads);case"edge":return c(_,m.dims,S,w,v,b.pads);default:throw new Error("Invalid mode")}},r=(g,m,b,_,w,v,S)=>{const O=m.length;let E="";for(let T=O-1;T>=0;--T)E+=` - k = m[${T}] - ${v[T]}; - if (k < 0) return constant; - if (k >= ${m[T]}) return constant; - offset += k * ${b[T]}; - `;return` - float padA(int m[${O}]) { - const float constant = float(${S}); - int offset = 0; - int k = 0; - ${E} - vec2 coords = offsetToCoords(offset, ${_}, ${w}); - float value = getColorAsFloat(${g.texture2D}(A, coords)); - return value; - } - `},i=(g,m,b,_,w,v)=>{const S=m.length;let O="";for(let E=S-1;E>=0;--E)O+=` - k = m[${E}] - ${v[E]}; - if (k < 0) { k = -k; } - { - const int _2n_1 = ${2*(m[E]-1)}; - k = int( mod( float(k), float(_2n_1) ) ) ; - if(k >= ${m[E]}) { k = _2n_1 - k; } - } - offset += k * ${b[E]}; - `;return` - float padA(int m[${S}]) { - int offset = 0; - int k = 0; - ${O} - vec2 coords = offsetToCoords(offset, ${_}, ${w}); - float value = getColorAsFloat(${g.texture2D}(A, coords)); - return value; - } - `},c=(g,m,b,_,w,v)=>{const S=m.length;let O="";for(let E=S-1;E>=0;--E)O+=` - k = m[${E}] - ${v[E]}; - if (k < 0) k = 0; - if (k >= ${m[E]}) k = ${m[E]-1}; - offset += k * ${b[E]}; - `;return` - float padA(int m[${S}]) { - int offset = 0; - int k = 0; - ${O} - vec2 coords = offsetToCoords(offset, ${_}, ${w}); - float value = getColorAsFloat(${g.texture2D}(A, coords)); - return value; - } - `}},2143:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.globalMaxPool=n.parseMaxPoolAttributes=n.maxPool=n.parseGlobalAveragePoolAttributes=n.globalAveragePool=n.parseAveragePoolAttributes=n.averagePool=void 0;const d=u(246),l=u(2517),p=u(2039);n.averagePool=(c,g,m)=>{t(g);const b={name:"AveragePool",inputNames:["X"],inputTypes:[p.TextureType.unpacked],cacheHint:m.cacheKey};return[c.run(Object.assign(Object.assign({},b),{get:()=>s(g,b,!1,m)}),g)]},n.parseAveragePoolAttributes=c=>{const g=c.attributes.getString("auto_pad","NOTSET"),m=c.attributes.getInt("ceil_mode",0),b=c.attributes.getInt("count_include_pad",0)!==0,_=c.attributes.getInts("kernel_shape"),w=c.attributes.getInts("strides",[]),v=c.attributes.getInts("pads",[]);if(m!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,d.createAttributeWithCacheKey)({autoPad:g,ceilMode:m,countIncludePad:b,kernelShape:_,strides:w,pads:v})};const s=(c,g,m,b)=>{const[_,w]=f(c,b,m),v=l.ShapeUtil.size(_.kernelShape);let S="";_.countIncludePad?S+=`value /= float(${v});`:S+=`value /= float(${v} - pad);`;const O=` - ${e(c[0].dims,_,"value += _X(x);",S,"0.0")} - `;return Object.assign(Object.assign({},g),{output:{dims:w,type:c[0].type,textureType:p.TextureType.unpacked},shaderSource:O})};n.globalAveragePool=(c,g,m)=>{t(g);const b={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[p.TextureType.unpacked],cacheHint:`${m.countIncludePad}`};return[c.run(Object.assign(Object.assign({},b),{get:()=>s(g,b,!0,m)}),g)]},n.parseGlobalAveragePoolAttributes=c=>{const g=c.attributes.getInt("count_include_pad",0)!==0;return(0,d.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:g,kernelShape:[],strides:[],pads:[]})},n.maxPool=(c,g,m)=>{t(g);const b={name:"MaxPool",inputNames:["X"],inputTypes:[p.TextureType.unpacked],cacheHint:m.cacheKey};return[c.run(Object.assign(Object.assign({},b),{get:()=>h(g,b,!1,m)}),g)]},n.parseMaxPoolAttributes=c=>{const g=c.attributes.getString("auto_pad","NOTSET"),m=c.attributes.getInt("ceil_mode",0),b=c.attributes.getInts("kernel_shape"),_=c.attributes.getInts("strides",[]),w=c.attributes.getInts("pads",[]),v=c.attributes.getInt("storage_order",0),S=c.attributes.getInts("dilations",[]);if(v!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(m!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,d.createAttributeWithCacheKey)({autoPad:g,ceilMode:m,countIncludePad:!1,kernelShape:b,strides:_,pads:w,storageOrder:v,dilations:S})};const h=(c,g,m,b)=>{const[_,w]=f(c,b,m),v=` - ${e(c[0].dims,_,` - value = max(_X(x), value); - `,"","-1e5")} - `;return Object.assign(Object.assign({},g),{output:{dims:w,type:c[0].type,textureType:p.TextureType.unpacked},shaderSource:v})},f=(c,g,m)=>{const b=c[0].dims.slice(),_=Object.hasOwnProperty.call(g,"dilations"),w=g.kernelShape.slice(),v=g.strides.slice(),S=_?g.dilations.slice():[],O=g.pads.slice();l.PoolConvUtil.adjustPoolAttributes(m,b,w,v,S,O);const E=l.PoolConvUtil.computePoolOutputShape(m,b,v,S,w,O,g.autoPad),T=Object.assign({},g);return _?Object.assign(T,{kernelShape:w,strides:v,pads:O,dilations:S,cacheKey:g.cacheKey}):Object.assign(T,{kernelShape:w,strides:v,pads:O,cacheKey:g.cacheKey}),[T,E]},a={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},o={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[p.TextureType.unpacked]};n.globalMaxPool=(c,g)=>(t(g),[c.run(Object.assign(Object.assign({},o),{get:()=>h(g,o,!0,a)}),g)]);const t=c=>{if(!c||c.length!==1)throw new Error("Pool ops requires 1 input.");if(c[0].type!=="float32"&&c[0].type!=="float64")throw new Error("Invalid input type.")},e=(c,g,m,b,_)=>{const w=c.length;if(g.kernelShape.length<=2){const v=g.kernelShape[g.kernelShape.length-1],S=g.strides[g.strides.length-1],O=g.pads[g.pads.length/2-1],E=g.pads[g.pads.length-1],T=c[w-1];let I="",C="",B="";if(I=O+E!==0?` - for (int i = 0; i < ${v}; i++) { - x[${w} - 1] = indices[${w} - 1] * ${S} - ${O} + i; - if (x[${w} - 1] < 0 || x[${w} - 1] >= ${T}) { - pad++; - continue; - } - ${m} - }`:` - for (int i = 0; i < ${v}; i++) { - x[${w} - 1] = indices[${w} - 1] * ${S} - ${O} + i; - ${m} - }`,g.kernelShape.length===2){const F=g.kernelShape[g.kernelShape.length-2],N=g.strides[g.strides.length-2],H=g.pads[g.pads.length/2-2],$=g.pads[g.pads.length-2],z=c[w-2];C=H+$!==0?` - for (int j = 0; j < ${F}; j++) { - x[${w} - 2] = indices[${w} - 2] * ${N} - ${H} + j; - if (x[${w} - 2] < 0 || x[${w} - 2] >= ${z}) { - pad+= ${v}; - continue; - } - `:` - for (int j = 0; j < ${F}; j++) { - x[${w} - 2] = indices[${w} - 2] * ${N} - ${H} + j; - `,B=` - } - `}return` - float process(int indices[${w}]) { - int x[${w}]; - copyVec(indices, x); - - float value = ${_}; - int pad = 0; - ${C} - ${I} - ${B} - ${b} - return value; - } - `}{const v=l.ShapeUtil.size(g.kernelShape),S=l.ShapeUtil.computeStrides(g.kernelShape),O=S.length,E=g.pads.length,T=i(O),I=r(c,"inputDims"),C=r(g.pads,"pads"),B=r(S,"kernelStrides"),F=r(g.strides,"strides");let N="";return N=g.pads.reduce((H,$)=>H+$)?` - if (x[j] >= inputDims[j] || x[j] < 0) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - ${m} - }`:` - } - ${m} - `,` - ${T} - float process(int indices[${w}]) { - int x[${w}]; - copyVec(indices, x); - int offset[${O}]; - int pads[${E}]; - int inputDims[${w}]; - int kernelStrides[${O}]; - int strides[${O}]; - ${C} - ${I} - ${F} - ${B} - - float value = ${_}; - int pad = 0; - bool isPad = false; - for (int i = 0; i < ${v}; i++) { - offsetToIndices(i, kernelStrides, offset); - isPad = false; - for (int j = ${w} - ${O}; j < ${w}; j++) { - x[j] = indices[j] * strides[j - ${w} + ${O}] - + offset[j - ${w} + ${O}] - pads[j - 2]; - ${N} - } - ${b} - - return value; - } - `}},r=(c,g)=>{let m="";for(let b=0;b` - void offsetToIndices(int offset, int[${c}] strides, out int[${c}] indices) { - if (${c} == 0) { - return; - } - for (int i = 0; i < ${c} - 1; ++i) { - indices[i] = offset / strides[i]; - offset -= indices[i] * strides[i]; - } - indices[${c} - 1] = offset; - }`},4939:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.reduceLogSumSquare=n.reduceLogSum=n.reduceProd=n.reduceMin=n.reduceMax=n.reduceMean=n.reduceSum=n.parseReduceAttributes=void 0;const d=u(246),l=u(782),p=u(2517),s=u(2039),h=(o,t,e,r,i)=>{a(t);const c={name:r,inputNames:["A"],inputTypes:[s.TextureType.unpacked]};return[o.run(Object.assign(Object.assign({},c),{cacheHint:e.cacheKey,get:()=>f(o,t,e,r,i,c)}),t)]};n.parseReduceAttributes=o=>{const t=o.attributes.getInts("axes",[]),e=o.attributes.getInt("keepdims",1)===1;return(0,d.createAttributeWithCacheKey)({axes:t,keepDims:e})};const f=(o,t,e,r,i,c)=>{const g=[],m=t[0].dims.length||1,b=[],_=p.ShapeUtil.normalizeAxes(e.axes,t[0].dims.length),w=i(t,_);let v=w[1];for(let O=0;O=0||_.length===0?(e.keepDims&&g.push(1),v=` - for(int j${O} = 0; j${O} < ${t[0].dims[O]}; j${O}++) { - inputIdx[${O}] = j${O}; - ${v} - }`):(b.push(`inputIdx[${O}] = outputIdx[${g.length}];`),g.push(t[0].dims[O]));const S=` - float process(int outputIdx[${g.length||1}]) { - float value; // final result - int inputIdx[${m}]; // addressing input data - ${b.join(` -`)} - ${w[0]} // init ops for reduce max/min - ${v} - ${w[2]} // final computation for reduce mean - return value; - }`;return Object.assign(Object.assign({},c),{output:{dims:g,type:t[0].type,textureType:s.TextureType.unpacked},shaderSource:S})},a=o=>{if(!o||o.length!==1)throw new Error("Reduce op requires 1 input.");if(l.NUMBER_TYPES.indexOf(o[0].type)===-1)throw new Error("Invalid input type.")};n.reduceSum=(o,t,e)=>h(o,t,e,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),n.reduceMean=(o,t,e)=>h(o,t,e,"ReduceMean",(r,i)=>{let c=1;for(let g=0;g=0||i.length===0)&&(c*=r[0].dims[g]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${c}.;`]}),n.reduceMax=(o,t,e)=>h(o,t,e,"ReduceMax",(r,i)=>{const c=[];for(let g=0;g=0||i.length===0)&&c.push(`inputIdx[${g}] = 0;`);return[`${c.join(` -`)} -value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),n.reduceMin=(o,t,e)=>h(o,t,e,"ReduceMin",(r,i)=>{const c=[];for(let g=0;g=0||i.length===0)&&c.push(`inputIdx[${g}] = 0;`);return[`${c.join(` -`)} -value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),n.reduceProd=(o,t,e)=>h(o,t,e,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),n.reduceLogSum=(o,t,e)=>h(o,t,e,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),n.reduceLogSumSquare=(o,t,e)=>h(o,t,e,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])},7019:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isReshapeCheap=n.processDims3D=n.createPackedReshape3DProgramInfoLoader=void 0;const d=u(2517),l=u(5060),p=u(2039),s=u(2827);n.createPackedReshape3DProgramInfoLoader=(h,f,a)=>{const o=(t=>({name:"Reshape (packed)",inputTypes:[p.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(a);return Object.assign(Object.assign({},o),{get:()=>((t,e,r,i)=>{const c=e.dims,g=i;let m="";for(let w=0;w<4;w++){let v="";switch(w){case 0:v="outputCoords = rc;";break;case 1:v="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:v="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:v="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}m+=` - ${v} - ${w>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""} - int flattenedIndex = getFlattenedIndex(outputCoords); - - ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); - vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); - - result[${w}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); - - ${w>0?"}":""} - `}const b=(0,l.getGlsl)(t.session.backend.glContext.version),_=` - ${function(w){const v=d.ShapeUtil.computeStrides(w),S=["b","r","c"],O="index";return` - ivec3 inputCoordsFromReshapedOutCoords(int index) { - ${v.map((E,T)=>`int ${S[T]} = ${O} / ${E}; ${T===v.length-1?`int ${S[T+1]} = ${O} - ${S[T]} * ${E}`:`index -= ${S[T]} * ${E}`};`).join("")} - return ivec3(b, r, c); - } - `}(c)} - ${function(w){const v=d.ShapeUtil.computeStrides(w);return` - int getFlattenedIndex(ivec3 coords) { - // reverse y, z order - return coords.x * ${v[0]} + coords.z * ${v[1]} + coords.y; - } -`}(g)} - ${(0,s.unpackFromChannel)()} - - void main() { - ivec3 rc = getOutputCoords(); - - vec4 result = vec4(0.0); - - ivec3 outputCoords; - int rows = ${g[2]}; - int cols = ${g[1]}; - - ${m} - ${b.output} = result; - } - `;return Object.assign(Object.assign({},r),{output:{dims:g,type:e.type,textureType:p.TextureType.packed},shaderSource:_,hasMain:!0})})(h,f,o,a)})},n.processDims3D=function(h){if(h.length===0)return[1,1,1];let f=1;for(let a=0;a1?h[h.length-2]:1,h[h.length-1]]},n.isReshapeCheap=function(h,f){let a=!1;return a=h.length===0||f.length===0||(h.length<2||f.length<2?h[h.length-1]===f[f.length-1]:h[h.length-1]===f[f.length-1]&&h[h.length-2]===f[f.length-2]),a}},718:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.reshape=void 0;const d=u(2517);n.reshape=(l,p)=>{const s=d.ShapeUtil.calculateReshapedDims(p[0].dims,p[1].integerData);return l.session.pack?[l.reshapePacked(p[0],s)]:[l.reshapeUnpacked(p[0],s)]}},2268:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseResizeAttributesV11=n.parseResizeAttributesV10=n.resize=void 0;const d=u(5060),l=u(2039),p=u(9390),s=u(2827),h=u(9793),f={name:"Resize",inputNames:["A"],inputTypes:[l.TextureType.packed]};n.resize=(r,i,c)=>((0,h.validateInputs)(i,c),[r.run(Object.assign(Object.assign({},f),{cacheHint:c.cacheKey,get:()=>a(r,i,c)}),i)]),n.parseResizeAttributesV10=r=>(0,h.parseUpsampleAttributes)(r,10),n.parseResizeAttributesV11=r=>(0,h.parseUpsampleAttributes)(r,11);const a=(r,i,c)=>{const g=(0,d.getGlsl)(r.session.backend.glContext.version),[m,b]=o(i,c);if(m.every(N=>N===1)&&c.coordinateTransformMode!=="tf_crop_and_resize")return Object.assign(Object.assign({},f),{output:{dims:b,type:i[0].type,textureType:l.TextureType.packed},hasMain:!0,shaderSource:`void main() { - vec4 v = ${g.texture2D}(X, TexCoords); - ${g.output} = v; - }`});const _=b.length;if(_<2)throw new Error(`output dimension should be at least 2, but got ${_}`);const w=b[_-2],v=b[_-1],S=i[0].dims;if(_!==S.length)throw new Error(`output dimension should match input ${S.length}, but got ${_}`);const O=S[_-2],E=S[_-1],T=m[_-2],I=m[_-1];let C="";if(c.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${c.mode}'`);switch(c.coordinateTransformMode){case"asymmetric":C=` - vec4 getSourceFracIndex(ivec4 coords) { - return vec4(coords) / scaleWHWH; - } - `;break;case"half_pixel":C=` - vec4 getSourceFracIndex(ivec4 coords) { - return (vec4(coords) + 0.5) / scaleWHWH - 0.5; - } - `;break;case"pytorch_half_pixel":C=` - vec4 getSourceFracIndex(ivec4 coords) { - vec4 fcoords = vec4(coords); - return vec4( - ${v}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, - ${w}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, - ${v}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, - ${w}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 - ); - } - `;break;case"align_corners":C=` - vec4 getSourceFracIndex(ivec4 coords) { - vec4 resized = vec4(${v}.0 - 1.0, ${w}.0 - 1.0, ${v}.0 - 1.0, - ${w}.0 - 1.0); - vec4 original = vec4(${E}.0 - 1.0, ${O}.0 - 1.0, ${E}.0 - 1.0, - ${O}.0 - 1.0); - vec4 new_scale = original / resized; - return vec4(coords) * new_scale; - } - `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${c.coordinateTransformMode}'`)}const B=(0,p.getCoordsDataType)(_),F=` - const vec2 inputWH = vec2(${O}.0, ${E}.0); - const vec4 scaleWHWH = vec4(float(${T}), float(${I}), float(${T}), float(${I})); - ${(0,s.unpackFromChannel)()} - ${C} - float getAValue(int x10, int r, int c, int d) { - return getChannel(getA(x10, r, c, d), vec2(c, d)); - } - void main() { - ${B} rc = getOutputCoords(); - - int batch = rc[0]; - int depth = rc[1]; - - // retrieve the 4 coordinates that is used in the 4 packed output values. - ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); - - // calculate the source index in fraction - vec4 sourceFrac = getSourceFracIndex(coords); - - // get the lower and upper bound of the 4 values that will be packed into one texel. - ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); - ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); - ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); - ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); - - bool hasNextRow = rc.w < ${w-1}; - bool hasNextCol = rc.z < ${v-1}; - - // pack x00, x01, x10, x11's top-left corner into one vec4 structure - vec4 topLeft = vec4( - getAValue(batch, depth, x00.x, x00.y), - hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); - - // pack x00, x01, x10, x11's top-right corner into one vec4 structure - vec4 topRight = vec4( - getAValue(batch, depth, x00.x, x00.w), - hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); - - // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure - vec4 bottomLeft = vec4( - getAValue(batch, depth, x00.z, x00.y), - hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); - - // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure - vec4 bottomRight = vec4( - getAValue(batch, depth, x00.z, x00.w), - hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); - - // calculate the interpolation fraction on u and v direction - vec4 frac = vec4(sourceFrac) - floor(sourceFrac); - vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); - - vec4 top = mix(topLeft, topRight, clampFrac.ywyw); - vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); - vec4 newValue = mix(top, bottom, clampFrac.xxzz); - - ${g.output} = vec4(newValue); - } - `;return Object.assign(Object.assign({},f),{output:{dims:b,type:i[0].type,textureType:l.TextureType.packed},hasMain:!0,shaderSource:F})},o=(r,i)=>{const c=r[0].dims;let g,m=i.scales;if(m.length===0){const _=r[i.scalesInputIdx];if(_&&_.size!==0){if(r[i.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");m=t(_,i.mode,i.isResize)}else{const w=r[i.sizesInputIdx];if(!w||w.size===0)throw new Error("Either scales or sizes MUST be provided as input.");g=Array.from(w.integerData),m=e(g,c,i.mode,i.isResize)}}else if(r[i.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const b=g||c.map((_,w)=>Math.floor(_*m[w]));return[m,b]},t=(r,i,c)=>{const g=Array.from(r.floatData);return(0,h.scalesValidation)(g,i,c),g},e=(r,i,c,g)=>{const m=i.length,b=new Array(m);for(let _=0,w=m;_{Object.defineProperty(n,"__esModule",{value:!0}),n.shape=void 0;const d=u(9162);n.shape=(p,s)=>(l(s),[new d.Tensor([s[0].dims.length],"int32",void 0,void 0,new Int32Array(s[0].dims))]);const l=p=>{if(!p||p.length!==1)throw new Error("Shape requires 1 input.")}},2278:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.sliceV10=n.parseSliceAttributes=n.slice=void 0;const d=u(246),l=u(782),p=u(2517),s=u(2039),h={name:"Slice",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};n.slice=(e,r,i)=>(a(r),[e.run(Object.assign(Object.assign({},h),{cacheHint:i.cacheKey,get:()=>f(e,r[0],i)}),r)]),n.parseSliceAttributes=e=>{const r=e.attributes.getInts("starts"),i=e.attributes.getInts("ends"),c=e.attributes.getInts("axes",[]);return(0,d.createAttributeWithCacheKey)({starts:r,ends:i,axes:c})};const f=(e,r,i)=>{const c=i.axes.length===0?r.dims.slice(0).map((S,O)=>O):i.axes,g=p.ShapeUtil.normalizeAxes(c,r.dims.length),m=i.starts.map((S,O)=>S>r.dims[g[O]]-1?r.dims[g[O]]:p.ShapeUtil.normalizeAxis(S,r.dims[g[O]])),b=i.ends.map((S,O)=>S>r.dims[g[O]]-1?r.dims[g[O]]:p.ShapeUtil.normalizeAxis(S,r.dims[g[O]])),_=r.dims.slice(),w=[];for(let S=0;S0&&w.push(`outputIdx[${g[S]}] += ${m[S]};`);const v=` - float process(int outputIdx[${_.length}]) { - ${w.join(` - `)} - return _A(outputIdx); - }`;return Object.assign(Object.assign({},h),{output:{dims:_,type:r.type,textureType:s.TextureType.unpacked},shaderSource:v})},a=e=>{if(!e||e.length!==1)throw new Error("Slice requires 1 input.");if(l.NUMBER_TYPES.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")};n.sliceV10=(e,r)=>{t(r);const i=o(e,r);return[e.run(Object.assign(Object.assign({},h),{cacheHint:i.cacheKey,get:()=>f(e,r[0],i)}),[r[0]])]};const o=(e,r)=>{if(!e.session.isInitializer(r[1].dataId)||!e.session.isInitializer(r[2].dataId)||r.length>=4&&!e.session.isInitializer(r[3].dataId)||r.length>=5&&!e.session.isInitializer(r[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(r.length>=5&&r[4].integerData.some(m=>m!==1))throw new Error("currently non-1 steps is not supported for Slice");const i=Array.from(r[1].integerData),c=Array.from(r[2].integerData),g=r.length>=4?Array.from(r[3].integerData):[];return{starts:i,ends:c,axes:g,cacheKey:`${g};${i};${c}`}},t=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if(e[1].type!=="int32"||e[1].dims.length!==1)throw new Error("Invalid input type.");if(e[2].type!=="int32"||e[2].dims.length!==1)throw new Error("Invalid input type.");if(e.length>=4&&(e[3].type!=="int32"||e[3].dims.length!==1))throw new Error("Invalid input type.");if(e.length>=5&&(e[4].type!=="int32"||e[4].dims.length!==1))throw new Error("Invalid input type.")}},5524:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.softmaxV13=n.parseSoftmaxAttributesV13=n.parseSoftmaxAttributes=n.softmax=void 0;const d=u(246),l=u(2517),p=u(5060),s=u(2039),h=u(3738),f={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[s.TextureType.unpacked]},a={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},o={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked,s.TextureType.unpacked]};n.softmax=(g,m,b)=>{c(m);const _=m[0].dims.slice(),w=l.ShapeUtil.normalizeAxis(b.axis,_.length),v=l.ShapeUtil.sizeToDimension(_,w),S=l.ShapeUtil.sizeFromDimension(_,w);return t(g,m,b,v,S)},n.parseSoftmaxAttributes=g=>(0,d.createAttributeWithCacheKey)({axis:g.attributes.getInt("axis",1)}),n.parseSoftmaxAttributesV13=g=>(0,d.createAttributeWithCacheKey)({axis:g.attributes.getInt("axis",-1)}),n.softmaxV13=(g,m,b)=>{c(m);const _=m[0].dims.slice(),w=l.ShapeUtil.normalizeAxis(b.axis,_.length),v=_.length,S=w!==v-1,O=[];let E,T=[],I=[];S&&(T=Array.from({length:v}).map((N,H)=>H),T[w]=v-1,T[v-1]=w,T.map(N=>O.push(_[N])),E=(0,d.createAttributeWithCacheKey)({perm:T}),I=(0,h.transpose)(g,m,E));const C=S?l.ShapeUtil.sizeToDimension(O,v-1):l.ShapeUtil.sizeToDimension(_,v-1),B=S?l.ShapeUtil.sizeFromDimension(O,v-1):l.ShapeUtil.sizeFromDimension(_,v-1),F=t(g,S?I:m,b,C,B);return S?(0,h.transpose)(g,F,E):F};const t=(g,m,b,_,w)=>{const v=e(g,m[0],_,w,[_]),S=g.run(Object.assign(Object.assign({},f),{cacheHint:b.cacheKey,get:()=>v}),m),O=r(g,m[0],_,w,v.output.dims,[_]),E=g.run(Object.assign(Object.assign({},a),{cacheHint:b.cacheKey,get:()=>O}),[m[0],S]),T=i(g,m[0],_,w,v.output.dims,O.output.dims);return[g.run(Object.assign(Object.assign({},o),{cacheHint:b.cacheKey,get:()=>T}),[m[0],S,E])]},e=(g,m,b,_,w)=>{const[v,S]=g.calculateTextureWidthAndHeight(m.dims,s.TextureType.unpacked),O=w.length;if(b<1||_<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(w.length!==1)throw new Error("Dimensionality of the output should be 1");if(w[0]!==b)throw new Error("Shape of the output should be equal to logical row count");const E=(0,p.getGlsl)(g.session.backend.glContext.version),T=` - float process(int[${O}] indices) { - int logical_row_start_offset = indices[0] * ${_}; - - float max = getColorAsFloat(${E.texture2D}(A, offsetToCoords(logical_row_start_offset, ${v}, - ${S} ))); - for(int i=1; i<${_}; ++i) - { - float current = getColorAsFloat(${E.texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${v}, ${S}))); - if(current > max) - max = current; - } - - return max; - }`;return Object.assign(Object.assign({},f),{output:{dims:w,type:m.type,textureType:s.TextureType.unpacked},shaderSource:T})},r=(g,m,b,_,w,v)=>{const[S,O]=g.calculateTextureWidthAndHeight(m.dims,s.TextureType.unpacked),E=v.length;if(b<1||_<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(v.length!==1)throw new Error("Dimensionality of the output should be 1");if(v[0]!==b)throw new Error("Shape of the output should be equal to logical row count");if(w.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(w[0]!==b)throw new Error("Shape of the intermediate results should be equal to logical row count");const T=` - float process(int[${E}] indices) { - int logical_row_start_offset = indices[0] * ${_}; - - float norm_factor = 0.0; - float max = _Max(indices); - for(int i=0; i<${_}; ++i) - { - norm_factor += exp(getColorAsFloat(${(0,p.getGlsl)(g.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${S}, ${O}))) - max); - } - - return norm_factor; - }`;return Object.assign(Object.assign({},a),{output:{dims:v,type:m.type,textureType:s.TextureType.unpacked},shaderSource:T})},i=(g,m,b,_,w,v)=>{const[S,O]=g.calculateTextureWidthAndHeight(m.dims,s.TextureType.unpacked),E=m.dims.length;if(b<1||_<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(w.length!==1||v.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(w[0]!==b||v[0]!==b)throw new Error("Shape of the intermediate results should be equal to logical row count");const T=` - float process(int[${E}] indices) { - - // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) - int offset = coordsToOffset(TexCoords, ${S}, ${O}); - - //determine the logical row for this index - int logical_row_index[1]; - logical_row_index[0] = offset / ${_}; - - float norm_factor = _Norm(logical_row_index); - - // avoid possible division by 0 - // if norm_facor is 0, all elements are zero - // if so, return 0 - if(norm_factor == 0.0) - return 0.0; - - return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; - }`;return Object.assign(Object.assign({},o),{output:{dims:m.dims,type:m.type,textureType:s.TextureType.unpacked},shaderSource:T})},c=g=>{if(!g||g.length!==1)throw new Error("Softmax requires 1 input.");if(g[0].type!=="float32"&&g[0].type!=="float64")throw new Error("Invalid input type")}},5975:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseSplitAttributes=n.split=void 0;const d=u(246),l=u(2517),p=u(2039),s={name:"Split",inputNames:["A"],inputTypes:[p.TextureType.unpacked]};n.split=(o,t,e)=>{a(t);const r=l.ShapeUtil.normalizeAxis(e.axis,t[0].dims.length),i=h(o,t,r,e),c=[];for(let g=0;gf(o,t[0],e,r,g)}),t));return c},n.parseSplitAttributes=o=>{const t=o.attributes.getInt("axis",0),e=o.attributes.getInts("split",[]),r=o.outputs.length;return(0,d.createAttributeWithCacheKey)({axis:t,split:e,numOutputs:r})};const h=(o,t,e,r)=>{const[,i]=l.SplitUtil.splitShape(t[0].dims,e,r.split,r.numOutputs);return i.length},f=(o,t,e,r,i)=>{const[c,g]=l.SplitUtil.splitShape(t.dims,r,e.split,e.numOutputs),m=g[i],b=c[i],_=` - float process(int indices[${b.length}]) { - indices[${r}] += ${m}; - return _A(indices); - } - `;return Object.assign(Object.assign({},s),{cacheHint:`${e.cacheKey}:${i}`,output:{dims:b,type:t.type,textureType:p.TextureType.unpacked},shaderSource:_})},a=o=>{if(!o||o.length!==1)throw new Error("Split requires one input.");if(o[0].type!=="int8"&&o[0].type!=="uint8"&&o[0].type!=="int16"&&o[0].type!=="uint16"&&o[0].type!=="int32"&&o[0].type!=="uint32"&&o[0].type!=="float32"&&o[0].type!=="float64"&&o[0].type!=="bool")throw new Error("Invalid input type.")}},3933:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseSqueezeAttributes=n.squeezeV13=n.squeeze=void 0;const d=u(2517);n.squeeze=(s,h,f)=>{l(h);const a=d.ShapeUtil.squeezeShape(h[0].dims,f);return[s.reshapeUnpacked(h[0],a)]},n.squeezeV13=(s,h)=>(p(h),(0,n.squeeze)(s,[h[0]],Array.from(h[1].integerData))),n.parseSqueezeAttributes=s=>s.attributes.getInts("axes");const l=s=>{if(!s||s.length!==1)throw new Error("Squeeze requires 1 input.");if(s[0].type==="string")throw new Error("invalid input tensor types.")},p=s=>{if(!s||s.length!==2)throw new Error("Squeeze requires 2 inputs.");if(s[1].type!=="int32")throw new Error("Invalid input type.")}},6558:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.sum=void 0;const d=u(5060),l=u(2039);n.sum=(h,f)=>{s(f);const a={name:"Sum",inputNames:f.map((o,t)=>`X${t}`),inputTypes:new Array(f.length).fill(l.TextureType.unpacked)};return[h.run(Object.assign(Object.assign({},a),{get:()=>p(h,f,a)}),f)]};const p=(h,f,a)=>{const o=(0,d.getGlsl)(h.session.backend.glContext.version),t=f[0].dims.slice(),e=` - void main() { - vec4 result = ${f.map((r,i)=>`${o.texture2D}(X${i},TexCoords)`).join(" + ")}; - ${o.output} = result; - } - `;return Object.assign(Object.assign({},a),{output:{dims:t,type:f[0].type,textureType:l.TextureType.unpacked},hasMain:!0,shaderSource:e})},s=h=>{if(!h||h.length===0)throw new Error("Sum requires inputs.");const f=h[0].dims.length;for(let a=1;a{Object.defineProperty(n,"__esModule",{value:!0}),n.tile=void 0;const d=u(782),l=u(2039);n.tile=(h,f)=>{s(f);const a={name:"Tile",inputNames:["A"],inputTypes:[l.TextureType.unpacked]};return[h.run(Object.assign(Object.assign({},a),{get:()=>p(h,f,a)}),f)]};const p=(h,f,a)=>{const o=f[0].dims.slice(),t=new Array(o.length),e=[];for(let c=0;c{if(!h||h.length!==2)throw new Error("Tile requires 2 input.");if(h[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(h[1].dims[0]!==h[0].dims.length)throw new Error("Invalid input shape.");if(d.NUMBER_TYPES.indexOf(h[0].type)===-1)throw new Error("Invalid input type.");if(h[1].type!=="int32"&&h[1].type!=="int16")throw new Error("Invalid repeat type.")}},3738:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseTransposeAttributes=n.transpose=void 0;const d=u(246),l=u(2517),p=u(2039),s={name:"Transpose",inputNames:["A"],inputTypes:[p.TextureType.unpacked]};n.transpose=(e,r,i)=>(t(r),[e.run(Object.assign(Object.assign({},s),{cacheHint:i.cacheKey,get:()=>h(e,r[0],i.perm)}),r)]),n.parseTransposeAttributes=e=>(0,d.createAttributeWithCacheKey)({perm:e.attributes.getInts("perm",[])});const h=(e,r,i)=>{const c=r.dims;i=f(c,i);const g=a(c,i),m=c.length,b=` - ${o("perm",i,m)} - float process(int indices[${m}]) { - int a[${m}]; - perm(a, indices); - return _A(a); - }`;return Object.assign(Object.assign({},s),{output:{dims:g,type:r.type,textureType:p.TextureType.unpacked},shaderSource:b})},f=(e,r)=>(r&&r.length!==e.length&&(r=[...e.keys()].reverse()),r),a=(e,r)=>(r=f(e,r),l.ShapeUtil.sortBasedOnPerm(e,r)),o=(e,r,i)=>{const c=[];c.push(`void ${e}(out int a[${i}], int src[${i}]) {`);for(let g=0;g{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("input should be float tensor")}},8710:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.encodeAsUint8=void 0;const d=u(5060),l=u(2039);n.encodeAsUint8=(p,s)=>{const h=s.shape,f=(0,d.getGlsl)(p.session.backend.glContext.version),a=` - const float FLOAT_MAX = 1.70141184e38; - const float FLOAT_MIN = 1.17549435e-38; - - bool isNaN(float val) { - return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; - } - - highp vec4 encodeAsUint8(highp float v) { - if (isNaN(v)) { - return vec4(255, 255, 255, 255); - } - - highp float av = abs(v); - - if(av < FLOAT_MIN) { - return vec4(0.0, 0.0, 0.0, 0.0); - } else if(v > FLOAT_MAX) { - return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; - } else if(v < -FLOAT_MAX) { - return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; - } - - highp vec4 c = vec4(0,0,0,0); - - highp float e = floor(log2(av)); - highp float m = exp2(fract(log2(av))) - 1.0; - - c[2] = floor(128.0 * m); - m -= c[2] / 128.0; - c[1] = floor(32768.0 * m); - m -= c[1] / 32768.0; - c[0] = floor(8388608.0 * m); - - highp float ebias = e + 127.0; - c[3] = floor(ebias / 2.0); - ebias -= c[3] * 2.0; - c[2] += floor(ebias) * 128.0; - - c[3] += 128.0 * step(0.0, -v); - - return c / 255.0; - } - - void main() { - float value = ${f.texture2D}(X,TexCoords).r; - ${f.output} = encodeAsUint8(value); - }`,o={name:"Uint8Encode",inputTypes:[l.TextureType.unpacked],inputNames:["X"],output:{dims:h,type:s.tensor.type,textureType:l.TextureType.downloadUint8AsFloat},shaderSource:a,hasMain:!0};return p.executeProgram(o,[s.tensor])}},4909:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.tanh=n.tan=n.sqrt=n.sin=n.sigmoid=n.relu=n.not=n.neg=n.log=n.parseLeakyReluAttributes=n.leakyRelu=n.identity=n.floor=n.exp=n.parseEluAttributes=n.elu=n.cos=n.ceil=n.clipV11=n.parseClipAttributes=n.clip=n.atan=n.asin=n.acos=n.abs=n.glslTanh=n.glslTan=n.glslSqrt=n.glslSigmoid=n.glslRelu=n.glslSin=n.glslNot=n.glslNeg=n.glslLog=n.glslLeakyRelu=n.glslIdentity=n.glslClip=n.glslFloor=n.glslExp=n.glslElu=n.glslCos=n.glslCeil=n.glslAtan=n.glslAsin=n.glslAcos=n.glslAbs=void 0;const d=u(246),l=u(2517),p=u(8520),s=u(5060),h=u(2039);function f(){return F("abs")}function a(){return F("acos")}function o(){return F("asin")}function t(){return F("atan")}function e(){return F("ceil")}function r(){return F("cos")}function i($){const z="elu";return{body:` - const float alpha = float(${$}); - - float ${z}_(float a) { - return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; - } - vec4 ${z}_(vec4 v) { - return vec4(${z}_(v.x), ${z}_(v.y), ${z}_(v.z), ${z}_(v.w)); - } - `,name:z,type:p.FunctionType.ValueBased}}function c(){return F("exp")}function g(){return F("floor")}function m($,z){const Q="clip";return{body:` - const float min = float(${$}); - const float max = float(${z}); - - float ${Q}_(float a) { - return clamp(a, min, max); - } - vec4 ${Q}_(vec4 v) { - return clamp(v, min, max); - } - `,name:Q,type:p.FunctionType.ValueBased}}function b(){const $="indentity";return{body:` - float ${$}_(float a) { - return a; - } - vec4 ${$}_(vec4 v) { - return v; - } - `,name:$,type:p.FunctionType.ValueBased}}function _($){const z="leakyRelu";return{body:` - const float alpha = float(${$}); - - float ${z}_(float a) { - return a < 0.0 ? a * alpha : a; - } - vec4 ${z}_(vec4 v) { - return vec4(${z}_(v.x), ${z}_(v.y), ${z}_(v.z), ${z}_(v.w)); - } - `,name:z,type:p.FunctionType.ValueBased}}function w(){return F("log")}function v(){const $="neg";return{body:` - float ${$}_(float a) { - return -a; - } - vec4 ${$}_(vec4 v) { - return -v; - } - `,name:$,type:p.FunctionType.ValueBased}}function S(){const $="not";return{body:` - float ${$}_(float a) { - return float( ! bool(a) ); - } - bool ${$}_(bool a) { - return !a; - } - vec4 ${$}_(vec4 v) { - return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); - } - bvec4 ${$}_(bvec4 v) { - return bvec4(!v.x, !v.y, !v.z, !v.w); - } - `,name:$,type:p.FunctionType.ValueBased}}function O(){return F("sin")}function E(){const $="relu";return{body:` - float ${$}_(float a) { - return max( a, 0.0 ); - } - vec4 ${$}_(vec4 v) { - return max( v, 0.0 ); - } - `,name:$,type:p.FunctionType.ValueBased}}function T(){const $="sigmoid";return{body:` - float ${$}_(float a) { - return 1.0 / (1.0 + exp(-a)); - } - vec4 ${$}_(vec4 v) { - return 1.0 / (1.0 + exp(-v)); - } - `,name:$,type:p.FunctionType.ValueBased}}function I(){return F("sqrt")}function C(){return F("tan")}function B(){const $="tanh";return{body:` - float ${$}_(float a) { - a = clamp(a, -10., 10.); - a = exp(2.*a); - return (a - 1.) / (a + 1.); - } - vec4 ${$}_(vec4 v) { - v = clamp(v, -10., 10.); - v = exp(2.*v); - return (v - 1.) / (v + 1.); - } - `,name:$,type:p.FunctionType.ValueBased}}function F($){return{body:` - float ${$}_(float a) { - return ${$}(a); - } - vec4 ${$}_(vec4 v) { - return ${$}(v); - } - `,name:$,type:p.FunctionType.ValueBased}}n.glslAbs=f,n.glslAcos=a,n.glslAsin=o,n.glslAtan=t,n.glslCeil=e,n.glslCos=r,n.glslElu=i,n.glslExp=c,n.glslFloor=g,n.glslClip=m,n.glslIdentity=b,n.glslLeakyRelu=_,n.glslLog=w,n.glslNeg=v,n.glslNot=S,n.glslSin=O,n.glslRelu=E,n.glslSigmoid=T,n.glslSqrt=I,n.glslTan=C,n.glslTanh=B;const N=($,z,Q,X)=>{const te=$.session.pack?h.TextureType.packed:h.TextureType.unpacked,ne={name:Q.name,inputTypes:[te],inputNames:["A"],cacheHint:X};return Object.assign(Object.assign({},ne),{get:()=>((me,Ie,Oe,ce)=>{const Te=me.session.pack?h.TextureType.packed:h.TextureType.unpacked,_e=(0,s.getGlsl)(me.session.backend.glContext.version);return Object.assign(Object.assign({},Ie),{output:{dims:Oe.dims,type:Oe.type,textureType:Te},shaderSource:` - ${ce.body} - void main() { - vec4 v = ${_e.texture2D}(A, TexCoords); - v = ${ce.name}_(v); - ${_e.output} = v; - } - `,hasMain:!0})})($,ne,z,Q)})};n.abs=($,z)=>[$.run(N($,z[0],f()),z)],n.acos=($,z)=>[$.run(N($,z[0],a()),z)],n.asin=($,z)=>[$.run(N($,z[0],o()),z)],n.atan=($,z)=>[$.run(N($,z[0],t()),z)],n.clip=($,z,Q)=>[$.run(N($,z[0],m(Q.min,Q.max),Q.cacheKey),z)],n.parseClipAttributes=$=>(0,d.createAttributeWithCacheKey)({min:$.attributes.getFloat("min",l.MIN_CLIP),max:$.attributes.getFloat("max",l.MAX_CLIP)}),n.clipV11=($,z)=>{const Q=H($,z);return(0,n.clip)($,[z[0]],Q)};const H=($,z)=>{if(z.length>=3&&(!$.session.isInitializer(z[1].dataId)||!$.session.isInitializer(z[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const Q=z.length>=3?z[1].numberData[0]:l.MIN_CLIP,X=z.length>=3?z[2].numberData[0]:l.MAX_CLIP;return(0,d.createAttributeWithCacheKey)({min:Q,max:X})};n.ceil=($,z)=>[$.run(N($,z[0],e()),z)],n.cos=($,z)=>[$.run(N($,z[0],r()),z)],n.elu=($,z,Q)=>[$.run(N($,z[0],i(Q.alpha),Q.cacheKey),z)],n.parseEluAttributes=$=>(0,d.createAttributeWithCacheKey)({alpha:$.attributes.getFloat("alpha",1)}),n.exp=($,z)=>[$.run(N($,z[0],c()),z)],n.floor=($,z)=>[$.run(N($,z[0],g()),z)],n.identity=($,z)=>[$.run(N($,z[0],b()),z)],n.leakyRelu=($,z,Q)=>[$.run(N($,z[0],_(Q.alpha),Q.cacheKey),z)],n.parseLeakyReluAttributes=$=>(0,d.createAttributeWithCacheKey)({alpha:$.attributes.getFloat("alpha",.01)}),n.log=($,z)=>[$.run(N($,z[0],w()),z)],n.neg=($,z)=>[$.run(N($,z[0],v()),z)],n.not=($,z)=>[$.run(N($,z[0],S()),z)],n.relu=($,z)=>[$.run(N($,z[0],E()),z)],n.sigmoid=($,z)=>[$.run(N($,z[0],T()),z)],n.sin=($,z)=>[$.run(N($,z[0],O()),z)],n.sqrt=($,z)=>[$.run(N($,z[0],I()),z)],n.tan=($,z)=>[$.run(N($,z[0],C()),z)],n.tanh=($,z)=>[$.run(N($,z[0],B()),z)]},5611:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createUnpackProgramInfoLoader=n.createUnpackProgramInfo=void 0;const d=u(5060),l=u(2039),p=u(9390),s=u(2827),h={name:"unpack",inputNames:["A"],inputTypes:[l.TextureType.packed]};n.createUnpackProgramInfo=(f,a)=>{const o=a.dims.length,t=(0,s.getChannels)("rc",o),e=t.slice(-2),r=(0,p.getCoordsDataType)(o),i=(0,s.unpackFromChannel)(),c=a.dims.length===0?"":function(b,_){if(b===1)return"rc";let w="";for(let v=0;vObject.assign(Object.assign({},h),{get:()=>(0,n.createUnpackProgramInfo)(f,a)})},8428:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseUnsqueezeAttributes=n.unsqueezeV13=n.unsqueeze=void 0;const d=u(2517);n.unsqueeze=(s,h,f)=>{l(h);const a=d.ShapeUtil.unsqueezeShape(h[0].dims,f);return[s.reshapeUnpacked(h[0],a)]},n.unsqueezeV13=(s,h)=>(p(h),(0,n.unsqueeze)(s,[h[0]],Array.from(h[1].integerData))),n.parseUnsqueezeAttributes=s=>s.attributes.getInts("axes");const l=s=>{if(!s||s.length!==1)throw new Error("Unsqueeze requires 1 input.");if(s[0].type==="string")throw new Error("invalid input tensor types.")},p=s=>{if(!s||s.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(s[1].type!=="int32")throw new Error("Invalid input type.")}},9793:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.scalesValidation=n.validateInputs=n.parseUpsampleAttributes=n.parseUpsampleAttributesV9=n.parseUpsampleAttributesV7=n.upsample=void 0;const d=u(246),l=u(5060),p=u(2039),s={name:"Upsample",inputNames:["X"],inputTypes:[p.TextureType.unpacked]};n.upsample=(f,a,o)=>((0,n.validateInputs)(a,o),[f.run(Object.assign(Object.assign({},s),{cacheHint:o.cacheKey,get:()=>h(f,a,o)}),a)]),n.parseUpsampleAttributesV7=f=>(0,n.parseUpsampleAttributes)(f,7),n.parseUpsampleAttributesV9=f=>(0,n.parseUpsampleAttributes)(f,9),n.parseUpsampleAttributes=(f,a)=>{const o=a>=10,t=f.attributes.getString("mode","nearest");if(t!=="nearest"&&t!=="linear"&&(a<11||t!=="cubic"))throw new Error(`unrecognized mode: ${t}`);let e=[];a<9&&(e=f.attributes.getFloats("scales"),(0,n.scalesValidation)(e,t,o));const r=f.attributes.getFloat("extrapolation_value",0),i=a>10?f.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(i)===-1)throw new Error(`coordinate_transform_mode '${i}' is not supported`);const c=i==="tf_crop_and_resize",g=c,m=t==="nearest"&&a>=11?f.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(m)===-1)throw new Error(`nearest_mode '${m}' is not supported`);const b=f.attributes.getFloat("cubic_coeff_a",-.75),_=f.attributes.getInt("exclude_outside",0)!==0;if(_&&t!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const w=a<11||t==="nearest"&&i==="asymmetric"&&m==="floor";let v=0,S=0,O=0;return a>10?f.inputs.length>2?(v=1,S=2,O=3):(S=1,O=2):a===9&&(S=1),(0,d.createAttributeWithCacheKey)({opset:a,isResize:o,mode:t,scales:e,extrapolationValue:r,coordinateTransformMode:i,useExtrapolation:g,needRoiInput:c,nearestMode:m,cubicCoefficientA:b,excludeOutside:_,useNearest2xOptimization:w,roiInputIdx:v,scalesInputIdx:S,sizesInputIdx:O})};const h=(f,a,o)=>{const t=(0,l.getGlsl)(f.session.backend.glContext.version),[e,r]=f.calculateTextureWidthAndHeight(a[0].dims,p.TextureType.unpacked),i=a[0].dims.map((O,E)=>Math.floor(O*o.scales[E])),[c,g]=f.calculateTextureWidthAndHeight(i,p.TextureType.unpacked),m=i.length,b=new Array(m),_=new Array(m);let w=` - int output_pitches[${m}]; - int input_pitches[${m}]; - `;for(let O=m-1;O>=0;O--)b[O]=O===m-1?1:b[O+1]*i[O+1],_[O]=O===m-1?1:_[O+1]*a[0].dims[O+1],w+=` - output_pitches[${O}] = ${b[O]}; - input_pitches[${O}] = ${_[O]}; - `;const v=` - float getInputFloat(int index) { - vec2 coords = offsetToCoords(index, ${e}, ${r}); - float value = getColorAsFloat(${t.texture2D}(X, coords)); - return value; - } - `,S=o.mode==="nearest"?` - ${v} - float process(int indices[${m}]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${c}, ${g}); - - ${w} - - int d, m; - for (int dim = 0; dim < ${m}; ++dim) { - d = output_index / output_pitches[dim]; - m = output_index - d * output_pitches[dim]; - output_index = m; - - if (scales[dim] != 1 && d > 0) { - int d2 = d / scales[dim]; - m = d - d2 * scales[dim]; - d = d2; - } - input_index += input_pitches[dim] * d; - } - - return getInputFloat(input_index); - }`:m===4?` - ${v} - float process(int indices[4]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${c}, ${g}); - - ${w} - - int m; - int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; - index_of_dim0 = output_index / output_pitches[0]; - m = output_index - index_of_dim0 * output_pitches[0]; - index_of_dim1 = m / output_pitches[1]; - m = m - index_of_dim1 * output_pitches[1]; - index_of_dim2 = m / output_pitches[2]; - m = m - index_of_dim2 * output_pitches[2]; - index_of_dim3 = m; - - int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; - index_of_input_dim2 = index_of_dim2 / scales[2]; - y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; - index_of_input_dim3 = index_of_dim3 / scales[3]; - x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; - - input_index = index_of_dim0 * input_pitches[0] + - index_of_dim1 * input_pitches[1] + - index_of_input_dim2 * input_pitches[2] + - index_of_input_dim3; - - float x00 = getInputFloat(input_index); - float x10, x01, x11; - - bool end_of_dim2 = false; - if (index_of_input_dim2 == (${a[0].dims[2]} - 1)) { - // It's the end in dimension 2 - x01 = x00; - end_of_dim2 = true; - } else { - x01 = getInputFloat(input_index + input_pitches[2]); - } - - if (index_of_input_dim3 == (input_pitches[2] - 1)) { - // It's the end in dimension 3 - x10 = x00; - x11 = x01; - } - else { - x10 = getInputFloat(input_index + 1); - x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); - } - - float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); - float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); - return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); - }`:` - ${v} - float process(int indices[2]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${c}, ${g}); - - ${w} - - int m; - int index_of_dim0, index_of_dim1; - index_of_dim0 = output_index / output_pitches[0]; - m = output_index - index_of_dim0 * output_pitches[0]; - index_of_dim1 = m; - - int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; - index_of_input_dim0 = index_of_dim0 / scales[0]; - y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; - index_of_input_dim1 = index_of_dim1 / scales[1]; - x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; - - input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; - - float x00 = getInputFloat(input_index); - float x10, x01, x11; - - bool end_of_dim0 = false; - if (index_of_input_dim0 == (${a[0].dims[0]} - 1)) { - // It's the end in dimension 0 - x01 = x00; - end_of_dim0 = true; - } else { - x01 = getInputFloat(input_index + input_pitches[0]); - } - - if (index_of_input_dim1 == (input_pitches[0] - 1)) { - // It's the end in dimension 1 - x10 = x00; - x11 = x01; - } - else { - x10 = getInputFloat(input_index + 1); - x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); - } - - float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); - float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); - return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); - }`;return Object.assign(Object.assign({},s),{output:{dims:i,type:a[0].type,textureType:p.TextureType.unpacked},shaderSource:S,variables:[{name:"scales",type:"int",arrayLength:o.scales.length,data:o.scales.map(O=>Math.ceil(O))}]})};n.validateInputs=(f,a)=>{if(!f||a.opset<9&&f.length!==1||a.opset>=9&&a.opset<11&&f.length!==2||a.opset>=11&&f.length<2)throw new Error("invalid inputs.");if(a.scales.length>0&&f[0].dims.length!==a.scales.length)throw new Error("Invalid input shape.");if(f[0].type==="string")throw new Error("Invalid input tensor types.")},n.scalesValidation=(f,a,o)=>{if(o){for(const t of f)if(t<=0)throw new Error("Scale value should be greater than 0.")}else for(const t of f)if(t<1)throw new Error("Scale value should be greater than or equal to 1.");if(!(a!=="linear"&&a!=="cubic"||f.length===2||f.length===4&&f[0]===1&&f[1]===1))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${o?"Resize":"Upsample"} opeartor.`)}},1958:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ProgramManager=void 0;const d=u(1670),l=u(6231),p=u(8879),s=u(5060);n.ProgramManager=class{constructor(h,f,a){this.profiler=h,this.glContext=f,this.textureLayoutStrategy=a,this.repo=new Map,this.attributesBound=!1}getArtifact(h){return this.repo.get(h)}setArtifact(h,f){this.repo.set(h,f)}run(h,f,a){var o;this.profiler.event("op",`ProgramManager.run ${(o=h.programInfo.name)!==null&&o!==void 0?o:"unknown kernel"}`,()=>{var t;const e=this.glContext.gl,r=h.program;e.useProgram(r);try{this.bindOutput(a),this.attributesBound||this.bindAttributes(h.attribLocations),this.bindUniforms(h.uniformLocations,(t=h.programInfo.variables)!==null&&t!==void 0?t:[],f)}catch(i){throw l.Logger.error("ProgramManager",h.programInfo.shaderSource),i}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(h=>this.glContext.deleteProgram(h.program))}build(h,f,a){return this.profiler.event("backend","ProgramManager.build",()=>{const o=new p.GlslPreprocessor(this.glContext,h,f,a),t=o.preprocess(),e=this.compile(t);return{programInfo:h,program:e,uniformLocations:this.getUniformLocations(e,o.context.programInfo.inputNames,o.context.programInfo.variables),attribLocations:this.getAttribLocations(e)}})}compile(h){if(!this.vertexShader){l.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const o=(0,s.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(o,this.glContext.gl.VERTEX_SHADER)}d.env.debug&&l.Logger.verbose("ProrgramManager",`FragShader: -${h} -`);const f=this.glContext.compileShader(h,this.glContext.gl.FRAGMENT_SHADER),a=this.glContext.createProgram(this.vertexShader,f);return this.glContext.deleteShader(f),a}bindOutput(h){const f=h.width,a=h.height;l.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${f}/${a}, shape=${h.shape}, type=${h.tensor.type}`),this.glContext.attachFramebuffer(h.texture,f,a)}bindAttributes(h){const f=h.position,a=h.textureCoord;this.glContext.setVertexAttributes(f,a),this.attributesBound=!0}bindUniforms(h,f,a){var o;const t=this.glContext.gl;let e=0;for(const{name:r,type:i,location:c,arrayLength:g}of h){const m=(o=f.find(b=>b.name===r))===null||o===void 0?void 0:o.data;if(i!=="sampler2D"&&!m)throw new Error(`variable '${r}' does not have data defined in program info`);switch(i){case"sampler2D":this.bindTexture(a[e],c,e),e++;break;case"float":g?t.uniform1fv(c,m):t.uniform1f(c,m);break;case"int":g?t.uniform1iv(c,m):t.uniform1i(c,m);break;default:throw new Error(`Uniform not implemented: ${i}`)}}}bindTexture(h,f,a){this.glContext.bindTextureToUniform(h.texture,a,f)}getAttribLocations(h){return{position:this.getAttribLocation(h,"position"),textureCoord:this.getAttribLocation(h,"textureCoord")}}getUniformLocations(h,f,a){const o=[];if(f)for(const t of f)o.push({name:t,type:"sampler2D",location:this.getUniformLocation(h,t)});if(a)for(const t of a)o.push(Object.assign(Object.assign({},t),{location:this.getUniformLocation(h,t.name)}));return o}getUniformLocation(h,f){const a=this.glContext.gl.getUniformLocation(h,f);if(a===null)throw new Error(`Uniform ${f} not found.`);return a}getAttribLocation(h,f){return this.glContext.gl.getAttribLocation(h,f)}}},6416:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLSessionHandler=void 0;const d=u(6231),l=u(1047),p=u(8316),s=u(1640),h=u(1958),f=u(7859),a=u(5702);n.WebGLSessionHandler=class{constructor(o,t){this.backend=o,this.context=t,this.layoutStrategy=new f.PreferLogicalStrategy(o.glContext.maxTextureSize),this.programManager=new h.ProgramManager(this.context.profiler,o.glContext,this.layoutStrategy),this.textureManager=new a.TextureManager(o.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:o.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=o.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new p.WebGLInferenceHandler(this)}onGraphInitialized(o){const t=o.getValues().filter(e=>e.from===-1&&e.tensor).map(e=>e.tensor.dataId);this.initializers=new Set(t)}isInitializer(o){return!!this.initializers&&this.initializers.has(o)}addInitializer(o){this.initializers.add(o)}getTextureData(o,t){return t?this.packedTextureDataCache.get(o):this.unpackedTextureDataCache.get(o)}setTextureData(o,t,e=!1){d.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),e?this.packedTextureDataCache.set(o,t):this.unpackedTextureDataCache.set(o,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(o=>this.textureManager.releaseTexture(o,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(o=>this.textureManager.releaseTexture(o,!0)),this.unpackedTextureDataCache=new Map}resolve(o,t,e){const r=(0,l.resolveOperator)(o,t,s.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(o,e):o}}}},7769:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Uint8DataEncoder=n.RGBAFloatDataEncoder=n.RedFloat32DataEncoder=void 0;const d=u(6231);n.RedFloat32DataEncoder=class{constructor(l,p=1){if(p===1)this.internalFormat=l.R32F,this.format=l.RED,this.textureType=l.FLOAT,this.channelSize=p;else{if(p!==4)throw new Error(`Invalid number of channels: ${p}`);this.internalFormat=l.RGBA32F,this.format=l.RGBA,this.textureType=l.FLOAT,this.channelSize=p}}encode(l,p){let s,h;return l.constructor!==Float32Array&&(d.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),h=new Float32Array(l)),p*this.channelSize>l.length?(d.Logger.warning("Encoder","Source data too small. Allocating larger array"),h=l,s=this.allocate(p*this.channelSize),h.forEach((f,a)=>s[a]=f)):(h=l,s=h),s}allocate(l){return new Float32Array(4*l)}decode(l,p){return this.channelSize===1?l.filter((s,h)=>h%4==0).subarray(0,p):l.subarray(0,p)}},n.RGBAFloatDataEncoder=class{constructor(l,p=1,s){if(p!==1&&p!==4)throw new Error(`Invalid number of channels: ${p}`);this.internalFormat=l.RGBA,this.format=l.RGBA,this.channelSize=p,this.textureType=s||l.FLOAT}encode(l,p){let s=l;return this.channelSize===1&&(d.Logger.verbose("Encoder","Exploding into a larger array"),s=this.allocate(p),l.forEach((h,f)=>s[4*f]=h)),s}allocate(l){return new Float32Array(4*l)}decode(l,p){return this.channelSize===1?l.filter((s,h)=>h%4==0).subarray(0,p):l.subarray(0,p)}},n.Uint8DataEncoder=class{constructor(l,p=1){if(this.channelSize=4,p===1)this.internalFormat=l.ALPHA,this.format=l.ALPHA,this.textureType=l.UNSIGNED_BYTE,this.channelSize=p;else{if(p!==4)throw new Error(`Invalid number of channels: ${p}`);this.internalFormat=l.RGBA,this.format=l.RGBA,this.textureType=l.UNSIGNED_BYTE,this.channelSize=p}}encode(l,p){return new Uint8Array(l.buffer,l.byteOffset,l.byteLength)}allocate(l){return new Uint8Array(l*this.channelSize)}decode(l,p){if(l instanceof Uint8Array)return l.subarray(0,p);throw new Error(`Invalid array type: ${l.constructor}`)}}},7859:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getBatchDim=n.sizeToSquarishShape=n.getRowsCols=n.sizeFromShape=n.isInt=n.parseAxisParam=n.squeezeShape=n.PreferLogicalStrategy=n.AlwaysKeepOriginalSizeStrategy=void 0;const d=u(6231),l=u(2517);function p(o,t){const e=[],r=[],i=t!=null&&Array.isArray(t)&&t.length===0,c=t==null||i?null:s(t,o).sort();let g=0;for(let m=0;mm)&&o[m]===1&&(e.push(o[m]),r.push(m)),c[g]<=m&&g++}o[m]!==1&&(e.push(o[m]),r.push(m))}return{newShape:e,keptDims:r}}function s(o,t){const e=t.length;return o=o==null?t.map((r,i)=>i):[].concat(o),(0,l.assert)(o.every(r=>r>=-e&&r`All values in axis param must be in range [-${e}, ${e}) but got axis ${o}`),(0,l.assert)(o.every(h),()=>`All values in axis param must be integers but got axis ${o}`),o.map(r=>r<0?e+r:r)}function h(o){return o%1==0}function f(o){if(o.length===0)return 1;let t=o[0];for(let e=1;e=o.length?1:o.slice(t.breakAxis).reduce((m,b)=>m*b),g=t.breakAxis<=0?1:o.slice(0,t.breakAxis).reduce((m,b)=>m*b);if(!(c>e||g>e))return[c,g];d.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${o}, breakAxis:${t.breakAxis}`)}const r=o.reduce((c,g)=>c*g);let i=Math.floor(Math.sqrt(r));for(;i=e||r%i!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${o}`);return[i,r/i]}},n.PreferLogicalStrategy=class{constructor(o){this.maxTextureSize=o}computeTextureWH(o,t){const e=this.computeTexture(o,t);return t&&t.isPacked&&(e[0]/=2,e[1]/=2),t&&t.reverseWH?[e[1],e[0]]:e}computeTexture(o,t){const e=t&&t.isPacked;if(o.length===0)return e?[2,2]:[1,1];let r=this.maxTextureSize;if(t&&t.breakAxis!==void 0){const g=t.breakAxis>=o.length?1:o.slice(t.breakAxis).reduce((b,_)=>b*_),m=t.breakAxis<=0?1:o.slice(0,t.breakAxis).reduce((b,_)=>b*_);if(!(g>r||m>r))return[g,m];d.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${o}, breakAxis:${t.breakAxis}`)}let i=o.slice(0);e&&(r*=2,i=i.map((g,m)=>m>=i.length-2?i[m]%2==0?i[m]:i[m]+1:i[m]),i.length===1&&(i=[2,i[0]])),i.length!==2&&(i=p(i).newShape);const c=f(i);return i.length<=1&&c<=r?[1,c]:i.length===2&&i[0]<=r&&i[1]<=r?i:i.length===3&&i[0]*i[1]<=r&&i[2]<=r?[i[0]*i[1],i[2]]:i.length===3&&i[0]<=r&&i[1]*i[2]<=r?[i[0],i[1]*i[2]]:i.length===4&&i[0]*i[1]*i[2]<=r&&i[3]<=r?[i[0]*i[1]*i[2],i[3]]:i.length===4&&i[0]<=r&&i[1]*i[2]*i[3]<=r?[i[0],i[1]*i[2]*i[3]]:e?a(c/4).map(g=>2*g):a(c)}},n.squeezeShape=p,n.parseAxisParam=s,n.isInt=h,n.sizeFromShape=f,n.getRowsCols=function(o){if(o.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[o.length>1?o[o.length-2]:1,o[o.length-1]]},n.sizeToSquarishShape=a,n.getBatchDim=function(o,t=2){return f(o.slice(0,o.length-t))}},4057:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createTextureLayoutFromShape=n.calculateTextureWidthAndHeight=n.createTextureLayoutFromTextureType=void 0;const d=u(2517),l=u(2039);n.createTextureLayoutFromTextureType=(p,s,h)=>{const f=h===l.TextureType.unpacked||h===l.TextureType.unpackedReversed?1:4,a=h===l.TextureType.packed,o=h===l.TextureType.unpackedReversed||h===l.TextureType.packed,t=h===l.TextureType.packedLastDimension?s.length-1:void 0,e=h===l.TextureType.packedLastDimension?s.map((r,i)=>i===s.length-1?4*r:r):void 0;return(0,n.createTextureLayoutFromShape)(p,s,f,e,{isPacked:a,reverseWH:o,breakAxis:t})},n.calculateTextureWidthAndHeight=(p,s,h)=>{const f=(0,n.createTextureLayoutFromTextureType)(p,s,h);return[f.width,f.height]},n.createTextureLayoutFromShape=(p,s,h=1,f,a)=>{const o=!(!a||!a.isPacked),[t,e]=p.computeTextureWH(o&&f||s,a),r=s.length;let i=s.slice(0);if(r===0&&(i=[1]),h===1)f=s;else if(o){if(h!==4)throw new Error("a packed texture must be 4-channel");f=s,r>0&&(i[r-1]=Math.ceil(i[r-1]/2)),r>1&&(i[r-2]=Math.ceil(i[r-2]/2))}else if(!f)throw new Error("Unpacked shape is needed when using channels > 1");return{width:t,height:e,channels:h,isPacked:o,shape:i,strides:d.ShapeUtil.computeStrides(i),unpackedShape:f,reversedWH:a&&a.reverseWH}}},5702:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.TextureManager=void 0;const d=u(6231);n.TextureManager=class{constructor(l,p,s,h){this.glContext=l,this.layoutStrategy=p,this.profiler=s,this.config=h,this.pendingRead=new Map,h.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(l,p,s,h){const f=this.toEncoderType(l),a=this.glContext.getEncoder(f,p.channels||1,h);if(p.isPacked&&h===1)throw new Error("not implemented");const o=p.width,t=p.height;let e,r;if(this.config.reuseTextures){e=`${o}x${t}_${a.format}_${a.internalFormat}_${a.textureType}`,r=this.inUseTextures.get(e),r||(r=[],this.inUseTextures.set(e,r));const c=this.idleTextures.get(e);if(c&&c.length>0){const g=c.pop();return r.push(g),h===1&&this.glContext.updateTexture(g,o,t,a,this.toTextureData(l,s)),g}}d.Logger.verbose("TextureManager",`Creating new texture of size ${p.width}x${p.height}`);const i=this.glContext.allocateTexture(o,t,a,this.toTextureData(l,s));return this.config.reuseTextures&&(r.push(i),this.textureLookup.set(i,e)),i}readTexture(l,p,s){return s||(s=1),this.profiler.event("backend","TextureManager.readTexture",()=>{const h=l.shape.reduce((a,o)=>a*o)*s,f=this.glContext.readTexture(l.texture,l.width,l.height,h,this.toEncoderType(p),s);return this.toTensorData(p,f)})}async readTextureAsync(l,p,s){const h=l.tensor.dataId;if(s||(s=1),this.pendingRead.has(h)){const f=this.pendingRead.get(h);return new Promise(a=>f==null?void 0:f.push(a))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(h,[]);const f=l.shape.reduce((e,r)=>e*r)*s;await this.glContext.createAndWaitForFence();const a=this.glContext.readTexture(l.texture,l.width,l.height,f,this.toEncoderType(p),s),o=this.toTensorData(p,a),t=this.pendingRead.get(h);return this.pendingRead.delete(h),t==null||t.forEach(e=>e(o)),o})}readUint8TextureAsFloat(l){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{const p=l.shape.reduce((h,f)=>h*f),s=this.glContext.readTexture(l.texture,l.width,l.height,4*p,"byte",4);return new Float32Array(s.buffer,s.byteOffset,p)})}releaseTexture(l,p){let s;if(this.config.reuseTextures&&(s=this.textureLookup.get(l.texture),s)){p&&this.textureLookup.delete(s);const h=this.inUseTextures.get(s);if(h){const f=h.indexOf(l.texture);if(f!==-1){h.splice(f,1);let a=this.idleTextures.get(s);a||(a=[],this.idleTextures.set(s,a)),a.push(l.texture)}}}s&&!p||(d.Logger.verbose("TextureManager",`Deleting texture of size ${l.width}x${l.height}`),this.glContext.deleteTexture(l.texture))}toTensorData(l,p){switch(l){case"int16":return p instanceof Int16Array?p:Int16Array.from(p);case"int32":return p instanceof Int32Array?p:Int32Array.from(p);case"int8":return p instanceof Int8Array?p:Int8Array.from(p);case"uint16":return p instanceof Uint16Array?p:Uint16Array.from(p);case"uint32":return p instanceof Uint32Array?p:Uint32Array.from(p);case"uint8":case"bool":return p instanceof Uint8Array?p:Uint8Array.from(p);case"float32":return p instanceof Float32Array?p:Float32Array.from(p);case"float64":return p instanceof Float64Array?p:Float64Array.from(p);default:throw new Error(`TensorData type ${l} is not supported`)}}toTextureData(l,p){if(p)return p instanceof Float32Array?p:new Float32Array(p)}toEncoderType(l){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(y,n)=>{var u;Object.defineProperty(n,"__esModule",{value:!0}),n.TextureType=void 0,(u=n.TextureType||(n.TextureType={}))[u.unpacked=0]="unpacked",u[u.unpackedReversed=1]="unpackedReversed",u[u.packed=2]="packed",u[u.downloadUint8AsFloat=3]="downloadUint8AsFloat",u[u.packedLastDimension=4]="packedLastDimension"},9390:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getGlChannels=n.getCoordsDataType=n.getSqueezedParams=n.squeezeInputShape=n.generateShaderFuncNameFromInputSamplerNameAtOutCoords=n.generateShaderFuncNameFromInputSamplerName=n.repeatedTry=n.getPackedShape=void 0;const d=u(2517);n.getPackedShape=function(l){const p=l.length;return l.slice(0,p-1).concat(l[p-1]/4)},n.repeatedTry=async function(l,p=h=>0,s){return new Promise((h,f)=>{let a=0;const o=()=>{if(l())return void h();a++;const t=p(a);s!=null&&a>=s?f():setTimeout(o,t)};o()})},n.generateShaderFuncNameFromInputSamplerName=function(l){return(0,d.assert)(l!==void 0&&l.length!==0,()=>"empty string found for sampler name"),"get"+l.charAt(0).toUpperCase()+l.slice(1)},n.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(l){return(0,d.assert)(l!==void 0&&l.length!==0,()=>"empty string found for sampler name"),"get"+l.charAt(0).toUpperCase()+l.slice(1)+"AtOutCoords"},n.squeezeInputShape=function(l,p){let s=JSON.parse(JSON.stringify(l));return s=p,s},n.getSqueezedParams=function(l,p){return p.map(s=>l[s]).join(", ")},n.getCoordsDataType=function(l){if(l<=1)return"int";if(l===2)return"ivec2";if(l===3)return"ivec3";if(l===4)return"ivec4";if(l===5)return"ivec5";if(l===6)return"ivec6";throw Error(`GPU for rank ${l} is not yet supported`)},n.getGlChannels=function(l=6){return["x","y","z","w","u","v"].slice(0,l)}},7305:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createNewWebGLContext=n.createWebGLContext=void 0;const d=u(6231),l=u(1713),p={};function s(h){const f=function(){if(typeof document>"u"){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const t=document.createElement("canvas");return t.width=1,t.height=1,t}();let a;const o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!h||h==="webgl2")&&(a=f.getContext("webgl2",o),a))try{return new l.WebGLContext(a,2)}catch(t){d.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`)}if((!h||h==="webgl")&&(a=f.getContext("webgl",o)||f.getContext("experimental-webgl",o),a))try{return new l.WebGLContext(a,1)}catch(t){d.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`)}throw new Error("WebGL is not supported")}n.createWebGLContext=function h(f){let a;f&&f!=="webgl2"||!("webgl2"in p)?f&&f!=="webgl"||!("webgl"in p)||(a=p.webgl):a=p.webgl2,a=a||s(f),f=f||a.version===1?"webgl":"webgl2";const o=a.gl;return p[f]=a,o.isContextLost()?(delete p[f],h(f)):(o.disable(o.DEPTH_TEST),o.disable(o.STENCIL_TEST),o.disable(o.BLEND),o.disable(o.DITHER),o.disable(o.POLYGON_OFFSET_FILL),o.disable(o.SAMPLE_COVERAGE),o.enable(o.SCISSOR_TEST),o.enable(o.CULL_FACE),o.cullFace(o.BACK),a)},n.createNewWebGLContext=s},1713:function(y,n,u){var d=this&&this.__createBinding||(Object.create?function(o,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(o,r,i)}:function(o,t,e,r){r===void 0&&(r=e),o[r]=t[e]}),l=this&&this.__setModuleDefault||(Object.create?function(o,t){Object.defineProperty(o,"default",{enumerable:!0,value:t})}:function(o,t){o.default=t}),p=this&&this.__importStar||function(o){if(o&&o.__esModule)return o;var t={};if(o!=null)for(var e in o)e!=="default"&&Object.prototype.hasOwnProperty.call(o,e)&&d(t,o,e);return l(t,o),t};Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLContext=n.linearSearchLastTrue=void 0;const s=u(1670),h=p(u(7769)),f=u(9390);function a(o){let t=0;for(;tthis.isTimerResultAvailable(o)),this.getTimerResult(o)}async createAndWaitForFence(){const o=this.createFence(this.gl);return this.pollFence(o)}createFence(o){let t;const e=o,r=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return o.flush(),t=r===null?()=>!0:()=>{const i=e.clientWaitSync(r,0,0);return i===e.ALREADY_SIGNALED||i===e.CONDITION_SATISFIED},{query:r,isFencePassed:t}}async pollFence(o){return new Promise(t=>{this.addItemToPoll(()=>o.isFencePassed(),()=>t())})}pollItems(){const o=a(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=o;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(o+1)}async addItemToPoll(o,t){this.itemsToPoll.push({isDoneFn:o,resolveFn:t}),this.itemsToPoll.length>1||await(0,f.repeatedTry)(()=>(this.pollItems(),this.itemsToPoll.length===0))}}},1036:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExecutionPlan=void 0;const d=u(6231);class l{constructor(s,h){this.op=s,this.node=h}}n.ExecutionPlan=class{constructor(p,s,h){this.graph=p,this.profiler=h,this.initialize(s)}initialize(p){this.profiler.event("session","ExecutionPlan.initialize",()=>{const s=this.graph.getNodes();if(s.length!==p.length)throw new Error("The size of nodes and OPs do not match.");this._ops=p.map((h,f)=>new l(h,s[f])),this.reset(),this._starter=[],this._ops.forEach((h,f)=>{let a=!0;for(const o of h.node.inputs)if(!this._values[o]&&this.graph.getInputIndices().indexOf(o)===-1){a=!1;break}a&&this._starter.push(f)})})}reset(){this._values=this.graph.getValues().map(p=>p.tensor)}async execute(p,s){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();const h=p.createInferenceHandler(),f=this.graph.getInputIndices();if(s.length!==f.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${s.length} expected: ${f.length}`);s.forEach((i,c)=>{const g=f[c];this._values[g]=i});const a=this._starter.slice(0),o=this.graph.getValues(),t=this.graph.getNodes();let e=0;for(;ethis._values[w]);if(g.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${c.node}`);const m=g;d.Logger.verbose("ExecPlan",`Runing op:${c.node.name} (${m.map((w,v)=>`'${c.node.inputs[v]}': ${w.type}[${w.dims.join(",")}]`).join(", ")})`);const b=await this.profiler.event("node",c.node.name,async()=>c.op.impl(h,m,c.op.context));if(b.length!==c.node.outputs.length)throw new Error("the size of output does not match model definition.");b.forEach((w,v)=>{const S=c.node.outputs[v];if(this._values[S])throw new Error(`output [${S}] already has value: op:${c.node.name}`);this._values[S]=w});const _=new Set;b.forEach((w,v)=>{const S=c.node.outputs[v];for(const O of o[S].to){const E=t[O];let T=!0;for(const I of E.inputs)if(!this._values[I]){T=!1;break}T&&_.add(O)}}),a.push(..._)}const r=[];for(let i=0;i{Object.defineProperty(n,"__esModule",{value:!0}),n.Graph=void 0;const d=u(1446),l=u(7778),p=u(9395),s=u(9162),h=u(2517);var f=p.onnxruntime.experimental.fbs;n.Graph={from:(e,r)=>new t(e,r)};class a{constructor(r){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,r&&(this.type=h.ProtoUtil.tensorValueTypeFromProto(r.type.tensorType))}get from(){return this._from}get to(){return this._to}}class o{constructor(r,i){r instanceof d.onnx.NodeProto?(this.name=r.name,this.opType=r.opType,this.attributes=new l.Attribute(r.attribute)):r instanceof f.Node&&(this.name=i??r.name(),this.opType=r.opType(),this.attributes=new l.Attribute(h.ProtoUtil.tensorAttributesFromORTFormat(r))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class t{constructor(r,i){if(!r)throw new TypeError("graph is empty");this.buildGraph(r),this.transformGraph(i),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(r){if(r instanceof d.onnx.GraphProto)this.buildGraphFromOnnxFormat(r);else{if(!(r instanceof f.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(r)}}buildGraphFromOnnxFormat(r){const i=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const c=new Map;if(!r.input)throw new Error("missing information in graph: input");const g=[];for(const m of r.input){if(i.has(m.name))throw new Error(`duplicated input name: ${m.name}`);const b=this._allData.push(new a(m))-1;i.set(m.name,b),g.push(m.name)}if(!r.initializer)throw new Error("missing information in graph: initializer");for(const m of r.initializer){let b=i.get(m.name);if(b===void 0){const _=new a;_.type={shape:{dims:h.ProtoUtil.tensorDimsFromProto(m.dims)},tensorType:h.ProtoUtil.tensorDataTypeFromProto(m.dataType)},b=this._allData.push(_)-1,i.set(m.name,b)}this._allData[b]._from=-1,this._allData[b].tensor=s.Tensor.fromProto(m)}for(let m=0;m{this._allData[g]._to.forEach(m=>{r.add(m)})});const i=Array.from(r),c=new Array(this._nodes.length).fill("white");for(;i.length>0;){const g=i.pop();c[g]==="gray"?c[g]="black":(i.push(g),c[g]="gray",this._nodes[g].outputs.forEach(m=>{const b=this._allData[m];if(b.tensor!==void 0)throw new Error("node outputs should not be initialized");if(b._from!==g)throw new Error("from property of the Value object doesn't match index of Node being processed");b._to.forEach(_=>{if(c[_]==="gray")throw new Error("model graph is cyclic");c[_]==="white"&&i.push(_)})}))}}transformGraph(r){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),r&&r.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let r=0;for(let i=0;i0&&(this._nodes[i].inputs.forEach(c=>{const g=this._allData[c]._to.indexOf(i+r);g!==-1&&(this._allData[c]._to[g]=i)}),this._nodes[i].outputs.forEach(c=>{this._allData[c]._from&&this._allData[c]._from===i+r&&(this._allData[c]._from=i)})):(r++,this._nodes[i].outputs.forEach(c=>{this._allData[c]._from=-2}),this._nodes.splice(i,1),i--);r=0;for(let i=0;i0){let c=-1;this._allData[i].from!==void 0&&this._allData[i].from!==-1?(c=this._nodes[this._allData[i].from].outputs.indexOf(i+r),c!==-1&&(this._nodes[this._allData[i].from].outputs[c]=i)):(c=this._allInputIndices.indexOf(i+r),c!==-1&&(this._allInputIndices[c]=i)),this._allData[i].to.forEach(g=>{c=this._nodes[g].inputs.indexOf(i+r),c!==-1&&(this._nodes[g].inputs[c]=i)}),this._allData[i].to.length===0&&(c=this._allOutputIndices.indexOf(i+r),c!==-1&&(this._allOutputIndices[c]=i))}}else r++,this._allData.splice(i,1),i--}deleteNode(r){const i=this._nodes[r];if(i.outputs.length>1){for(let w=1;w0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}i.executeNode=!1;const c=i.inputs[0],g=i.outputs[0],m=this._allData[g].to,b=this._allData[c].to.indexOf(r);if(b===-1)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[c].to.splice(b,1),this._allData[g]._to=[];const _=this._allOutputIndices.indexOf(g);if(_!==-1&&(this._allOutputIndices[_]=c),m&&m.length>0)for(const w of m){const v=this._nodes[w].inputs.indexOf(g);if(v===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[w].inputs[v]=c,this._allData[c].to.push(w)}}removeAllDropoutNodes(){let r=0;for(const i of this._nodes){if(i.opType==="Dropout"){if(i.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(i.outputs.length!==1&&i.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(i.outputs.length===2&&this._allData[i.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(r)}r++}}removeAllIdentityNodes(){let r=0;for(const i of this._nodes)i.opType==="Identity"&&this.deleteNode(r),r++}isActivation(r){switch(r.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const r of this._nodes)if(r.opType==="Conv"){const i=this._allData[r.outputs[0]]._to;if(i.length===1&&this.isActivation(this._nodes[i[0]])){const c=this._nodes[i[0]];if(c.opType==="Clip")if(c.inputs.length===1)try{r.attributes.set("activation_params","floats",[c.attributes.getFloat("min"),c.attributes.getFloat("max")])}catch{r.attributes.set("activation_params","floats",[h.MIN_CLIP,h.MAX_CLIP])}else{if(!(c.inputs.length>=3&&this._allData[c.inputs[1]].tensor!==void 0&&this._allData[c.inputs[2]].tensor!==void 0))continue;r.attributes.set("activation_params","floats",[this._allData[c.inputs[1]].tensor.floatData[0],this._allData[c.inputs[2]].tensor.floatData[0]])}r.attributes.set("activation","string",c.opType),this.deleteNode(i[0])}}}}},6231:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.now=n.Profiler=n.Logger=void 0;const u={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},d={none:new class{log(o,t,e){}},console:new class{log(o,t,e){console.log(`${this.color(o)} ${e?"\x1B[35m"+e+"\x1B[0m ":""}${t}`)}color(o){switch(o){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${o}`)}}}},l={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let p={"":l};function s(o,t,e,r){if(t===void 0)return i=o,{verbose:s.verbose.bind(null,i),info:s.info.bind(null,i),warning:s.warning.bind(null,i),error:s.error.bind(null,i),fatal:s.fatal.bind(null,i)};if(e===void 0)h(o,t);else if(typeof e=="number"&&r===void 0)h(o,t);else if(typeof e=="string"&&r===void 0)h(o,e,0,t);else{if(typeof e!="string"||typeof r!="number")throw new TypeError("input is valid");h(o,e,0,t)}var i}function h(o,t,e,r){const i=p[r||""]||p[""];u[o]{g.then(async _=>{i&&await i.end(),m(_)},async _=>{i&&await i.end(),b(_)})});if(!c&&i){const m=i.end();if(m&&typeof m.then=="function")return new Promise((b,_)=>{m.then(()=>{b(g)},w=>{_(w)})})}return g}begin(o,t,e){if(!this._started)throw new Error("profiler is not started yet");if(e===void 0){const r=(0,n.now)();return this.flush(r),new f(o,t,r,i=>this.endSync(i))}{const r=e.beginTimer();return new f(o,t,0,async i=>this.end(i),r,e)}}async end(o){const t=await o.checkTimer();this._timingEvents.length=this._flushBatchSize||o-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointerperformance.now():Date.now},2644:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Model=void 0;const d=u(5686),l=u(1446),p=u(7070),s=u(9395),h=u(2517);var f=s.onnxruntime.experimental.fbs;n.Model=class{constructor(){}load(a,o,t){if(!t)try{return void this.loadFromOnnxFormat(a,o)}catch(e){if(t!==void 0)throw e}this.loadFromOrtFormat(a,o)}loadFromOnnxFormat(a,o){const t=l.onnx.ModelProto.decode(a);if(h.LongUtil.longToNumber(t.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=t.opsetImport.map(e=>({domain:e.domain,version:h.LongUtil.longToNumber(e.version)})),this._graph=p.Graph.from(t.graph,o)}loadFromOrtFormat(a,o){const t=new d.flatbuffers.ByteBuffer(a),e=f.InferenceSession.getRootAsInferenceSession(t).model();if(h.LongUtil.longToNumber(e.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let r=0;r{Object.defineProperty(n,"__esModule",{value:!0}),n.FLOAT_TYPES=n.INT_TYPES=n.NUMBER_TYPES=void 0,n.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],n.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],n.FLOAT_TYPES=["float32","float64"]},1047:(y,n)=>{function u(d,l){if(l.endsWith("+")){const p=Number.parseInt(l.substring(0,l.length-1),10);return!isNaN(p)&&p<=d}if(l.split("-").length===2){const p=l.split("-"),s=Number.parseInt(p[0],10),h=Number.parseInt(p[1],10);return!isNaN(s)&&!isNaN(h)&&s<=d&&d<=h}return Number.parseInt(l,10)===d}Object.defineProperty(n,"__esModule",{value:!0}),n.resolveOperator=void 0,n.resolveOperator=function(d,l,p){for(const s of p){const h=s[0],f=s[1],a=s[2],o=s[3],t=s[4];if(d.opType===h){for(const e of l)if((e.domain===f||e.domain==="ai.onnx"&&f==="")&&u(e.version,a))return{opImpl:o,opInit:t}}}throw new TypeError(`cannot resolve operator '${d.opType}' with opsets: ${l.map(s=>`${s.domain||"ai.onnx"} v${s.version}`).join(", ")}`)}},9395:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.onnxruntime=void 0;const d=u(5686);var l,p;l=n.onnxruntime||(n.onnxruntime={}),function(s){(function(h){h[h.UNDEFINED=0]="UNDEFINED",h[h.FLOAT=1]="FLOAT",h[h.INT=2]="INT",h[h.STRING=3]="STRING",h[h.TENSOR=4]="TENSOR",h[h.GRAPH=5]="GRAPH",h[h.FLOATS=6]="FLOATS",h[h.INTS=7]="INTS",h[h.STRINGS=8]="STRINGS",h[h.TENSORS=9]="TENSORS",h[h.GRAPHS=10]="GRAPHS",h[h.SPARSE_TENSOR=11]="SPARSE_TENSOR",h[h.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(s.AttributeType||(s.AttributeType={}))}((p=l.experimental||(l.experimental={})).fbs||(p.fbs={})),function(s){(function(h){(function(f){(function(a){a[a.UNKNOWN=0]="UNKNOWN",a[a.VALUE=1]="VALUE",a[a.PARAM=2]="PARAM"})(f.DimensionValueType||(f.DimensionValueType={}))})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){(function(a){a[a.UNDEFINED=0]="UNDEFINED",a[a.FLOAT=1]="FLOAT",a[a.UINT8=2]="UINT8",a[a.INT8=3]="INT8",a[a.UINT16=4]="UINT16",a[a.INT16=5]="INT16",a[a.INT32=6]="INT32",a[a.INT64=7]="INT64",a[a.STRING=8]="STRING",a[a.BOOL=9]="BOOL",a[a.FLOAT16=10]="FLOAT16",a[a.DOUBLE=11]="DOUBLE",a[a.UINT32=12]="UINT32",a[a.UINT64=13]="UINT64",a[a.COMPLEX64=14]="COMPLEX64",a[a.COMPLEX128=15]="COMPLEX128",a[a.BFLOAT16=16]="BFLOAT16"})(f.TensorDataType||(f.TensorDataType={}))})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){(function(a){a[a.Primitive=0]="Primitive",a[a.Fused=1]="Fused"})(f.NodeType||(f.NodeType={}))})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){(function(a){a[a.NONE=0]="NONE",a[a.tensor_type=1]="tensor_type",a[a.sequence_type=2]="sequence_type",a[a.map_type=3]="map_type"})(f.TypeInfoValue||(f.TypeInfoValue={}))})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsShape(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}dim(t,e){let r=this.bb.__offset(this.bb_pos,4);return r?(e||new s.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}dimLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}static startShape(t){t.startObject(1)}static addDim(t,e){t.addFieldOffset(0,e,0)}static createDimVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startDimVector(t,e){t.startVector(4,e,4)}static endShape(t){return t.endObject()}static createShape(t,e){return a.startShape(t),a.addDim(t,e),a.endShape(t)}}f.Shape=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimension(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}value(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new s.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}denotation(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimension(t){t.startObject(2)}static addValue(t,e){t.addFieldOffset(0,e,0)}static addDenotation(t,e){t.addFieldOffset(1,e,0)}static endDimension(t){return t.endObject()}static createDimension(t,e,r){return a.startDimension(t),a.addValue(t,e),a.addDenotation(t,r),a.endDimension(t)}}f.Dimension=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimensionValue(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):s.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}dimParam(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimensionValue(t){t.startObject(3)}static addDimType(t,e){t.addFieldInt8(0,e,s.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static addDimParam(t,e){t.addFieldOffset(2,e,0)}static endDimensionValue(t){return t.endObject()}static createDimensionValue(t,e,r,i){return a.startDimensionValue(t),a.addDimType(t,e),a.addDimValue(t,r),a.addDimParam(t,i),a.endDimensionValue(t)}}f.DimensionValue=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensorTypeAndShape(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.TensorDataType.UNDEFINED}shape(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(t,e){t.addFieldInt32(0,e,s.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,r){return a.startTensorTypeAndShape(t),a.addElemType(t,e),a.addShape(t,r),a.endTensorTypeAndShape(t)}}f.TensorTypeAndShape=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMapType(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.TensorDataType.UNDEFINED}valueType(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(t,e){t.addFieldInt32(0,e,s.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,r){return a.startMapType(t),a.addKeyType(t,e),a.addValueType(t,r),a.endMapType(t)}}f.MapType=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSequenceType(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}elemType(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new s.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSequenceType(t){t.startObject(1)}static addElemType(t,e){t.addFieldOffset(0,e,0)}static endSequenceType(t){return t.endObject()}static createSequenceType(t,e){return a.startSequenceType(t),a.addElemType(t,e),a.endSequenceType(t)}}f.SequenceType=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(h.fbs||(h.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(f,a){return this.bb_pos=f,this.bb=a,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(f,a,o,t){return f.prep(4,12),f.writeInt32(t),f.writeInt32(o),f.writeInt32(a),f.offset()}}})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNodeEdge(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}nodeIndex(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb_pos+t):0}inputEdges(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new s.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}inputEdgesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}outputEdges(t,e){let r=this.bb.__offset(this.bb_pos,8);return r?(e||new s.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}outputEdgesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNodeEdge(t){t.startObject(3)}static addNodeIndex(t,e){t.addFieldInt32(0,e,0)}static addInputEdges(t,e){t.addFieldOffset(1,e,0)}static startInputEdgesVector(t,e){t.startVector(12,e,4)}static addOutputEdges(t,e){t.addFieldOffset(2,e,0)}static startOutputEdgesVector(t,e){t.startVector(12,e,4)}static endNodeEdge(t){return t.endObject()}static createNodeEdge(t,e,r,i){return a.startNodeEdge(t),a.addNodeIndex(t,e),a.addInputEdges(t,r),a.addOutputEdges(t,i),a.endNodeEdge(t)}}f.NodeEdge=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNode(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}sinceVersion(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):0}index(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint32(this.bb_pos+t):0}opType(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.NodeType.Primitive}executionProviderType(t){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,t):null}inputs(t,e){let r=this.bb.__offset(this.bb_pos,20);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let r=this.bb.__offset(this.bb_pos,22);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}attributes(t,e){let r=this.bb.__offset(this.bb_pos,24);return r?(e||new s.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}attributesLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCounts(t){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*t):0}inputArgCountsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCountsArray(){let t=this.bb.__offset(this.bb_pos,26);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}implicitInputs(t,e){let r=this.bb.__offset(this.bb_pos,28);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}implicitInputsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNode(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDomain(t,e){t.addFieldOffset(2,e,0)}static addSinceVersion(t,e){t.addFieldInt32(3,e,0)}static addIndex(t,e){t.addFieldInt32(4,e,0)}static addOpType(t,e){t.addFieldOffset(5,e,0)}static addType(t,e){t.addFieldInt32(6,e,s.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(t,e){t.addFieldOffset(7,e,0)}static addInputs(t,e){t.addFieldOffset(8,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(9,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addAttributes(t,e){t.addFieldOffset(10,e,0)}static createAttributesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startAttributesVector(t,e){t.startVector(4,e,4)}static addInputArgCounts(t,e){t.addFieldOffset(11,e,0)}static createInputArgCountsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addInt32(e[r]);return t.endVector()}static startInputArgCountsVector(t,e){t.startVector(4,e,4)}static addImplicitInputs(t,e){t.addFieldOffset(12,e,0)}static createImplicitInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startImplicitInputsVector(t,e){t.startVector(4,e,4)}static endNode(t){return t.endObject()}static createNode(t,e,r,i,c,g,m,b,_,w,v,S,O,E){return a.startNode(t),a.addName(t,e),a.addDocString(t,r),a.addDomain(t,i),a.addSinceVersion(t,c),a.addIndex(t,g),a.addOpType(t,m),a.addType(t,b),a.addExecutionProviderType(t,_),a.addInputs(t,w),a.addOutputs(t,v),a.addAttributes(t,S),a.addInputArgCounts(t,O),a.addImplicitInputs(t,E),a.endNode(t)}}f.Node=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsValueInfo(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new s.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startValueInfo(t){t.startObject(3)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldOffset(2,e,0)}static endValueInfo(t){return t.endObject()}static createValueInfo(t,e,r,i){return a.startValueInfo(t),a.addName(t,e),a.addDocString(t,r),a.addType(t,i),a.endValueInfo(t)}}f.ValueInfo=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTypeInfo(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}denotation(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}valueType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):s.experimental.fbs.TypeInfoValue.NONE}value(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}static startTypeInfo(t){t.startObject(3)}static addDenotation(t,e){t.addFieldOffset(0,e,0)}static addValueType(t,e){t.addFieldInt8(1,e,s.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,r,i){return a.startTypeInfo(t),a.addDenotation(t,e),a.addValueType(t,r),a.addValue(t,i),a.endTypeInfo(t)}}f.TypeInfo=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}domain(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}version(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}static startOperatorSetId(t){t.startObject(2)}static addDomain(t,e){t.addFieldOffset(0,e,0)}static addVersion(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static endOperatorSetId(t){return t.endObject()}static createOperatorSetId(t,e,r){return a.startOperatorSetId(t),a.addDomain(t,e),a.addVersion(t,r),a.endOperatorSetId(t)}}f.OperatorSetId=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensor(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}dataType(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.TensorDataType.UNDEFINED}rawData(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}rawDataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}rawDataArray(){let t=this.bb.__offset(this.bb_pos,12);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}stringData(t,e){let r=this.bb.__offset(this.bb_pos,14);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}stringDataLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}static startTensor(t){t.startObject(6)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static addDataType(t,e){t.addFieldInt32(3,e,s.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(t,e){t.addFieldOffset(4,e,0)}static createRawDataVector(t,e){t.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)t.addInt8(e[r]);return t.endVector()}static startRawDataVector(t,e){t.startVector(1,e,1)}static addStringData(t,e){t.addFieldOffset(5,e,0)}static createStringDataVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startStringDataVector(t,e){t.startVector(4,e,4)}static endTensor(t){return t.endObject()}static createTensor(t,e,r,i,c,g,m){return a.startTensor(t),a.addName(t,e),a.addDocString(t,r),a.addDims(t,i),a.addDataType(t,c),a.addRawData(t,g),a.addStringData(t,m),a.endTensor(t)}}f.Tensor=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSparseTensor(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}values(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}indices(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSparseTensor(t){t.startObject(3)}static addValues(t,e){t.addFieldOffset(0,e,0)}static addIndices(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static endSparseTensor(t){return t.endObject()}static createSparseTensor(t,e,r,i){return a.startSparseTensor(t),a.addValues(t,e),a.addIndices(t,r),a.addDims(t,i),a.endSparseTensor(t)}}f.SparseTensor=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsAttribute(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):s.experimental.fbs.AttributeType.UNDEFINED}f(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readFloat32(this.bb_pos+t):0}i(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}s(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}t(t){let e=this.bb.__offset(this.bb_pos,16);return e?(t||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}g(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new s.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}floats(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*t):0}floatsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}floatsArray(){let t=this.bb.__offset(this.bb_pos,20);return t?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}ints(t){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}intsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}strings(t,e){let r=this.bb.__offset(this.bb_pos,24);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}stringsLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}tensors(t,e){let r=this.bb.__offset(this.bb_pos,26);return r?(e||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}tensorsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}graphs(t,e){let r=this.bb.__offset(this.bb_pos,28);return r?(e||new s.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}graphsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startAttribute(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldInt32(2,e,s.experimental.fbs.AttributeType.UNDEFINED)}static addF(t,e){t.addFieldFloat32(3,e,0)}static addI(t,e){t.addFieldInt64(4,e,t.createLong(0,0))}static addS(t,e){t.addFieldOffset(5,e,0)}static addT(t,e){t.addFieldOffset(6,e,0)}static addG(t,e){t.addFieldOffset(7,e,0)}static addFloats(t,e){t.addFieldOffset(8,e,0)}static createFloatsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addFloat32(e[r]);return t.endVector()}static startFloatsVector(t,e){t.startVector(4,e,4)}static addInts(t,e){t.addFieldOffset(9,e,0)}static createIntsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startIntsVector(t,e){t.startVector(8,e,8)}static addStrings(t,e){t.addFieldOffset(10,e,0)}static createStringsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startStringsVector(t,e){t.startVector(4,e,4)}static addTensors(t,e){t.addFieldOffset(11,e,0)}static createTensorsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startTensorsVector(t,e){t.startVector(4,e,4)}static addGraphs(t,e){t.addFieldOffset(12,e,0)}static createGraphsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startGraphsVector(t,e){t.startVector(4,e,4)}static endAttribute(t){return t.endObject()}static createAttribute(t,e,r,i,c,g,m,b,_,w,v,S,O,E){return a.startAttribute(t),a.addName(t,e),a.addDocString(t,r),a.addType(t,i),a.addF(t,c),a.addI(t,g),a.addS(t,m),a.addT(t,b),a.addG(t,_),a.addFloats(t,w),a.addInts(t,v),a.addStrings(t,S),a.addTensors(t,O),a.addGraphs(t,E),a.endAttribute(t)}}f.Attribute=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsGraph(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}initializers(t,e){let r=this.bb.__offset(this.bb_pos,4);return r?(e||new s.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}initializersLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeArgs(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new s.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeArgsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}nodes(t,e){let r=this.bb.__offset(this.bb_pos,8);return r?(e||new s.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}maxNodeIndex(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readUint32(this.bb_pos+t):0}nodeEdges(t,e){let r=this.bb.__offset(this.bb_pos,12);return r?(e||new s.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeEdgesLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}inputs(t,e){let r=this.bb.__offset(this.bb_pos,14);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let r=this.bb.__offset(this.bb_pos,16);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}sparseInitializers(t,e){let r=this.bb.__offset(this.bb_pos,18);return r?(e||new s.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}sparseInitializersLength(){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}static startGraph(t){t.startObject(8)}static addInitializers(t,e){t.addFieldOffset(0,e,0)}static createInitializersVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInitializersVector(t,e){t.startVector(4,e,4)}static addNodeArgs(t,e){t.addFieldOffset(1,e,0)}static createNodeArgsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodeArgsVector(t,e){t.startVector(4,e,4)}static addNodes(t,e){t.addFieldOffset(2,e,0)}static createNodesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodesVector(t,e){t.startVector(4,e,4)}static addMaxNodeIndex(t,e){t.addFieldInt32(3,e,0)}static addNodeEdges(t,e){t.addFieldOffset(4,e,0)}static createNodeEdgesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodeEdgesVector(t,e){t.startVector(4,e,4)}static addInputs(t,e){t.addFieldOffset(5,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(6,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addSparseInitializers(t,e){t.addFieldOffset(7,e,0)}static createSparseInitializersVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startSparseInitializersVector(t,e){t.startVector(4,e,4)}static endGraph(t){return t.endObject()}static createGraph(t,e,r,i,c,g,m,b,_){return a.startGraph(t),a.addInitializers(t,e),a.addNodeArgs(t,r),a.addNodes(t,i),a.addMaxNodeIndex(t,c),a.addNodeEdges(t,g),a.addInputs(t,m),a.addOutputs(t,b),a.addSparseInitializers(t,_),a.endGraph(t)}}f.Graph=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsModel(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}irVersion(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}opsetImport(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new s.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}opsetImportLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}producerName(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}producerVersion(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}modelVersion(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}docString(t){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,t):null}graph(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new s.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}graphDocString(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,t):null}static startModel(t){t.startObject(9)}static addIrVersion(t,e){t.addFieldInt64(0,e,t.createLong(0,0))}static addOpsetImport(t,e){t.addFieldOffset(1,e,0)}static createOpsetImportVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOpsetImportVector(t,e){t.startVector(4,e,4)}static addProducerName(t,e){t.addFieldOffset(2,e,0)}static addProducerVersion(t,e){t.addFieldOffset(3,e,0)}static addDomain(t,e){t.addFieldOffset(4,e,0)}static addModelVersion(t,e){t.addFieldInt64(5,e,t.createLong(0,0))}static addDocString(t,e){t.addFieldOffset(6,e,0)}static addGraph(t,e){t.addFieldOffset(7,e,0)}static addGraphDocString(t,e){t.addFieldOffset(8,e,0)}static endModel(t){return t.endObject()}static createModel(t,e,r,i,c,g,m,b,_,w){return a.startModel(t),a.addIrVersion(t,e),a.addOpsetImport(t,r),a.addProducerName(t,i),a.addProducerVersion(t,c),a.addDomain(t,g),a.addModelVersion(t,m),a.addDocString(t,b),a.addGraph(t,_),a.addGraphDocString(t,w),a.endModel(t)}}f.Model=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}nodeIndices(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*t):0}nodeIndicesLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeIndicesArray(){let t=this.bb.__offset(this.bb_pos,4);return t?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}kernelDefHashes(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}kernelDefHashesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startKernelCreateInfos(t){t.startObject(2)}static addNodeIndices(t,e){t.addFieldOffset(0,e,0)}static createNodeIndicesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addInt32(e[r]);return t.endVector()}static startNodeIndicesVector(t,e){t.startVector(4,e,4)}static addKernelDefHashes(t,e){t.addFieldOffset(1,e,0)}static createKernelDefHashesVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startKernelDefHashesVector(t,e){t.startVector(8,e,8)}static endKernelCreateInfos(t){return t.endObject()}static createKernelCreateInfos(t,e,r){return a.startKernelCreateInfos(t),a.addNodeIndices(t,e),a.addKernelDefHashes(t,r),a.endKernelCreateInfos(t)}}f.KernelCreateInfos=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSubGraphSessionState(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}graphId(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSubGraphSessionState(t){t.startObject(2)}static addGraphId(t,e){t.addFieldOffset(0,e,0)}static addSessionState(t,e){t.addFieldOffset(1,e,0)}static endSubGraphSessionState(t){let e=t.endObject();return t.requiredField(e,4),e}static createSubGraphSessionState(t,e,r){return a.startSubGraphSessionState(t),a.addGraphId(t,e),a.addSessionState(t,r),a.endSubGraphSessionState(t)}}f.SubGraphSessionState=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSessionState(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}kernels(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new s.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}subGraphSessionStates(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new s.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}subGraphSessionStatesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSessionState(t){t.startObject(2)}static addKernels(t,e){t.addFieldOffset(0,e,0)}static addSubGraphSessionStates(t,e){t.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startSubGraphSessionStatesVector(t,e){t.startVector(4,e,4)}static endSessionState(t){return t.endObject()}static createSessionState(t,e,r){return a.startSessionState(t),a.addKernels(t,e),a.addSubGraphSessionStates(t,r),a.endSessionState(t)}}f.SessionState=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(s){(function(h){(function(f){class a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInferenceSession(t,e){return(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+d.flatbuffers.SIZE_PREFIX_LENGTH),(e||new a).__init(t.readInt32(t.position())+t.position(),t)}static bufferHasIdentifier(t){return t.__has_identifier("ORTM")}ortVersion(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}model(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new s.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new s.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startInferenceSession(t){t.startObject(3)}static addOrtVersion(t,e){t.addFieldOffset(0,e,0)}static addModel(t,e){t.addFieldOffset(1,e,0)}static addSessionState(t,e){t.addFieldOffset(2,e,0)}static endInferenceSession(t){return t.endObject()}static finishInferenceSessionBuffer(t,e){t.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(t,e){t.finish(e,"ORTM",!0)}static createInferenceSession(t,e,r,i){return a.startInferenceSession(t),a.addOrtVersion(t,e),a.addModel(t,r),a.addSessionState(t,i),a.endInferenceSession(t)}}f.InferenceSession=a})(h.fbs||(h.fbs={}))})(s.experimental||(s.experimental={}))}(n.onnxruntime||(n.onnxruntime={}))},7448:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OnnxjsSessionHandler=void 0;const d=u(1670),l=u(9162);n.OnnxjsSessionHandler=class{constructor(p){this.session=p,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(p,s,h){const f=new Map;for(const t in p)if(Object.hasOwnProperty.call(p,t)){const e=p[t];f.set(t,new l.Tensor(e.dims,e.type,void 0,void 0,e.data))}const a=await this.session.run(f),o={};return a.forEach((t,e)=>{o[e]=new d.Tensor(t.type,t.data,t.dims)}),o}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Session=void 0;const d=u(7067),l=u(1296),p=u(7091),s=u(1036),h=u(6231),f=u(2644);n.Session=class{constructor(a={}){this._initialized=!1,this.backendHint=a.backendHint,this.profiler=h.Profiler.create(a.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(a,o,t){await this.profiler.event("session","Session.loadModel",async()=>{const e=await(0,p.resolveBackend)(this.backendHint);if(this.sessionHandler=e.createSessionHandler(this.context),this._model=new f.Model,typeof a=="string"){const r=a.endsWith(".ort");if(typeof fetch>"u"){const i=await(0,l.promisify)(d.readFile)(a);this.initialize(i,r)}else{const i=await fetch(a),c=await i.arrayBuffer();this.initialize(new Uint8Array(c),r)}}else if(ArrayBuffer.isView(a))this.initialize(a);else{const r=new Uint8Array(a,o||0,t||a.byteLength);this.initialize(r)}})}initialize(a,o){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{const t=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(a,t,o),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new s.ExecutionPlan(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(a){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{const o=this.normalizeAndValidateInputs(a),t=await this._executionPlan.execute(this.sessionHandler,o);return this.createOutput(t)})}normalizeAndValidateInputs(a){const o=this._model.graph.getInputNames();if(Array.isArray(a)){if(a.length!==o.length)throw new Error(`incorrect input array length: expected ${o.length} but got ${a.length}`)}else{if(a.size!==o.length)throw new Error(`incorrect input map size: expected ${o.length} but got ${a.size}`);const t=new Array(a.size);let e=0;for(let r=0;rtypeof E=="string")))throw new TypeError("cache should be a string array");O&&(this.cache=new Array(S))}else{if(w!==void 0){const E=e(m);if(!(w instanceof E))throw new TypeError(`cache should be type ${E.name}`)}if(O){const E=new ArrayBuffer(S*function(T){switch(T){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${T}`)}}(m));this.cache=function(T,I){return new(e(I))(T)}(E,m)}}}static fromProto(g){if(!g)throw new Error("cannot construct Value from an empty tensor");const m=f.ProtoUtil.tensorDataTypeFromProto(g.dataType),b=f.ProtoUtil.tensorDimsFromProto(g.dims),_=new o(b,m);if(m==="string")g.stringData.forEach((w,v)=>{_.data[v]=(0,f.decodeUtf8String)(w)});else if(g.rawData&&typeof g.rawData.byteLength=="number"&&g.rawData.byteLength>0){const w=_.data,v=new DataView(g.rawData.buffer,g.rawData.byteOffset,g.rawData.byteLength),S=t(g.dataType),O=g.rawData.byteLength/S;if(g.rawData.byteLength%S!=0)throw new Error("invalid buffer length");if(w.length!==O)throw new Error("buffer length mismatch");for(let E=0;E0){const w=_.data,v=new DataView(g.rawDataArray().buffer,g.rawDataArray().byteOffset,g.rawDataLength()),S=t(g.dataType()),O=g.rawDataLength()/S;if(g.rawDataLength()%S!=0)throw new Error("invalid buffer length");if(w.length!==O)throw new Error("buffer length mismatch");for(let E=0;E1&&I>1)return;O[S-E]=Math.max(T,I)}return O}static index(m,b){const _=new Array(b.length);return a.fillIndex(m,b,_),_}static fillIndex(m,b,_){const w=m.length-b.length;for(let v=0;v=0;Q--)T[Q]=B%S[Q],B=Math.floor(B/S[Q]);H||(a.fillIndex(T,m.dims,I),F=m.get(I)),$||(a.fillIndex(T,b.dims,C),N=b.get(C)),E.set(T,_(F,N))}}return E}}static isValidBroadcast(m,b){const _=m.length,w=b.length;if(_>w)return!1;for(let v=1;v<=_;v++)if(m[_-v]!==1&&m[_-v]!==b[w-v])return!1;return!0}static getBroadcastDims(m,b){const _=m.length,w=[];for(let v=0;v<_;v++){const S=_-1-v,O=m[S]||1;(b[b.length-1-v]||1)>1&&O===1&&w.unshift(S)}return w}}n.BroadcastUtil=a,n.arrayCopyHelper=function(g,m,b,_,w){if(_<0||_>=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(_+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let v=0;vp.default.isLong(b)?b.toNumber():b)}static tensorValueTypeFromProto(m){return{tensorType:o.tensorDataTypeFromProto(m.elemType),shape:{dims:o.tensorDimsFromProto(m.shape.dim.map(b=>b.dimValue))}}}static tensorDimsFromORTFormat(m){const b=[];for(let _=0;_m.length)throw new Error(`invalid dimension of ${b} for sizeFromDimension as Tensor has ${m.length} dimensions.`);return e.getSizeFromDimensionRange(m,b,m.length)}static sizeToDimension(m,b){if(b<0||b>m.length)throw new Error(`invalid dimension of ${b} for sizeToDimension as Tensor has ${m.length} dimensions.`);return e.getSizeFromDimensionRange(m,0,b)}static getSizeFromDimensionRange(m,b,_){let w=1;for(let v=b;v<_;v++){if(m[v]<=0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");w*=m[v]}return w}static computeStrides(m){const b=m.length;if(b===0)return[];if(b===1)return[1];const _=new Array(b);_[b-1]=1,_[b-2]=m[b-1];for(let w=b-3;w>=0;--w)_[w]=_[w+1]*m[w+1];return _}static transpose(m){return m.slice().reverse()}static indicesToOffset(m,b,_){_===void 0&&(_=m.length);let w=0;for(let v=0;v<_;++v)w+=b[v]*m[v];return w}static offsetToIndices(m,b){const _=b.length;if(_===0)return[];if(_===1)return[m*b[0]];const w=new Array(b.length);for(let v=0;v=b)throw new Error("unsupported axis for this operation.");return m<0?m+b:m}static normalizeAxes(m,b){return m.map(_=>this.normalizeAxis(_,b))}static incrementIndex(m,b,_){if(b.length===0||m.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(_===void 0)_=b.length;else if(_<=0||_>b.length)throw new Error("Incorrect axis to increment on");for(let w=_-1;w>=0&&(m[w]++,!(m[w]=m.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");w[E]=m[E]}else w[E]=b[E];S*=w[E]}}const O=e.size(m);if(v!==-1){if(O%S!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${m}] Output shape: [${b}]`);w[v]=O/S}else if(S!==O)throw new Error("reshapedDims and originalDims don't have matching sizes");return w}static sortBasedOnPerm(m,b){return b?b.map(_=>m[_]):m.slice().reverse()}static padShape(m,b){const _=m.length;return m.map((w,v)=>w+b[v]+b[v+_])}static areEqual(m,b){return m.length===b.length&&m.every((_,w)=>_===b[w])}static validateDimsAndCalcSize(m){if(m.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let b=1;for(const _ of m){if(!Number.isInteger(_))throw new TypeError(`Invalid shape: ${_} is not an integer`);if(_<0||_>2147483647)throw new TypeError(`Invalid shape: length ${_} is not allowed`);b*=_}return b}static flattenShape(m,b){b<0&&(b+=m.length);const _=m.reduce((v,S)=>v*S,1),w=m.slice(b).reduce((v,S)=>v*S,1);return[_/w,w]}static squeezeShape(m,b){const _=new Array;b=e.normalizeAxes(b,m.length);for(let w=0;w=0;if(v&&m[w]!==1)throw new Error("squeeze an axis of size different than 1");(b.length===0&&m[w]>1||b.length>0&&!v)&&_.push(m[w])}return _}static unsqueezeShape(m,b){const _=new Array(m.length+b.length);_.fill(0);for(let v=0;v=_.length)throw new Error("'axes' has an out of range axis");if(_[S]!==0)throw new Error("'axes' has a duplicate axis");_[S]=1}let w=0;for(let v=0;v<_.length;v++)_[v]===0&&(_[v]=m[w++]);if(w!==m.length)throw new Error("the unsqueezed dimension could not be established");return _}}n.ShapeUtil=e,n.MathUtil=class{static sqr(g,m,b,_,w){if(_<0||_>=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(_+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let v=0;v=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(_+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let S=0;S=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(_+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let S=0;S=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(_+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let v=0;vb.push(N));const O=i.calcReduceShape(S,b,!0),E=e.size(O),T=new h.Tensor(O,m.type),I=e.computeStrides(O),C=e.computeStrides(S),B=new Array(S.length);for(let F=0;F=b.length)return S(m[v]);const T=b[w],I=T>=_.length?1:e.size(_.slice(T+1));for(let C=0;C<_[T];C++)E=C===0?i.calcReduceByAxis(m,b,_,w+1,v,S,O):O(E,i.calcReduceByAxis(m,b,_,w+1,v,S,O)),v+=I;return E}static calcReduceShape(m,b,_){const w=m.slice();for(let v=0;vv!==0)}}n.ReduceUtil=i;class c{static adjustPoolAttributes(m,b,_,w,v,S){if(!m&&_.length!==b.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(m)for(let O=0;O=_.length?_.push(b[O+2]):_[O]=b[O+2];for(let O=0;O<_.length;O++)if(O=_[O]||S[O+_.length]>=_[O])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(m,b,_,w,v,S){if(S){if(v.length!==2*(m.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(b.length!==m.length-2)throw new Error("length of strides should be the length of data dimensions");if(w.length!==m.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let O=0;O{Object.defineProperty(n,"__esModule",{value:!0}),n.iterateExtraOptions=void 0,n.iterateExtraOptions=(u,d,l,p)=>{if(typeof u=="object"&&u!==null){if(l.has(u))throw new Error("Circular reference in options");l.add(u)}Object.entries(u).forEach(([s,h])=>{const f=d?d+s:s;if(typeof h=="object")(0,n.iterateExtraOptions)(h,f+".",l,p);else if(typeof h=="string"||typeof h=="number")p(f,h.toString());else{if(typeof h!="boolean")throw new Error("Can't handle extra config type: "+typeof h);p(f,h?"1":"0")}})}},2157:function(y,n,u){var d,l=this&&this.__createBinding||(Object.create?function(I,C,B,F){F===void 0&&(F=B);var N=Object.getOwnPropertyDescriptor(C,B);N&&!("get"in N?!C.__esModule:N.writable||N.configurable)||(N={enumerable:!0,get:function(){return C[B]}}),Object.defineProperty(I,F,N)}:function(I,C,B,F){F===void 0&&(F=B),I[F]=C[B]}),p=this&&this.__setModuleDefault||(Object.create?function(I,C){Object.defineProperty(I,"default",{enumerable:!0,value:C})}:function(I,C){I.default=C}),s=this&&this.__importStar||function(I){if(I&&I.__esModule)return I;var C={};if(I!=null)for(var B in I)B!=="default"&&Object.prototype.hasOwnProperty.call(I,B)&&l(C,I,B);return p(C,I),C};Object.defineProperty(n,"__esModule",{value:!0}),n.endProfiling=n.run=n.releaseSession=n.createSession=n.createSessionFinalize=n.createSessionAllocate=n.initOrt=n.initWasm=void 0;const h=u(1670),f=s(u(349)),a=u(6361),o=()=>!!h.env.wasm.proxy&&typeof document<"u";let t,e,r,i=!1,c=!1,g=!1;const m=[],b=[],_=[],w=[],v=[],S=[],O=()=>{if(i||!c||g||!t)throw new Error("worker not ready")},E=I=>{switch(I.data.type){case"init-wasm":i=!1,I.data.err?(g=!0,e[1](I.data.err)):(c=!0,e[0]());break;case"init-ort":I.data.err?r[1](I.data.err):r[0]();break;case"create_allocate":I.data.err?m.shift()[1](I.data.err):m.shift()[0](I.data.out);break;case"create_finalize":I.data.err?b.shift()[1](I.data.err):b.shift()[0](I.data.out);break;case"create":I.data.err?_.shift()[1](I.data.err):_.shift()[0](I.data.out);break;case"release":I.data.err?w.shift()[1](I.data.err):w.shift()[0]();break;case"run":I.data.err?v.shift()[1](I.data.err):v.shift()[0](I.data.out);break;case"end-profiling":I.data.err?S.shift()[1](I.data.err):S.shift()[0]()}},T=typeof document<"u"?(d=document==null?void 0:document.currentScript)===null||d===void 0?void 0:d.src:void 0;n.initWasm=async()=>{if(o()){if(c)return;if(i)throw new Error("multiple calls to 'initWasm()' detected.");if(g)throw new Error("previous call to 'initWasm()' failed.");return i=!0,h.env.wasm.wasmPaths===void 0&&T&&T.indexOf("blob:")!==0&&(h.env.wasm.wasmPaths=T.substr(0,+T.lastIndexOf("/")+1)),new Promise((I,C)=>{t==null||t.terminate(),t=u(9710).Z(),t.onmessage=E,e=[I,C];const B={type:"init-wasm",in:h.env.wasm};t.postMessage(B)})}return(0,a.initializeWebAssembly)(h.env.wasm)},n.initOrt=async(I,C)=>{if(o())return O(),new Promise((B,F)=>{r=[B,F];const N={type:"init-ort",in:{numThreads:I,loggingLevel:C}};t.postMessage(N)});f.initOrt(I,C)},n.createSessionAllocate=async I=>o()?(O(),new Promise((C,B)=>{m.push([C,B]);const F={type:"create_allocate",in:{model:I}};t.postMessage(F,[I.buffer])})):f.createSessionAllocate(I),n.createSessionFinalize=async(I,C)=>o()?(O(),new Promise((B,F)=>{b.push([B,F]);const N={type:"create_finalize",in:{modeldata:I,options:C}};t.postMessage(N)})):f.createSessionFinalize(I,C),n.createSession=async(I,C)=>o()?(O(),new Promise((B,F)=>{_.push([B,F]);const N={type:"create",in:{model:I,options:C}};t.postMessage(N,[I.buffer])})):f.createSession(I,C),n.releaseSession=async I=>{if(o())return O(),new Promise((C,B)=>{w.push([C,B]);const F={type:"release",in:I};t.postMessage(F)});f.releaseSession(I)},n.run=async(I,C,B,F,N)=>o()?(O(),new Promise((H,$)=>{v.push([H,$]);const z={type:"run",in:{sessionId:I,inputIndices:C,inputs:B,outputIndices:F,options:N}};t.postMessage(z,f.extractTransferableBuffers(B))})):f.run(I,C,B,F,N),n.endProfiling=async I=>{if(o())return O(),new Promise((C,B)=>{S.push([C,B]);const F={type:"end-profiling",in:I};t.postMessage(F)});f.endProfiling(I)}},586:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.setRunOptions=void 0;const d=u(7967),l=u(4983),p=u(6361);n.setRunOptions=s=>{const h=(0,p.getInstance)();let f=0;const a=[],o=s||{};try{if((s==null?void 0:s.logSeverityLevel)===void 0)o.logSeverityLevel=2;else if(typeof s.logSeverityLevel!="number"||!Number.isInteger(s.logSeverityLevel)||s.logSeverityLevel<0||s.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${s.logSeverityLevel}`);if((s==null?void 0:s.logVerbosityLevel)===void 0)o.logVerbosityLevel=0;else if(typeof s.logVerbosityLevel!="number"||!Number.isInteger(s.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${s.logVerbosityLevel}`);(s==null?void 0:s.terminate)===void 0&&(o.terminate=!1);let t=0;if((s==null?void 0:s.tag)!==void 0&&(t=(0,l.allocWasmString)(s.tag,a)),f=h._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,t),f===0)throw new Error("Can't create run options");return(s==null?void 0:s.extra)!==void 0&&(0,d.iterateExtraOptions)(s.extra,"",new WeakSet,(e,r)=>{const i=(0,l.allocWasmString)(e,a),c=(0,l.allocWasmString)(r,a);if(h._OrtAddRunConfigEntry(f,i,c)!==0)throw new Error(`Can't set a run config entry: ${e} - ${r}`)}),[f,a]}catch(t){throw f!==0&&h._OrtReleaseRunOptions(f),a.forEach(h._free),t}}},2306:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OnnxruntimeWebAssemblySessionHandler=void 0;const d=u(2806),l=u(1670),p=u(2850),s=u(2157);let h;n.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(f){const a=await fetch(f),o=await a.arrayBuffer();return(0,s.createSessionAllocate)(new Uint8Array(o))}async loadModel(f,a){if(h||(await(0,s.initOrt)(l.env.wasm.numThreads,(o=>{switch(o){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${o}`)}})(l.env.logLevel)),h=!0),typeof f=="string")if(typeof fetch>"u"){const o=await(0,p.promisify)(d.readFile)(f);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(o,a)}else{const o=await this.createSessionAllocate(f);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSessionFinalize)(o,a)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(f,a)}async dispose(){return(0,s.releaseSession)(this.sessionId)}async run(f,a,o){const t=[],e=[];Object.entries(f).forEach(g=>{const m=g[0],b=g[1],_=this.inputNames.indexOf(m);if(_===-1)throw new Error(`invalid input '${m}'`);t.push(b),e.push(_)});const r=[];Object.entries(a).forEach(g=>{const m=g[0],b=this.outputNames.indexOf(m);if(b===-1)throw new Error(`invalid output '${m}'`);r.push(b)});const i=await(0,s.run)(this.sessionId,e,t.map(g=>[g.type,g.dims,g.data]),r,o),c={};for(let g=0;g{Object.defineProperty(n,"__esModule",{value:!0}),n.setSessionOptions=void 0;const d=u(7967),l=u(4983),p=u(6361);n.setSessionOptions=s=>{const h=(0,p.getInstance)();let f=0;const a=[],o=s||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(o);try{(s==null?void 0:s.graphOptimizationLevel)===void 0&&(o.graphOptimizationLevel="all");const t=(i=>{switch(i){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${i}`)}})(o.graphOptimizationLevel);(s==null?void 0:s.enableCpuMemArena)===void 0&&(o.enableCpuMemArena=!0),(s==null?void 0:s.enableMemPattern)===void 0&&(o.enableMemPattern=!0),(s==null?void 0:s.executionMode)===void 0&&(o.executionMode="sequential");const e=(i=>{switch(i){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${i}`)}})(o.executionMode);let r=0;if((s==null?void 0:s.logId)!==void 0&&(r=(0,l.allocWasmString)(s.logId,a)),(s==null?void 0:s.logSeverityLevel)===void 0)o.logSeverityLevel=2;else if(typeof s.logSeverityLevel!="number"||!Number.isInteger(s.logSeverityLevel)||s.logSeverityLevel<0||s.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${s.logSeverityLevel}`);if((s==null?void 0:s.logVerbosityLevel)===void 0)o.logVerbosityLevel=0;else if(typeof s.logVerbosityLevel!="number"||!Number.isInteger(s.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${s.logVerbosityLevel}`);if((s==null?void 0:s.enableProfiling)===void 0&&(o.enableProfiling=!1),f=h._OrtCreateSessionOptions(t,!!o.enableCpuMemArena,!!o.enableMemPattern,e,!!o.enableProfiling,0,r,o.logSeverityLevel,o.logVerbosityLevel),f===0)throw new Error("Can't create session options");return s!=null&&s.executionProviders&&((i,c,g)=>{for(const m of c){let b=typeof m=="string"?m:m.name;switch(b){case"xnnpack":b="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${b}`)}const _=(0,l.allocWasmString)(b,g);if((0,p.getInstance)()._OrtAppendExecutionProvider(i,_)!==0)throw new Error(`Can't append execution provider: ${b}`)}})(f,s.executionProviders,a),(s==null?void 0:s.extra)!==void 0&&(0,d.iterateExtraOptions)(s.extra,"",new WeakSet,(i,c)=>{const g=(0,l.allocWasmString)(i,a),m=(0,l.allocWasmString)(c,a);if(h._OrtAddSessionConfigEntry(f,g,m)!==0)throw new Error(`Can't set a session config entry: ${i} - ${c}`)}),[f,a]}catch(t){throw f!==0&&h._OrtReleaseSessionOptions(f),a.forEach(h._free),t}}},4983:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.allocWasmString=void 0;const d=u(6361);n.allocWasmString=(l,p)=>{const s=(0,d.getInstance)(),h=s.lengthBytesUTF8(l)+1,f=s._malloc(h);return s.stringToUTF8(l,f,h),p.push(f),f}},349:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.extractTransferableBuffers=n.endProfiling=n.run=n.releaseSession=n.createSession=n.createSessionFinalize=n.createSessionAllocate=n.initOrt=void 0;const d=u(586),l=u(4919),p=u(4983),s=u(6361);n.initOrt=(t,e)=>{const r=(0,s.getInstance)()._OrtInit(t,e);if(r!==0)throw new Error(`Can't initialize onnxruntime. error code = ${r}`)};const h=new Map;n.createSessionAllocate=t=>{const e=(0,s.getInstance)(),r=e._malloc(t.byteLength);return e.HEAPU8.set(t,r),[r,t.byteLength]},n.createSessionFinalize=(t,e)=>{const r=(0,s.getInstance)();let i=0,c=0,g=[];try{if([c,g]=(0,l.setSessionOptions)(e),i=r._OrtCreateSession(t[0],t[1],c),i===0)throw new Error("Can't create a session")}finally{r._free(t[0]),r._OrtReleaseSessionOptions(c),g.forEach(r._free)}const m=r._OrtGetInputCount(i),b=r._OrtGetOutputCount(i),_=[],w=[],v=[],S=[];for(let O=0;O{const r=(0,n.createSessionAllocate)(t);return(0,n.createSessionFinalize)(r,e)},n.releaseSession=t=>{const e=(0,s.getInstance)(),r=h.get(t);if(!r)throw new Error("invalid session id");const i=r[0],c=r[1],g=r[2];c.forEach(e._OrtFree),g.forEach(e._OrtFree),e._OrtReleaseSession(i),h.delete(t)};const f=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},a=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},o=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};n.run=(t,e,r,i,c)=>{const g=(0,s.getInstance)(),m=h.get(t);if(!m)throw new Error("invalid session id");const b=m[0],_=m[1],w=m[2],v=e.length,S=i.length;let O=0,E=[];const T=[],I=[];try{[O,E]=(0,d.setRunOptions)(c);for(let $=0;$g.HEAP32[Oe++]=Te);const ce=g._OrtCreateTensor(f(z),te,ne,Ie,Q.length);if(ce===0)throw new Error("Can't create a tensor");T.push(ce)}finally{g.stackRestore(me)}}const C=g.stackSave(),B=g.stackAlloc(4*v),F=g.stackAlloc(4*v),N=g.stackAlloc(4*S),H=g.stackAlloc(4*S);try{let $=B/4,z=F/4,Q=N/4,X=H/4;for(let me=0;meve*je);if(Te=a(We),Te==="string"){const ve=[];let je=_e/4;for(let ze=0;ze{const e=(0,s.getInstance)(),r=h.get(t);if(!r)throw new Error("invalid session id");const i=r[0],c=e._OrtEndProfiling(i);if(c===0)throw new Error("Can't get an profile file name");e._OrtFree(c)},n.extractTransferableBuffers=t=>{const e=[];for(const r of t){const i=r[2];!Array.isArray(i)&&i.buffer&&e.push(i.buffer)}return e}},6361:function(y,n,u){var d=this&&this.__createBinding||(Object.create?function(c,g,m,b){b===void 0&&(b=m);var _=Object.getOwnPropertyDescriptor(g,m);_&&!("get"in _?!g.__esModule:_.writable||_.configurable)||(_={enumerable:!0,get:function(){return g[m]}}),Object.defineProperty(c,b,_)}:function(c,g,m,b){b===void 0&&(b=m),c[b]=g[m]}),l=this&&this.__setModuleDefault||(Object.create?function(c,g){Object.defineProperty(c,"default",{enumerable:!0,value:g})}:function(c,g){c.default=g}),p=this&&this.__importStar||function(c){if(c&&c.__esModule)return c;var g={};if(c!=null)for(var m in c)m!=="default"&&Object.prototype.hasOwnProperty.call(c,m)&&d(g,c,m);return l(g,c),g},s=this&&this.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(n,"__esModule",{value:!0}),n.dispose=n.getInstance=n.initializeWebAssembly=void 0;const h=p(u(6449)),f=s(u(932)),a=u(3474);let o,t=!1,e=!1,r=!1;const i=(c,g)=>g?c?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":c?"ort-wasm-simd.wasm":"ort-wasm.wasm";n.initializeWebAssembly=async c=>{if(t)return Promise.resolve();if(e)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(r)throw new Error("previous call to 'initializeWebAssembly()' failed.");e=!0;const g=c.initTimeout,m=c.numThreads,b=c.simd,_=m>1&&(()=>{try{return typeof SharedArrayBuffer<"u"&&(typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch{return!1}})(),w=b&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}})(),v=typeof c.wasmPaths=="string"?c.wasmPaths:void 0,S=i(!1,_),O=i(w,_),E=typeof c.wasmPaths=="object"?c.wasmPaths[O]:void 0;let T=!1;const I=[];if(g>0&&I.push(new Promise(C=>{setTimeout(()=>{T=!0,C()},g)})),I.push(new Promise((C,B)=>{const F=_?a:f.default,N={locateFile:(H,$)=>_&&H.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([u(4154)],{type:"text/javascript"})):H===S?E??(v??$)+O:$+H};if(_)if(typeof Blob>"u")N.mainScriptUrlOrBlob=h.join("/","ort-wasm-threaded.js");else{const H=`var ortWasmThreaded=(function(){var _scriptDir;return ${F.toString()}})();`;N.mainScriptUrlOrBlob=new Blob([H],{type:"text/javascript"})}F(N).then(H=>{e=!1,t=!0,o=H,C()},H=>{e=!1,r=!0,B(H)})})),await Promise.race(I),T)throw new Error(`WebAssembly backend initializing failed due to timeout: ${g}ms`)},n.getInstance=()=>{if(t&&o)return o;throw new Error("WebAssembly is not initialized yet.")},n.dispose=()=>{var c;!t||e||r||(e=!0,(c=o.PThread)===null||c===void 0||c.terminateAllThreads(),o=void 0,e=!1,t=!1,r=!0)}},9710:(y,n,u)=>{u.d(n,{Z:()=>p});var d=u(477),l=u.n(d);function p(){return l()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:y=>{y.exports=function(n,u,d,l){var p=self||window;try{try{var s;try{s=new p.Blob([n])}catch{(s=new(p.BlobBuilder||p.WebKitBlobBuilder||p.MozBlobBuilder||p.MSBlobBuilder)).append(n),s=s.getBlob()}var h=p.URL||p.webkitURL,f=h.createObjectURL(s),a=new p[u](f,d);return h.revokeObjectURL(f),a}catch{return new p[u]("data:application/javascript,".concat(encodeURIComponent(n)),d)}}catch{if(!l)throw Error("Inline worker is not supported");return new p[u](l,d)}}},4154:y=>{y.exports=`"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}}; -`},1670:y=>{y.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(y,n,u)=>{u.r(n),u.d(n,{flatbuffers:()=>d});var d={};d.Offset,d.Table,d.SIZEOF_SHORT=2,d.SIZEOF_INT=4,d.FILE_IDENTIFIER_LENGTH=4,d.SIZE_PREFIX_LENGTH=4,d.Encoding={UTF8_BYTES:1,UTF16_STRING:2},d.int32=new Int32Array(2),d.float32=new Float32Array(d.int32.buffer),d.float64=new Float64Array(d.int32.buffer),d.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,d.Long=function(l,p){this.low=0|l,this.high=0|p},d.Long.create=function(l,p){return l==0&&p==0?d.Long.ZERO:new d.Long(l,p)},d.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},d.Long.prototype.equals=function(l){return this.low==l.low&&this.high==l.high},d.Long.ZERO=new d.Long(0,0),d.Builder=function(l){if(l)p=l;else var p=1024;this.bb=d.ByteBuffer.allocate(p),this.space=p,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},d.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},d.Builder.prototype.forceDefaults=function(l){this.force_defaults=l},d.Builder.prototype.dataBuffer=function(){return this.bb},d.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},d.Builder.prototype.prep=function(l,p){l>this.minalign&&(this.minalign=l);for(var s=1+~(this.bb.capacity()-this.space+p)&l-1;this.space=0&&this.vtable[p]==0;p--);for(var s=p+1;p>=0;p--)this.addInt16(this.vtable[p]!=0?l-this.vtable[p]:0);this.addInt16(l-this.object_start);var h=(s+2)*d.SIZEOF_SHORT;this.addInt16(h);var f=0,a=this.space;e:for(p=0;p=0;a--)this.writeInt8(f.charCodeAt(a))}this.prep(this.minalign,d.SIZEOF_INT+h),this.addOffset(l),h&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},d.Builder.prototype.finishSizePrefixed=function(l,p){this.finish(l,p,!0)},d.Builder.prototype.requiredField=function(l,p){var s=this.bb.capacity()-l,h=s-this.bb.readInt32(s);if(this.bb.readInt16(h+p)==0)throw new Error("FlatBuffers: field "+p+" must be set")},d.Builder.prototype.startVector=function(l,p,s){this.notNested(),this.vector_num_elems=p,this.prep(d.SIZEOF_INT,l*p),this.prep(s,l*p)},d.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},d.Builder.prototype.createString=function(l){if(l instanceof Uint8Array)var p=l;else{p=[];for(var s=0;s=56320?f:(f<<10)+l.charCodeAt(s++)+-56613888)<128?p.push(h):(h<2048?p.push(h>>6&31|192):(h<65536?p.push(h>>12&15|224):p.push(h>>18&7|240,h>>12&63|128),p.push(h>>6&63|128)),p.push(63&h|128))}}this.addInt8(0),this.startVector(1,p.length,1),this.bb.setPosition(this.space-=p.length),s=0;for(var a=this.space,o=this.bb.bytes();s>24},d.ByteBuffer.prototype.readUint8=function(l){return this.bytes_[l]},d.ByteBuffer.prototype.readInt16=function(l){return this.readUint16(l)<<16>>16},d.ByteBuffer.prototype.readUint16=function(l){return this.bytes_[l]|this.bytes_[l+1]<<8},d.ByteBuffer.prototype.readInt32=function(l){return this.bytes_[l]|this.bytes_[l+1]<<8|this.bytes_[l+2]<<16|this.bytes_[l+3]<<24},d.ByteBuffer.prototype.readUint32=function(l){return this.readInt32(l)>>>0},d.ByteBuffer.prototype.readInt64=function(l){return new d.Long(this.readInt32(l),this.readInt32(l+4))},d.ByteBuffer.prototype.readUint64=function(l){return new d.Long(this.readUint32(l),this.readUint32(l+4))},d.ByteBuffer.prototype.readFloat32=function(l){return d.int32[0]=this.readInt32(l),d.float32[0]},d.ByteBuffer.prototype.readFloat64=function(l){return d.int32[d.isLittleEndian?0:1]=this.readInt32(l),d.int32[d.isLittleEndian?1:0]=this.readInt32(l+4),d.float64[0]},d.ByteBuffer.prototype.writeInt8=function(l,p){this.bytes_[l]=p},d.ByteBuffer.prototype.writeUint8=function(l,p){this.bytes_[l]=p},d.ByteBuffer.prototype.writeInt16=function(l,p){this.bytes_[l]=p,this.bytes_[l+1]=p>>8},d.ByteBuffer.prototype.writeUint16=function(l,p){this.bytes_[l]=p,this.bytes_[l+1]=p>>8},d.ByteBuffer.prototype.writeInt32=function(l,p){this.bytes_[l]=p,this.bytes_[l+1]=p>>8,this.bytes_[l+2]=p>>16,this.bytes_[l+3]=p>>24},d.ByteBuffer.prototype.writeUint32=function(l,p){this.bytes_[l]=p,this.bytes_[l+1]=p>>8,this.bytes_[l+2]=p>>16,this.bytes_[l+3]=p>>24},d.ByteBuffer.prototype.writeInt64=function(l,p){this.writeInt32(l,p.low),this.writeInt32(l+4,p.high)},d.ByteBuffer.prototype.writeUint64=function(l,p){this.writeUint32(l,p.low),this.writeUint32(l+4,p.high)},d.ByteBuffer.prototype.writeFloat32=function(l,p){d.float32[0]=p,this.writeInt32(l,d.int32[0])},d.ByteBuffer.prototype.writeFloat64=function(l,p){d.float64[0]=p,this.writeInt32(l,d.int32[d.isLittleEndian?0:1]),this.writeInt32(l+4,d.int32[d.isLittleEndian?1:0])},d.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10),56320+(1023&a)))}return h},d.ByteBuffer.prototype.__indirect=function(l){return l+this.readInt32(l)},d.ByteBuffer.prototype.__vector=function(l){return l+this.readInt32(l)+d.SIZEOF_INT},d.ByteBuffer.prototype.__vector_len=function(l){return this.readInt32(l+this.readInt32(l))},d.ByteBuffer.prototype.__has_identifier=function(l){if(l.length!=d.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+d.FILE_IDENTIFIER_LENGTH);for(var p=0;p{var n=y&&y.__esModule?()=>y.default:()=>y;return __webpack_require__.d(n,{a:n}),n},__webpack_require__.d=(y,n)=>{for(var u in n)__webpack_require__.o(n,u)&&!__webpack_require__.o(y,u)&&Object.defineProperty(y,u,{enumerable:!0,get:n[u]})},__webpack_require__.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),__webpack_require__.o=(y,n)=>Object.prototype.hasOwnProperty.call(y,n),__webpack_require__.r=y=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(y,"__esModule",{value:!0})};var __webpack_exports__=__webpack_require__(6018);return __webpack_exports__})())})(ortWeb_min$1);var ortWeb_minExports=ortWeb_min$1.exports,ortWeb_min=getDefaultExportFromCjs(ortWeb_minExports),ONNX_WEB=_mergeNamespaces({__proto__:null,default:ortWeb_min},[ortWeb_minExports]);let ONNX;const executionProviders=["wasm"];typeof process<"u"&&((tt=process==null?void 0:process.release)==null?void 0:tt.name)==="node"?(ONNX=sharp??ONNX_NODE,executionProviders.unshift("cpu")):(ONNX=ortWeb_min??ONNX_WEB,typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(ONNX.env.wasm.simd=!1));const{env:onnx_env}=ONNX,VERSION="2.5.0",WEB_CACHE_AVAILABLE=typeof self<"u"&&"caches"in self,FS_AVAILABLE=!isEmpty(sharp),PATH_AVAILABLE=!isEmpty(sharp),RUNNING_LOCALLY=FS_AVAILABLE&&PATH_AVAILABLE,__dirname=RUNNING_LOCALLY?sharp.dirname(sharp.dirname(sharp.fileURLToPath(self.location.href))):"./",DEFAULT_CACHE_DIR=RUNNING_LOCALLY?sharp.join(__dirname,"/.cache/"):null,DEFAULT_LOCAL_MODEL_PATH="/models/",localModelPath=RUNNING_LOCALLY?sharp.join(__dirname,DEFAULT_LOCAL_MODEL_PATH):DEFAULT_LOCAL_MODEL_PATH;onnx_env.wasm.wasmPaths=RUNNING_LOCALLY?sharp.join(__dirname,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;const env={backends:{onnx:onnx_env,tfjs:{}},__dirname,version:VERSION,allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!0,localModelPath,useFS:FS_AVAILABLE,useBrowserCache:WEB_CACHE_AVAILABLE,useFSCache:FS_AVAILABLE,cacheDir:DEFAULT_CACHE_DIR,useCustomCache:!1,customCache:null};function isEmpty(y){return Object.keys(y).length===0}globalThis.ReadableStream||(globalThis.ReadableStream=sharp.ReadableStream);class FileResponse{constructor(n){jt(this,"_CONTENT_TYPE_MAP",{txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"});if(this.filePath=n,this.headers=new Headers,this.exists=sharp.existsSync(n),this.exists){this.status=200,this.statusText="OK";let u=sharp.statSync(n);this.headers.set("content-length",u.size.toString()),this.updateContentType();let d=this;this.body=new ReadableStream({start(l){d.arrayBuffer().then(p=>{l.enqueue(new Uint8Array(p)),l.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const n=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[n]??"application/octet-stream")}clone(){let n=new FileResponse(this.filePath);return n.exists=this.exists,n.status=this.status,n.statusText=this.statusText,n.headers=new Headers(this.headers),n}async arrayBuffer(){return(await sharp.promises.readFile(this.filePath)).buffer}async blob(){const n=await sharp.promises.readFile(this.filePath);return new Blob([n],{type:this.headers.get("content-type")})}async text(){return await sharp.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function isValidHttpUrl(y,n=null){let u;try{u=new URL(y)}catch{return!1}return n&&!n.includes(u.hostname)?!1:u.protocol==="http:"||u.protocol==="https:"}async function getFile(y){var n,u,d;if(env.useFS&&!isValidHttpUrl(y))return new FileResponse(y);if(typeof process<"u"&&((n=process==null?void 0:process.release)==null?void 0:n.name)==="node"){const l=!!((u=process.env)!=null&&u.TESTING_REMOTELY),p=env.version,s=new Headers;if(s.set("User-Agent",`transformers.js/${p}; is_ci/${l};`),isValidHttpUrl(y,["huggingface.co","hf.co"])){const f=(d=process.env)==null?void 0:d.HF_ACCESS_TOKEN;f&&s.set("Authorization",`Bearer ${f}`)}return fetch(y,{headers:s})}else return fetch(y)}const ERROR_MAPPING={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function handleError(y,n,u){if(!u)return null;const d=ERROR_MAPPING[y]??`Error (${y}) occurred while trying to load file`;throw Error(`${d}: "${n}".`)}class FileCache{constructor(n){this.path=n}async match(n){let u=sharp.join(this.path,n),d=new FileResponse(u);if(d.exists)return d}async put(n,u){const d=Buffer.from(await u.arrayBuffer());let l=sharp.join(this.path,n);try{await sharp.promises.mkdir(sharp.dirname(l),{recursive:!0}),await sharp.promises.writeFile(l,d)}catch(p){console.warn("An error occurred while writing the file to cache:",p)}}}async function tryCache(y,...n){for(let u of n)try{let d=await y.match(u);if(d)return d}catch{continue}}async function getModelFile(y,n,u=!0,d={}){if(!env.allowLocalModels&&d.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");dispatchCallback(d.progress_callback,{status:"initiate",name:y,file:n});let l;if(!l&&env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{l=await caches.open("transformers-cache")}catch(c){console.warn("An error occurred while opening the browser cache:",c)}}if(!l&&env.useFSCache&&(l=new FileCache(d.cache_dir??env.cacheDir)),!l&&env.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const p=d.revision??"main";let s=pathJoin(y,n),h=pathJoin(env.localModelPath,s),f=pathJoin(env.remoteHost,env.remotePathTemplate.replaceAll("{model}",y).replaceAll("{revision}",p),n),a=p==="main"?s:pathJoin(y,p,n),o,t=l instanceof FileCache?a:f,e,r;if(l&&(r=await tryCache(l,h,t)),r===void 0){if(env.allowLocalModels)if(isValidHttpUrl(s)){if(d.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`)}else try{r=await getFile(h),o=h}catch(g){console.warn(`Unable to load from local path "${h}": "${g}"`)}if(r===void 0||r.status===404){if(d.local_files_only||!env.allowRemoteModels){if(u)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${h}".`);return null}if(r=await getFile(f),r.status!==200)return handleError(r.status,f,u);o=t}l&&r instanceof Response&&r.status===200&&(e=r.clone())}dispatchCallback(d.progress_callback,{status:"download",name:y,file:n});const i=await readResponse(r,c=>{dispatchCallback(d.progress_callback,{status:"progress",...c,name:y,file:n})});return e&&o&&await l.match(o)===void 0&&await l.put(o,e).catch(c=>{console.warn(`Unable to add response to browser cache: ${c}.`)}),dispatchCallback(d.progress_callback,{status:"done",name:y,file:n}),i}async function getModelJSON(y,n,u=!0,d={}){let l=await getModelFile(y,n,u,d);if(l===null)return{};let s=new TextDecoder("utf-8").decode(l);return JSON.parse(s)}async function readResponse(y,n){const u=y.headers.get("Content-Length");u===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let d=parseInt(u??"0"),l=new Uint8Array(d),p=0;const s=y.body.getReader();async function h(){const{done:f,value:a}=await s.read();if(f)return;let o=p+a.length;if(o>d){d=o;let e=new Uint8Array(d);e.set(l),l=e}l.set(a,p),p=o;const t=p/d*100;return n({progress:t,loaded:p,total:d}),h()}return await h(),l}function pathJoin(...y){return y=y.map((n,u)=>(u&&(n=n.replace(new RegExp("^/"),"")),u!==y.length-1&&(n=n.replace(new RegExp("/$"),"")),n)),y.join("/")}function transpose_data(y,n,u){const d=new Array(u.length),l=new Array(u.length);for(let h=u.length-1,f=1;h>=0;--h)l[h]=f,d[h]=n[u[h]],f*=d[h];const p=u.map((h,f)=>l[u.indexOf(f)]),s=new y.constructor(y.length);for(let h=0;h=0;--a)f+=o%n[a]*p[a],o=Math.floor(o/n[a]);s[f]=y[h]}return[s,d]}function softmax(y){const n=max(y)[0],u=y.map(p=>Math.exp(p-n)),d=u.reduce((p,s)=>p+s,0);return u.map(p=>p/d)}function log_softmax(y){return softmax(y).map(d=>Math.log(d))}function getTopItems(y,n=0){return y=Array.from(y).map((u,d)=>[d,u]).sort((u,d)=>d[1]-u[1]),n>0&&(y=y.slice(0,n)),y}function min(y){if(y.length===0)throw Error("Array must not be empty");let n=y[0],u=0;for(let d=1;dn&&(n=y[d],u=d);return[n,u]}function medianFilter(y,n){if(n%2===0||n<=0)throw new Error("Window size must be a positive odd number");const u=new y.constructor(y.length),d=new y.constructor(n),l=Math.floor(n/2);for(let p=0;p=y.length&&(f=2*(y.length-1)-f),d[s++]=y[f]}d.sort(),u[p]=d[l]}return u}function round(y,n){const u=Math.pow(10,n);return Math.round(y*u)/u}const ONNXTensor$1=ONNX.Tensor;class Tensor extends ONNXTensor$1{constructor(...n){return n[0]instanceof ONNX.Tensor?super(n[0].type,n[0].data,n[0].dims):super(...n),new Proxy(this,{get:(u,d)=>{if(typeof d=="string"){let l=Number(d);if(Number.isInteger(l))return u._getitem(l)}return u[d]},set:(u,d,l)=>u[d]=l})}*[Symbol.iterator](){const[n,...u]=this.dims;if(u.length>0){const d=u.reduce((l,p)=>l*p);for(let l=0;l0){const l=d.reduce((p,s)=>p*s);return this._subarray(n,l,d)}else return new Tensor(this.type,[this.data[n]],d)}indexOf(n){for(let u=0;ua[1])throw new Error(`Invalid slice: ${a}`);let o=[Math.max(a[0],0),Math.min(a[1],this.dims[f])];d.push(o),u.push(o[1]-o[0])}else throw new Error(`Invalid slice: ${a}`)}let l=d.map(([f,a])=>a-f),p=l.reduce((f,a)=>f*a),s=new this.data.constructor(p);const h=this.stride();for(let f=0;f=0;--o){const e=l[o];a+=(t%e+d[o][0])*h[o],t=Math.floor(t/e)}s[f]=this.data[a]}return new Tensor(this.type,s,u)}transpose(...n){return transpose(this,n)}sum(n=null,u=!1){return this.norm(1,n,u)}norm(n="fro",u=null,d=!1){if(n==="fro")n=2;else if(typeof n=="string")throw Error(`Unsupported norm: ${n}`);if(u===null){let s=this.data.reduce((h,f)=>h+f**n,0)**(1/n);return new Tensor(this.type,[s],[])}u=safeIndex(u,this.dims.length);const l=this.dims.slice();l[u]=1;const p=new this.data.constructor(this.data.length/this.dims[u]);for(let s=0;s=0;--f){const t=this.dims[f];if(f!==u){const e=a%t;h+=e*o,o*=l[f]}a=Math.floor(a/t)}p[h]+=this.data[s]**n}if(n!==1)for(let s=0;s=0;--s){const a=this.dims[s];if(s!==u){const o=h%a;p+=o*f,f*=this.dims[s]}h=Math.floor(h/a)}this.data[l]/=d.data[p]}return this}normalize(n=2,u=1){return this.clone().normalize_(n,u)}stride(){return dimsToStride(this.dims)}squeeze(n=null){return new Tensor(this.type,this.data,calc_squeeze_dims(this.dims,n))}squeeze_(n=null){return this.dims=calc_squeeze_dims(this.dims,n),this}unsqueeze(n=null){return new Tensor(this.type,this.data,calc_unsqueeze_dims(this.dims,n))}unsqueeze_(n=null){return this.dims=calc_unsqueeze_dims(this.dims,n),this}flatten_(n=0,u=-1){u=(u+this.dims.length)%this.dims.length;let d=this.dims.slice(0,n),l=this.dims.slice(n,u+1),p=this.dims.slice(u+1);return this.dims=[...d,l.reduce((s,h)=>s*h,1),...p],this}flatten(n=0,u=-1){return this.clone().flatten_(n,u)}view(...n){let u=-1;for(let d=0;ds!==u?l*p:l,1);n[u]=this.data.length/d}return new Tensor(this.type,this.data,n)}neg_(){for(let n=0;np*s);if(u!==d)throw Error(`cannot reshape array of size ${u} into shape (${n})`);let l=y;for(let p=n.length-1;p>=0;p--)l=l.reduce((s,h)=>{let f=s[s.length-1];return f.lengthu!==1):typeof n=="number"?y[n]===1&&y.splice(n,1):Array.isArray(n)&&(y=y.filter((u,d)=>u!==1||!n.includes(d))),y}function calc_unsqueeze_dims(y,n){return n=safeIndex(n,y.length+1),y=y.slice(),y.splice(n,0,1),y}function safeIndex(y,n,u=null){if(y<-n||y>=n)throw new Error(`IndexError: index ${y} is out of bounds for dimension${u===null?"":" "+u} with size ${n}`);return y<0&&(y=(y%n+n)%n),y}function cat(y,n=0){n=safeIndex(n,y[0].dims.length);const u=y[0].dims.slice();u[n]=y.reduce((s,h)=>s+h.dims[n],0);const d=u.reduce((s,h)=>s*h,1),l=new y[0].data.constructor(d),p=y[0].type;if(n===0){let s=0;for(let h of y)l.set(h.data,s),s+=h.data.length}else{let s=0;for(let h=0;h=0;--t){const i=f.dims[t];let c=e%i;t===n&&(c+=s),o+=c*r,r*=u[t],e=Math.floor(e/i)}l[o]=f.data[a]}s+=f.dims[n]}}return new Tensor(p,l,u)}function stack(y,n=0){return cat(y.map(u=>u.unsqueeze(n)),n)}function std_mean(y,n=null,u=1,d=!1){if(n===null){const a=y.data.reduce((r,i)=>r+i,0)/y.data.length,o=Math.sqrt(y.data.reduce((r,i)=>r+(i-a)**2,0)/(y.data.length-u)),t=new Tensor(y.type,[a],[]);return[new Tensor(y.type,[o],[]),t]}n=safeIndex(n,y.dims.length);const l=mean(y,n,d),p=y.dims.slice();p[n]=1;const s=new y.data.constructor(y.data.length/y.dims[n]);for(let f=0;f=0;--o){const r=y.dims[o];if(o!==n){const i=t%r;a+=i*e,e*=p[o]}t=Math.floor(t/r)}s[a]+=(y.data[f]-l.data[a])**2}for(let f=0;fs+h,0);return new Tensor(y.type,[p/y.data.length],[])}n=safeIndex(n,y.dims.length);const d=y.dims.slice();d[n]=1;const l=new y.data.constructor(y.data.length/y.dims[n]);for(let p=0;p=0;--h){const o=y.dims[h];if(h!==n){const t=f%o;s+=t*a,a*=d[h]}f=Math.floor(f/o)}l[s]+=y.data[p]}if(y.dims[n]!==1)for(let p=0;p0||h>0;)switch(f.push(s-1),a.push(h-1),p[s][h].item()){case 0:--s,--h;break;case 1:--s;break;case 2:--h;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${h}]. Please file a bug report.`)}return f.reverse(),a.reverse(),[f,a]}function dimsToStride(y){const n=new Array(y.length);for(let u=y.length-1,d=1;u>=0;--u)n[u]=d,d*=y[u];return n}class PriorityQueue{constructor(n=(u,d)=>u>d){this._heap=[],this._comparator=n}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...n){return this.extend(n)}extend(n){for(const u of n)this._heap.push(u),this._siftUp();return this.size}pop(){const n=this.peek(),u=this.size-1;return u>0&&this._swap(0,u),this._heap.pop(),this._siftDown(),n}replace(n){const u=this.peek();return this._heap[0]=n,this._siftDown(),u}_parent(n){return(n+1>>>1)-1}_left(n){return(n<<1)+1}_right(n){return n+1<<1}_greater(n,u){return this._comparator(this._heap[n],this._heap[u])}_swap(n,u){const d=this._heap[n];this._heap[n]=this._heap[u],this._heap[u]=d}_siftUp(){let n=this.size-1;for(;n>0&&this._greater(n,this._parent(n));)this._swap(n,this._parent(n)),n=this._parent(n)}_siftDown(){let n=0;for(;this._left(n)this.tokens_to_ids.get(d)??this.unk_token_id);return this.fuse_unk&&(u=fuse(u,this.unk_token_id)),u}convert_ids_to_tokens(n){return n.map(u=>this.vocab[u]??this.unk_token)}}class WordPieceTokenizer extends TokenizerModel{constructor(n){super(n),this.tokens_to_ids=n.vocab,this.unk_token_id=this.tokens_to_ids.get(n.unk_token),this.unk_token=n.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[u,d]of this.tokens_to_ids)this.vocab[d]=u}encode(n){let u=[];for(let d of n){let l=[...d],p=!1,s=0,h=[];for(;s0&&(o=this.config.continuing_subword_prefix+o),this.tokens_to_ids.has(o)){a=o;break}--f}if(a===null){p=!0;break}h.push(a),s=f}p?u.push(this.unk_token):u.push(...h)}return u}}class Unigram extends TokenizerModel{constructor(n,u){super(n),this.vocab=new Array(n.vocab.size),this.scores=new Array(n.vocab.size);let d=0;n.vocab.forEach((l,p)=>{this.vocab[d]=p,this.scores[d]=l,++d}),this.unk_token_id=n.unk_id,this.unk_token=this.vocab[n.unk_id],this.tokens_to_ids=new Map(this.vocab.map((l,p)=>[l,p])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=u.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=min(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(n){const u=n.sentence,d=u.length;let l=0;for(;l{const y=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},(l,p)=>p+"!".charCodeAt(0)),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},(l,p)=>p+"¡".charCodeAt(0)),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},(l,p)=>p+"®".charCodeAt(0))];let n=y.slice(),u=0;for(let l=0;l<256;++l)y.includes(l)||(y.push(l),n.push(256+u),u+=1);let d=n.map(l=>String.fromCharCode(l));return Object.fromEntries(y.map((l,p)=>[l,d[p]]))})(),UNICODE_TO_BYTES=reverseDictionary(BYTES_TO_UNICODE);class BPE extends TokenizerModel{constructor(n){super(n),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=n.vocab,this.unk_token_id=this.tokens_to_ids.get(n.unk_token),this.unk_token=n.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[u,d]of this.tokens_to_ids)this.vocab[d]=u;this.bpe_ranks=new Map(n.merges.map((u,d)=>[u,d])),this.merges=n.merges.map(u=>u.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=n.end_of_word_suffix,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map,this.fuse_unk??(this.fuse_unk=this.config.fuse_unk)}bpe(n){if(n.length===0)return[];const u=this.cache.get(n);if(u!==void 0)return u;const d=Array.from(n);this.end_of_word_suffix&&(d[d.length-1]+=this.end_of_word_suffix);let l=[];if(d.length>1){const p=new PriorityQueue((f,a)=>f.score`<0x${s.toString(16).toUpperCase().padStart(2,"0")}>`)):u.push(this.unk_token)}return u}}class Normalizer extends Callable{constructor(n){super(),this.config=n}static fromConfig(n){if(n===null)return null;switch(n.type){case"BertNormalizer":return new BertNormalizer(n);case"Precompiled":return new Precompiled(n);case"Sequence":return new NormalizerSequence(n);case"Replace":return new Replace(n);case"NFC":return new NFC(n);case"NFKD":return new NFKD(n);case"StripAccents":return new StripAccents(n);case"Lowercase":return new Lowercase(n);case"Prepend":return new Prepend(n);default:throw new Error(`Unknown Normalizer type: ${n.type}`)}}normalize(n){throw Error("normalize should be implemented in subclass.")}_call(n){return this.normalize(n)}}class Replace extends Normalizer{normalize(n){let u=createPattern(this.config.pattern);return u===null||(n=n.replaceAll(u,this.config.content)),n}}class NFC extends Normalizer{normalize(n){return n=n.normalize("NFC"),n}}class NFKD extends Normalizer{normalize(n){return n=n.normalize("NFKD"),n}}class StripAccents extends Normalizer{normalize(n){return n=n.replace(/[\u0300-\u036f]/g,""),n}}class Lowercase extends Normalizer{normalize(n){return n=n.toLowerCase(),n}}class Prepend extends Normalizer{normalize(n){return n=this.config.prepend+n,n}}class NormalizerSequence extends Normalizer{constructor(n){super(n),this.normalizers=n.normalizers.map(u=>Normalizer.fromConfig(u))}normalize(n){return this.normalizers.reduce((u,d)=>d.normalize(u),n)}}class BertNormalizer extends Normalizer{_tokenize_chinese_chars(n){let u=[];for(let d=0;d=19968&&n<=40959||n>=13312&&n<=19903||n>=131072&&n<=173791||n>=173824&&n<=177983||n>=177984&&n<=178207||n>=178208&&n<=183983||n>=63744&&n<=64255||n>=194560&&n<=195103}stripAccents(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}normalize(n){return this.config.handle_chinese_chars&&(n=this._tokenize_chinese_chars(n)),this.config.lowercase?(n=n.toLowerCase(),this.config.strip_accents!==!1&&(n=this.stripAccents(n))):this.config.strip_accents&&(n=this.stripAccents(n)),n}}class PreTokenizer extends Callable{static fromConfig(n){if(n===null)return null;switch(n.type){case"BertPreTokenizer":return new BertPreTokenizer(n);case"Sequence":return new PreTokenizerSequence(n);case"WhitespaceSplit":return new WhitespaceSplit(n);case"Metaspace":return new MetaspacePreTokenizer(n);case"ByteLevel":return new ByteLevelPreTokenizer(n);case"Split":return new SplitPreTokenizer(n);case"Punctuation":return new PunctuationPreTokenizer(n);case"Digits":return new DigitsPreTokenizer(n);default:throw new Error(`Unknown PreTokenizer type: ${n.type}`)}}pre_tokenize_text(n){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(n){let u=[];return Array.isArray(n)?u=n.map(d=>this.pre_tokenize_text(d)):u=this.pre_tokenize_text(n),u.flat()}_call(n){return this.pre_tokenize(n)}}class BertPreTokenizer extends PreTokenizer{constructor(n){super(),this.pattern=new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`,"gu")}pre_tokenize_text(n){return n.trim().match(this.pattern)||[]}}class ByteLevelPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=BYTES_TO_UNICODE,this.text_encoder=new TextEncoder}pre_tokenize_text(n){return(this.use_regex?n.match(this.pattern)||[]:[n]).map(d=>(this.add_prefix_space&&!d.startsWith(" ")&&(d=" "+d),d=Array.from(this.text_encoder.encode(d),l=>this.byte_encoder[l]).join(""),d))}}class SplitPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n,this.pattern=createPattern(this.config.pattern,this.config.invert)}pre_tokenize_text(n){return this.pattern===null?[]:this.config.invert?n.match(this.pattern)||[]:n.split(this.pattern).filter(u=>u)}}class PunctuationPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n,this.pattern=new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`,"gu")}pre_tokenize_text(n){return n.match(this.pattern)||[]}}class DigitsPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n;const u=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(u,"gu")}pre_tokenize_text(n){return n.match(this.pattern)||[]}}class PostProcessor extends Callable{constructor(n){super(),this.config=n}static fromConfig(n){if(n===null)return null;switch(n.type){case"TemplateProcessing":return new TemplateProcessing(n);case"ByteLevel":return new ByteLevelPostProcessor(n);case"RobertaProcessing":return new RobertaProcessing(n);default:throw new Error(`Unknown PostProcessor type: ${n.type}`)}}post_process(n,...u){throw Error("post_process should be implemented in subclass.")}_call(n,...u){return this.post_process(n,...u)}}class RobertaProcessing extends PostProcessor{constructor(n){super(n),this.cls=n.cls[0],this.sep=n.sep[0]}post_process(n,u=null){return n=mergeArrays([this.cls],n,[this.sep]),u!==null&&(n=mergeArrays(n,[this.sep],u,[this.sep])),n}}class TemplateProcessing extends PostProcessor{constructor(n){super(n),this.single=n.single,this.pair=n.pair}post_process(n,u=null){let d=u===null?this.single:this.pair,l=[];for(let p of d)"SpecialToken"in p?l.push(p.SpecialToken.id):"Sequence"in p&&(p.Sequence.id==="A"?l=mergeArrays(l,n):p.Sequence.id==="B"&&(l=mergeArrays(l,u)));return l}}class ByteLevelPostProcessor extends PostProcessor{post_process(n){return n}}class Decoder extends Callable{constructor(n){super(),this.config=n,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=n.trim_offsets}static fromConfig(n){switch(n.type){case"WordPiece":return new WordPieceDecoder(n);case"Metaspace":return new MetaspaceDecoder(n);case"ByteLevel":return new ByteLevelDecoder(n);case"Replace":return new ReplaceDecoder(n);case"ByteFallback":return new ByteFallback(n);case"Fuse":return new FuseDecoder(n);case"Strip":return new StripDecoder(n);case"Sequence":return new DecoderSequence(n);default:throw new Error(`Unknown Decoder type: ${n.type}`)}}_call(n){return this.decode(n)}decode(n){return this.decode_chain(n).join("")}decode_chain(n){throw Error("`decode_chain` should be implemented in subclass.")}}class ReplaceDecoder extends Decoder{constructor(n){super(n)}decode_chain(n){let u=createPattern(this.config.pattern);return u===null?n:n.map(d=>d.replaceAll(u,this.config.content))}}class ByteFallback extends Decoder{constructor(n){super(n),this.text_decoder=new TextDecoder}decode_chain(n){let u=[],d=[];for(let l of n){let p=null;if(l.length===6&&l.startsWith("<0x")&&l.endsWith(">")){let s=parseInt(l.slice(3,5),16);isNaN(s)||(p=s)}if(p!==null)d.push(p);else{if(d.length>0){let s=this.text_decoder.decode(Uint8Array.from(d));u.push(s),d=[]}u.push(l)}}if(d.length>0){let l=this.text_decoder.decode(Uint8Array.from(d));u.push(l),d=[]}return u}}class FuseDecoder extends Decoder{constructor(n){super(n)}decode_chain(n){return[n.join("")]}}class StripDecoder extends Decoder{constructor(n){super(n),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(n){return n.map(u=>{let d=0;for(let p=0;p(d!==0&&(u.startsWith(this.config.prefix)?u=u.replace(this.config.prefix,""):u=" "+u),this.cleanup&&(u=clean_up_tokenization(u)),u))}}class ByteLevelDecoder extends Decoder{constructor(n){super(n),this.byte_decoder=UNICODE_TO_BYTES,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(n){let u=n.join(""),d=new Uint8Array([...u].map(p=>this.byte_decoder[p]));return this.text_decoder.decode(d)}decode_chain(n){let u=[],d=[];for(let l of n)this.added_tokens.includes(l)?(d.length>0&&(u.push(this.convert_tokens_to_string(d)),d=[]),u.push(l)):d.push(l);return d.length>0&&u.push(this.convert_tokens_to_string(d)),u}}class DecoderSequence extends Decoder{constructor(n){super(n),this.decoders=n.decoders.map(u=>Decoder.fromConfig(u))}decode_chain(n){return this.decoders.reduce((u,d)=>d.decode_chain(u),n)}}class MetaspacePreTokenizer extends PreTokenizer{constructor(n){super(),this.addPrefixSpace=n.add_prefix_space,this.replacement=n.replacement,this.strRep=n.str_rep||this.replacement}pre_tokenize(n){typeof n=="string"&&(n=n.trimStart().split(/\s+/));const u=[];for(let d of n){let l=d.replaceAll(" ",this.strRep);this.addPrefixSpace&&!l.startsWith(this.replacement)&&(l=this.strRep+l),u.push(l)}return u}}class MetaspaceDecoder extends Decoder{constructor(n){super(n),this.addPrefixSpace=n.add_prefix_space,this.replacement=n.replacement}decode_chain(n){let u=[];for(let d=0;dPreTokenizer.fromConfig(u))}pre_tokenize_text(n){return typeof n=="string"&&(n=[n]),this.tokenizers.reduce((u,d)=>d.pre_tokenize(u),n)}}class WhitespaceSplit extends PreTokenizer{constructor(n){super()}pre_tokenize_text(n){return whitespace_split(n)}}class PreTrainedTokenizer extends Callable{constructor(n,u){super(),this.normalizer=Normalizer.fromConfig(n.normalizer),this.pre_tokenizer=PreTokenizer.fromConfig(n.pre_tokenizer),n.model.vocab&&(Array.isArray(n.model.vocab)||(n.model.vocab=Object.entries(n.model.vocab)),n.model.vocab=new Map(n.model.vocab)),this.model=TokenizerModel.fromConfig(n.model,u),this.post_processor=PostProcessor.fromConfig(n.post_processor),this.decoder=Decoder.fromConfig(n.decoder),this.decoder.end_of_word_suffix=this.model.end_of_word_suffix,this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(let d of n.added_tokens){let l=d.id,p=d.content;this.added_tokens.push(p),this.model.tokens_to_ids.set(p,l),this.model.vocab[l]=p,d.special&&(this.special_tokens.push(p),this.all_special_ids.push(l))}this.decoder.added_tokens=this.added_tokens,this.added_tokens_regex=new RegExp("("+this.added_tokens.map(escapeRegExp).join("|")+")"),this.mask_token=this.getToken(u,"mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken(u,"pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken(u,"sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.model_max_length=u.model_max_length,this.remove_space=u.remove_space,this.clean_up_tokenization_spaces=u.clean_up_tokenization_spaces??!0,this.padding_side="right"}getToken(n,...u){for(let d of u){let l=n[d];if(l)if(typeof l=="object"){if(l.__type==="AddedToken")return l.content;throw Error(`Unknown token: ${l}`)}else return l}return null}static async from_pretrained(n,{progress_callback:u=null,config:d=null,cache_dir:l=null,local_files_only:p=!1,revision:s="main"}={}){let h=await loadTokenizer(n,{progress_callback:u,config:d,cache_dir:l,local_files_only:p,revision:s});return new this(...h)}prepare_model_inputs(n){return n}_call(n,{text_pair:u=null,padding:d=!1,truncation:l=null,max_length:p=null,return_tensor:s=!0}={}){let h;if(Array.isArray(n)){if(n.length===0)throw Error("text array must be non-empty");if(u!==null){if(Array.isArray(u)){if(n.length!==u.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");h=n.map((t,e)=>this.encode(t,u[e]))}else h=n.map(t=>this.encode(t))}else{if(n===null)throw Error("text may not be null");if(Array.isArray(u))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");h=[this.encode(n,u)]}let f=max(h.map(t=>t.length))[0];p===null&&(p=f),p=Math.min(p,this.model_max_length);let a=[];if(d||l)for(let t=0;tp)l&&(h[t]=h[t].slice(0,p)),a.push(new Array(h[t].length).fill(1));else if(d){let e=p-h[t].length;this.padding_side==="right"?(a.push(new Array(h[t].length).fill(1).concat(new Array(e).fill(0))),h[t].push(...new Array(e).fill(this.pad_token_id))):(a.push(new Array(e).fill(0).concat(new Array(h[t].length).fill(1))),h[t].unshift(...new Array(e).fill(this.pad_token_id)))}else a.push(new Array(h[t].length).fill(1));else a=h.map(t=>new Array(t.length).fill(1));if(s){if(!(d&&l)&&h.some(e=>e.length!==h[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let t=[h.length,h[0].length];h=new Tensor("int64",BigInt64Array.from(h.flat().map(BigInt)),t),a=new Tensor("int64",BigInt64Array.from(a.flat().map(BigInt)),t)}else Array.isArray(n)||(h=h[0],a=a[0]);let o={input_ids:h,attention_mask:a};return o=this.prepare_model_inputs(o),o}_encode_text(n){return n===null?null:n.split(this.added_tokens_regex).filter(l=>l).map(l=>{if(this.added_tokens.includes(l))return l;{this.remove_space===!0&&(l=l.trim().split(/\s+/).join(" ")),this.normalizer!==null&&(l=this.normalizer(l));let p=this.pre_tokenizer!==null?this.pre_tokenizer(l):[l];return this.model(p)}}).flat()}encode(n,u=null){let d=this._encode_text(n),l=this._encode_text(u),p=this.post_processor!==null?this.post_processor(d,l):mergeArrays(d??[],l??[]);return this.model.convert_tokens_to_ids(p)}batch_decode(n,u={}){return n.map(d=>this.decode(d,u))}decode(n,u={}){if(!Array.isArray(n)||n.length===0||!isIntegralNumber(n[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(n,u)}decode_single(n,{skip_special_tokens:u=!1,clean_up_tokenization_spaces:d=null}){let l=this.model.convert_ids_to_tokens(n);u&&(l=l.filter(s=>!this.special_tokens.includes(s)));let p=this.decoder(l);return this.decoder.end_of_word_suffix&&(p=p.replaceAll(this.decoder.end_of_word_suffix," "),u&&(p=p.trim())),(d??this.clean_up_tokenization_spaces)&&(p=clean_up_tokenization(p)),p}}function add_token_types(y){if(y.input_ids instanceof Tensor)y.token_type_ids=new Tensor("int64",new BigInt64Array(y.input_ids.data.length),y.input_ids.dims);else if(Array.isArray(y.input_ids))Array.isArray(y.input_ids[0])?y.token_type_ids=y.input_ids.map(n=>new Array(n.length).fill(0)):y.token_type_ids=new Array(y.input_ids.length).fill(0);else throw new Error("Input ids must be a Tensor or an Array");return y}class BertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class AlbertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class MobileBertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class SqueezeBertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class DistilBertTokenizer extends PreTrainedTokenizer{}class T5Tokenizer extends PreTrainedTokenizer{}class GPT2Tokenizer extends PreTrainedTokenizer{}class BartTokenizer extends PreTrainedTokenizer{}class RobertaTokenizer extends PreTrainedTokenizer{}class BloomTokenizer extends PreTrainedTokenizer{}class LlamaTokenizer extends PreTrainedTokenizer{}class XLMRobertaTokenizer extends PreTrainedTokenizer{}class MPNetTokenizer extends PreTrainedTokenizer{}class FalconTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return add_token_types(n)}}class GPTNeoXTokenizer extends PreTrainedTokenizer{}class NllbTokenizer extends PreTrainedTokenizer{constructor(n,u){super(n,u),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(d=>this.languageRegex.test(d))}_build_translation_inputs(n,u,d){if(!this.language_codes.includes(d.tgt_lang))throw new Error(`Target language code "${d.tgt_lang}" is not valid. Must be one of: {${this.language_codes.join(", ")}}`);if(d.src_lang!==void 0){if(!this.language_codes.includes(d.src_lang))throw new Error(`Source language code "${d.src_lang}" is not valid. Must be one of: {${this.language_codes.join(", ")}}`);for(let l of this.post_processor.config.single)if("SpecialToken"in l&&this.languageRegex.test(l.SpecialToken.id)){l.SpecialToken.id=d.src_lang;break}}return d.forced_bos_token_id=this.model.convert_tokens_to_ids([d.tgt_lang])[0],this._call(n,u)}}const WHISPER_LANGUAGES=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],WHISPER_LANGUAGE_MAPPING=new Map(WHISPER_LANGUAGES),WHISPER_TO_LANGUAGE_CODE_MAPPING=new Map([...WHISPER_LANGUAGES.map(([y,n])=>[n,y]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);class WhisperTokenizer extends PreTrainedTokenizer{_decode_asr(n,{return_timestamps:u=!1,return_language:d=!1,time_precision:l=null,force_full_sequences:p=!0}={}){if(l===null)throw Error("Must specify time_precision");let s=null;const h=u==="word";function f(){return{language:s,timestamp:[null,null],text:""}}const a=[];let o=f(),t=0;const e=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let r=[],i=[],c=!1,g=null;const m=new Set(this.all_special_ids);for(let w of n){const v=w.tokens,S=h?w.token_timestamps:null;let O=null,E=e;if("stride"in w){const[C,B,F]=w.stride;if(t-=B,g=C-F,B&&(E=B/l+e),F)for(let N=v.length-1;N>=0;--N){const H=v[N];if(H>=e){if(O!==null&&(H-e)*l=e){const F=(B-e)*l+t,N=round(F,2);if(O!==null&&B>=O)c=!0;else if(c||r.length>0&&B0?(r.push(T),h&&i.push(I)):r.every(C=>C.length===0)&&(o=f(),r=[],T=[],i=[],I=[])}if(r.length>0){if(p&&u)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[w,v]=this.findLongestCommonSequence(r,i),S=this.decode(w);o.text=S,h&&(o.words=this.collateWordTimestamps(w,v,s)),a.push(o)}let b=Object.create(null);const _=a.map(w=>w.text).join("");if(u||d){for(let w=0;w0;let h=s?[]:null,f=s?u[0]:null;for(let a=1;aN===C[H]).length,F=B/w+v;B>1&&F>t&&(t=F,e=[S,O,T,I])}const[i,c,g,m]=e,b=Math.floor((c+i)/2),_=Math.floor((m+g)/2);p.push(...d.slice(0,b)),d=o.slice(_),l=d.length,s&&(h.push(...f.slice(0,b)),f=u[a].slice(_))}return p.push(...d),s?(h.push(...f),[p,h]):[p,[]]}collateWordTimestamps(n,u,d){let[l,p,s]=this.combineTokensIntoWords(n,d),h=[];for(let f=0;f=l){let h=(s-l)*d;h=round(h,2),p.push(`<|${h}|>`),p.push([])}else p[p.length-1].push(s);return p=p.map(s=>typeof s=="string"?s:super.decode(s,u)),p.join("")}splitTokensOnUnicode(n){const u=this.decode(n,{decode_with_timestamps:!0}),d="�";let l=[],p=[],s=[],h=[],f=[],a=0;for(let o=0;o=this.model.tokens_to_ids.get("<|endoftext|>"),i=o.startsWith(" "),c=o.trim(),g=f.test(c);if(r||i||g||p.length===0)p.push(o),s.push(t),h.push(e);else{const m=p.length-1;p[m]+=o,s[m].push(...t),h[m].push(...e)}}return[p,s,h]}mergePunctuations(n,u,d,l,p){let s=structuredClone(n),h=structuredClone(u),f=structuredClone(d),a=s.length-2,o=s.length-1;for(;a>=0;)s[a].startsWith(" ")&&l.includes(s[a].trim())?(s[o]=s[a]+s[o],h[o]=mergeArrays(h[a],h[o]),f[o]=mergeArrays(f[a],f[o]),s[a]="",h[a]=[],f[a]=[]):o=a,--a;for(a=0,o=1;ot),h.filter(t=>t.length>0),f.filter(t=>t.length>0)]}get_decoder_prompt_ids({language:n=null,task:u=null,no_timestamps:d=!0}={}){let l=[];if(n){n=n.toLowerCase();let p=WHISPER_TO_LANGUAGE_CODE_MAPPING.get(n);if(p===void 0)if(WHISPER_LANGUAGE_MAPPING.has(n))p=n;else{const f=n.length===2?WHISPER_LANGUAGE_MAPPING.keys():WHISPER_LANGUAGE_MAPPING.values();throw new Error(`Language "${n}" is not supported. Must be one of: ${JSON.stringify(f)}`)}let s=this.model.tokens_to_ids.get(`<|${p}|>`);if(s===void 0)throw new Error(`Unable to find language "${p}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);l.push(s)}else l.push(null);if(u){if(u=u.toLowerCase(),u!=="transcribe"&&u!=="translate")throw new Error(`Task "${u}" is not supported. Must be one of: ["transcribe", "translate"]`);let p=this.model.tokens_to_ids.get(`<|${u}|>`);if(p===void 0)throw new Error(`Unable to find task "${u}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);l.push(p)}else l.push(null);if(d){let p=this.model.tokens_to_ids.get("<|notimestamps|>");if(p===void 0)throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');l.push(p)}return l.map((p,s)=>[s+1,p]).filter(p=>p[1]!==null)}}class CodeGenTokenizer extends PreTrainedTokenizer{}class CLIPTokenizer extends PreTrainedTokenizer{}class MarianTokenizer extends PreTrainedTokenizer{constructor(n,u){super(n,u),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(d=>this.languageRegex.test(d)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(n){if(n===null)return null;let[u,...d]=n.trim().split(this.languageRegex);if(d.length===0)return super._encode_text(u);if(d.length===2){let[l,p]=d;return this.supported_language_codes.includes(l)||console.warn(`Unsupported language code "${l}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),mergeArrays([l],super._encode_text(p))}}}class CharTrie{constructor(){this.root=CharTrieNode.default()}extend(n){for(let u of n)this.push(u)}push(n){let u=this.root;for(let d of n){let l=u.children.get(d);l===void 0&&(l=CharTrieNode.default(),u.children.set(d,l)),u=l}u.isLeaf=!0}*commonPrefixSearch(n){let u=this.root,d="";for(let l=0;lf)&&(a=o.clone(),f=t)}if(a!==null)h.prev=a,h.backtraceScore=f;else return[]}++u}const d=[],p=this.beginNodes[n][0].prev;if(p===null)return[];let s=p.clone();for(;s.prev!==null;)d.push(s.clone()),s=s.clone().prev.clone();return d.reverse(),d}piece(n){return this.sentence.slice(n.pos,n.pos+n.length)}tokens(){return this.viterbi().map(u=>this.piece(u))}tokenIds(){return this.viterbi().map(u=>u.tokenId)}}class TokenLatticeNode{constructor(n,u,d,l,p){this.tokenId=n,this.nodeId=u,this.pos=d,this.length=l,this.score=p,this.prev=null,this.backtraceScore=0}clone(){const n=new TokenLatticeNode(this.tokenId,this.nodeId,this.pos,this.length,this.score);return n.prev=this.prev,n.backtraceScore=this.backtraceScore,n}}class AutoTokenizer{static async from_pretrained(n,{quantized:u=!0,progress_callback:d=null,config:l=null,cache_dir:p=null,local_files_only:s=!1,revision:h="main"}={}){let[f,a]=await loadTokenizer(n,{quantized:u,progress_callback:d,config:l,cache_dir:p,local_files_only:s,revision:h}),o=a.tokenizer_class.replace(/Fast$/,""),t=this.TOKENIZER_CLASS_MAPPING[o];return t||(console.warn(`Unknown tokenizer class "${o}", attempting to construct from base class.`),t=PreTrainedTokenizer),new t(f,a)}}jt(AutoTokenizer,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer,DistilBertTokenizer,BertTokenizer,MobileBertTokenizer,SqueezeBertTokenizer,AlbertTokenizer,GPT2Tokenizer,BartTokenizer,RobertaTokenizer,WhisperTokenizer,CodeGenTokenizer,CLIPTokenizer,MarianTokenizer,BloomTokenizer,NllbTokenizer,LlamaTokenizer,XLMRobertaTokenizer,MPNetTokenizer,FalconTokenizer,GPTNeoXTokenizer,PreTrainedTokenizer});async function loadConfig(y,n){return await getModelJSON(y,"config.json",!0,n)}class PretrainedConfig{constructor(n){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,n)}static async from_pretrained(n,{progress_callback:u=null,config:d=null,cache_dir:l=null,local_files_only:p=!1,revision:s="main"}={}){let h=d??await loadConfig(n,{progress_callback:u,config:d,cache_dir:l,local_files_only:p,revision:s});return new this(h)}}class AutoConfig{static async from_pretrained(...n){return PretrainedConfig.from_pretrained(...n)}}class LogitsProcessorList extends Callable{constructor(){super(),this.processors=[]}push(n){this.processors.push(n)}extend(n){this.processors.push(...n)}_call(n,u){for(let d of u)this.processors.forEach(l=>l(n,d))}[Symbol.iterator](){return this.processors.values()}}class LogitsProcessor extends Callable{_call(n,u){throw Error("`_call` should be implemented in a subclass")}}class ForceTokensLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.force_token_map=Object.fromEntries(n??[])}_call(n,u){let d=this.force_token_map[n.length];return exists(d)&&(u.data.fill(-1/0),u.data[d]=0),u}}class ForcedBOSTokenLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.bos_token_id=n}_call(n,u){return n.length===1&&(u.data.fill(-1/0),u.data[this.bos_token_id]=0),u}}class ForcedEOSTokenLogitsProcessor extends LogitsProcessor{constructor(n,u){super(),this.max_length=n,this.forced_eos_token_id=u}_call(n,u){}}class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor{constructor(n,u){super(),this.begin_suppress_tokens=n,this.begin_index=u}_call(n,u){if(n.length===this.begin_index)for(let d of this.begin_suppress_tokens)u.data[d]=-1/0;return u}}class WhisperTimeStampLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.eos_token_id=n.eos_token_id,this.no_timestamps_token_id=n.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(n.forced_decoder_ids||[]).length+2,n.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=n.max_initial_timestamp_index}_call(n,u){if(u.data[this.no_timestamps_token_id]=-1/0,n.length===this.begin_index-1)return u.data.fill(-1/0),u.data[this.timestamp_begin]=0,u;const d=n.slice(this.begin_index),l=d.length>=1&&d[d.length-1]>=this.timestamp_begin,p=d.length<2||d[d.length-2]>=this.timestamp_begin;if(l&&(p?u.data.subarray(this.timestamp_begin).fill(-1/0):u.data.subarray(0,this.eos_token_id).fill(-1/0)),n.length===this.begin_index&&this.max_initial_timestamp_index!==null){const a=this.timestamp_begin+this.max_initial_timestamp_index;u.data.subarray(a+1).fill(-1/0)}const s=log_softmax(u.data),h=Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((a,o)=>a+o)),f=max(s.subarray(0,this.timestamp_begin))[0];return h>f&&u.data.subarray(0,this.timestamp_begin).fill(-1/0),u}}class NoRepeatNGramLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.no_repeat_ngram_size=n}getNgrams(n){const u=n.length,d=[];for(let p=0;p0&&(l=l.map(p=>p/this.generation_config.temperature)),l}randomSelect(n){let u=n.reduce((l,p)=>l+p,0),d=Math.random()*u;for(let l=0;l1)return new BeamSearchSampler(n);if(n.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${n.num_return_sequences}.`);return new GreedySampler(n)}}class GreedySampler extends Sampler{sample(n,u=-1){let d=this.getLogits(n,u);return[[max(d)[1],0]]}}class MultinomialSampler extends Sampler{sample(n,u=-1){let d=n.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const l=this.getLogits(n,u),p=getTopItems(l,d),s=softmax(p.map(h=>h[1]));return Array.from({length:this.generation_config.num_beams},()=>{const h=this.randomSelect(s);return[p[h][0],Math.log(s[h])]})}}class BeamSearchSampler extends Sampler{sample(n,u=-1){let d=n.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const l=this.getLogits(n,u),p=getTopItems(l,d),s=softmax(p.map(h=>h[1]));return Array.from({length:this.generation_config.num_beams},(h,f)=>[p[f][0],Math.log(s[f])])}}const{InferenceSession,Tensor:ONNXTensor}=ONNX;class ModelType{}class EncoderOnlyModelType extends ModelType{}class EncoderDecoderModelType extends ModelType{}class Seq2SeqModelType extends EncoderDecoderModelType{}class DecoderOnlyModelType extends ModelType{}const MODEL_TYPE_MAPPING=new Map([["CLIPTextModelWithProjection",EncoderOnlyModelType],["CLIPVisionModelWithProjection",EncoderOnlyModelType]]);async function forward(y,n){return MODEL_TYPE_MAPPING.get(y.constructor.name)===DecoderOnlyModelType?await decoderForward(y,n):await encoderForward(y,n)}async function constructSession(y,n,u){let d=`onnx/${n}${u.quantized?"_quantized":""}.onnx`,l=await getModelFile(y,d,!0,u);try{return await InferenceSession.create(l,{executionProviders})}catch(p){if(executionProviders.length===1&&executionProviders[0]==="wasm")throw p;return console.warn(p),console.warn("Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. "),await InferenceSession.create(l,{executionProviders:["wasm"]})}}async function validateInputs(y,n){const u={},d=[];for(let s of y.inputNames)n[s]===void 0?d.push(s):u[s]=n[s];if(d.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${d.join(", ")}.`);const l=Object.keys(n).length,p=y.inputNames.length;if(l>p){let s=Object.keys(n).filter(h=>!y.inputNames.includes(h));console.warn(`WARNING: Too many inputs were provided (${l} > ${p}). The following inputs will be ignored: "${s.join(", ")}".`)}return u}async function sessionRun(y,n){const u=await validateInputs(y,n);try{let d=await y.run(u);return d=replaceTensors(d),d}catch(d){throw console.error(`An error occurred during model execution: "${d}".`),console.error("Inputs given to model:",u),d}}function replaceTensors(y){for(let n in y)y[n]instanceof ONNXTensor?y[n]=new Tensor(y[n]):typeof y[n]=="object"&&replaceTensors(y[n]);return y}function toI64Tensor(y){if(y instanceof Tensor)return y;if(y.length===0)throw Error("items must be non-empty");if(Array.isArray(y[0])){if(y.some(n=>n.length!==y[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new Tensor("int64",BigInt64Array.from(y.flat().map(n=>BigInt(n))),[y.length,y[0].length])}else return new Tensor("int64",BigInt64Array.from(y.map(n=>BigInt(n))),[1,y.length])}function prepareAttentionMask(y,n){let u=y.config.pad_token_id??null,d=y.config.eos_token_id??null;isIntegralNumber(d)&&(d=[d]);let l=n.indexOf(u)!==-1,p=d===null||!d.includes(u);if(l&&p){let s=BigInt64Array.from(n.data.map(h=>h!=u));return new Tensor("int64",s,n.dims)}else return new Tensor("int64",new BigInt64Array(n.data.length).fill(1n),n.dims)}function boolTensor(y){return new Tensor("bool",[y],[1])}async function seq2seqForward(y,n,{add_decoder_pkv:u=!0}={}){let{encoder_outputs:d,past_key_values:l}=n;d||(d=(await encoderForward(y,n)).last_hidden_state);let p={input_ids:n.decoder_input_ids,encoder_hidden_states:d,use_cache_branch:boolTensor(!!l)};y.decoder_merged_session.inputNames.includes("encoder_attention_mask")&&(p.encoder_attention_mask=n.attention_mask),y.addPastKeyValues(p,l,u);const s=await sessionRun(y.decoder_merged_session,p);let h=s.logits;l=y.getPastKeyValues(s,l);const f=y.getAttentions(s);return new Seq2SeqLMOutput({logits:h,past_key_values:l,encoder_outputs:d,...f})}function seq2seqStartBeams(y,n,u,d=!0){let l=[],p=0,s=y.config.decoder_start_token_id;Array.isArray(s)||(s=[s]);for(let h of n){h.dims=[1,...h.dims];let f={inputs:h,encoder_outputs:null,prev_model_outputs:null,output_token_ids:s,done:!1,score:0,id:p++};d&&(f.attention_mask=prepareAttentionMask(y,h)),l.push(f)}return l}async function seq2seqRunBeam(y,n,{input_name:u="input_ids"}={}){var p;let d={[u]:n.inputs,decoder_input_ids:toI64Tensor(n.output_token_ids.slice(-1)),encoder_outputs:n.encoder_outputs,past_key_values:(p=n.prev_model_outputs)==null?void 0:p.past_key_values};n.attention_mask&&(d.attention_mask=n.attention_mask);let l=await y.forward(d);return n.prev_model_outputs=l,n.encoder_outputs=l.encoder_outputs,l}async function encoderForward(y,n){let u={};for(let d of y.session.inputNames)u[d]=n[d];return await sessionRun(y.session,u)}async function decoderForward(y,n){let{input_ids:u,past_key_values:d,attention_mask:l}=n,p={input_ids:u,attention_mask:l??prepareAttentionMask(y,u),use_cache_branch:boolTensor(d!==null)};y.addPastKeyValues(p,d);let s=await sessionRun(y.session,p),h=s.logits;return d=y.getPastKeyValues(s,d),{logits:h,past_key_values:d}}function decoderStartBeams(y,n,u,d){let l=[],p=0;for(let s of n){let h=s.tolist().map(Number);s.dims=[1,...s.dims];let f;d?(f=d[p],f.dims=[1,...f.dims]):f=prepareAttentionMask(y,s);let a={input:s,model_input_ids:s,attention_mask:f,prev_model_outputs:null,output_token_ids:h,num_output_tokens:u,done:!1,score:0,id:p++};l.push(a)}return l}async function decoderRunBeam(y,n){var p;let u=new BigInt64Array(n.output_token_ids.length).fill(1n),d={input_ids:n.model_input_ids,attention_mask:new Tensor("int64",u,[1,u.length]),past_key_values:(p=n.prev_model_outputs)==null?void 0:p.past_key_values},l=await y.forward(d);return n.prev_model_outputs=l,l}function decoderUpdatebeam(y,n){y.output_token_ids=[...y.output_token_ids,n],y.model_input_ids=new Tensor("int64",[BigInt(n)],[1,1])}class PreTrainedModel extends Callable{constructor(n,u){super(),this.config=n,this.session=u}async dispose(){let n=[];for(let u of Object.keys(this)){let d=this[u];d instanceof InferenceSession&&n.push(d.handler.dispose())}return await Promise.all(n)}static async from_pretrained(n,{quantized:u=!0,progress_callback:d=null,config:l=null,cache_dir:p=null,local_files_only:s=!1,revision:h="main",model_file_name:f=null}={}){let a={quantized:u,progress_callback:d,config:l,cache_dir:p,local_files_only:s,revision:h,model_file_name:f},o=MODEL_TYPE_MAPPING.get(this.name),t;if(o===DecoderOnlyModelType)t=await Promise.all([AutoConfig.from_pretrained(n,a),constructSession(n,a.model_file_name??"decoder_model_merged",a)]);else if(o===Seq2SeqModelType)t=await Promise.all([AutoConfig.from_pretrained(n,a),constructSession(n,"encoder_model",a),constructSession(n,"decoder_model_merged",a),getModelJSON(n,"generation_config.json",!1,a)]);else if(o===EncoderDecoderModelType)t=await Promise.all([AutoConfig.from_pretrained(n,a),constructSession(n,"encoder_model",a),constructSession(n,"decoder_model_merged",a)]);else if(o===EncoderOnlyModelType)t=await Promise.all([AutoConfig.from_pretrained(n,a),constructSession(n,a.model_file_name??"model",a)]);else throw console.warn("Malformed class definition.",this),Error(`Unable to load model: ${n}. Please report this bug at https://github.com/xenova/transformers.js/issues/new/choose.`);return new this(...t)}async _call(n){return await this.forward(n)}async forward(n){return await forward(this,n)}_get_logits_processor(n,u,d=null){const l=new LogitsProcessorList;if(n.repetition_penalty!==null&&n.repetition_penalty!==1&&l.push(new RepetitionPenaltyLogitsProcessor(n.repetition_penalty)),n.no_repeat_ngram_size!==null&&n.no_repeat_ngram_size>0&&l.push(new NoRepeatNGramLogitsProcessor(n.no_repeat_ngram_size)),n.forced_bos_token_id!==null&&l.push(new ForcedBOSTokenLogitsProcessor(n.forced_bos_token_id)),n.forced_eos_token_id!==null&&l.push(new ForcedEOSTokenLogitsProcessor(n.max_length,n.forced_eos_token_id)),n.begin_suppress_tokens!==null){let p=u>1||n.forced_bos_token_id===null?u:u+1;n.forced_decoder_ids!==null&&(p+=n.forced_decoder_ids[n.forced_decoder_ids.length-1][0]),l.push(new SuppressTokensAtBeginLogitsProcessor(n.begin_suppress_tokens,p))}return n.forced_decoder_ids!==null&&l.push(new ForceTokensLogitsProcessor(n.forced_decoder_ids)),d!==null&&l.extend(d),l}_get_generation_config(n){let u=new GenerationConfig;return"generation_config"in this&&Object.assign(u,this.generation_config),n!==null&&Object.assign(u,n),u}async generate(n,u=null,d=null,{inputs_attention_mask:l=null}={}){if(!(n instanceof Tensor)&&!isTypedArray(n)&&!Array.isArray(n))throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${n.constructor.name}".`);let p;if(this.config.is_encoder_decoder)p=0;else if(p=n instanceof Tensor?n.dims[0]:n.length,p===0)throw Error("Must supply a non-empty array of input token ids.");u=this._get_generation_config(u),d=d??new LogitsProcessorList,d=this._get_logits_processor(u,p,d);let s=1;const h=s+(u.max_new_tokens??1/0),f=Number.isInteger(u.max_length)&&(u.max_new_tokens??null)===null;let a=Sampler.getSampler(u),o=this.getStartBeams(n,s,l);for(;o.some(i=>!i.done)&&s=u.max_length){c.done=!0,i.push(c);continue}let g=await this.runBeam(c);u.output_attentions&&this.addAttentionsToBeam(c,g),u.output_scores;let m=g.logits.slice(null,-1,null);d(c.output_token_ids,m);let b=a(m);for(let[_,w]of b){let v={...c};this.updateBeam(v,_),v.score+=w,_===this.config.eos_token_id&&(v.done=!0),i.push(v)}}++s,i=this.groupBeams(i).map(c=>c.sort((g,m)=>m.score-g.score).slice(0,u.num_beams)),o=i.flat(),u.callback_function&&u.callback_function(o)}const t=this.groupBeams(o),e=i=>t.map(c=>u.num_return_sequences>1?c.slice(0,u.num_return_sequences).map(g=>g[i]):[c[0][i]]).flat(),r=e("output_token_ids");if(u.return_dict_in_generate){const i=e("decoder_attentions"),c=e("cross_attentions");return{sequences:r,decoder_attentions:i,cross_attentions:c}}else return r}addAttentionsToBeam(n,u){if(this.config.is_encoder_decoder){if(!u.cross_attentions||u.cross_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`.");n.cross_attentions||(n.cross_attentions=[]),n.cross_attentions.push(u.cross_attentions)}if(!u.decoder_attentions||u.decoder_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`.");n.decoder_attentions||(n.decoder_attentions=[]),n.decoder_attentions.push(u.decoder_attentions)}groupBeams(n){const u=Object.create(null);for(const d of n)u[d.id]===void 0?u[d.id]=[d]:u[d.id].push(d);return Object.values(u)}getPastKeyValues(n,u){const d=Object.create(null);for(const l in n)if(l.startsWith("present")){let p=l.replace("present","past_key_values");u&&l.includes("encoder")?d[p]=u[p]:d[p]=n[l]}return d}getAttentions(n){const u=Object.create(null);for(const d of["cross_attentions","decoder_attentions"]){const l=[];for(const p in n)if(p.startsWith(d)){const s=p.split(".").pop();l[s]=n[p]}u[d]=l}return u}addPastKeyValues(n,u,d=!1){if(u)Object.assign(n,u);else if(d){let l=[1,this.num_encoder_heads,0,this.encoder_dim_kv];for(let s=0;s{let a=Array.from({length:this.config.decoder_layers},(c,g)=>cat(f.map(m=>m[g]),2)),o=stack(u.map(([c,g])=>a[c].slice(null,g)));o=o.transpose(1,0,2,3);let[t,e]=std_mean(o,-2,0,!0),r=o.clone();for(let c=0;co[g+1]-o[g]),r=mergeArrays([1],e).map(c=>!!c),i=[];for(let c=0;c{let n=TOKENIZER_MAPPINGS.get(y.data.model_id);n||(n=AutoTokenizer.from_pretrained(y.data.model_id),TOKENIZER_MAPPINGS.set(y.data.model_id,new Promise(a=>{n.then(o=>{switch(o.constructor.name){case"LlamaTokenizer":o.decoder.decoders.pop();break;case"T5Tokenizer":o.decoder.addPrefixSpace=!1;break}a(o)})})));const u=await n,d=y.data.text,l=performance.now(),p=u.encode(d),s=performance.now();console.log("[INFO]",`Tokenized ${d.length} characters in ${(s-l).toFixed(2)}ms`);let h=p.map(a=>u.decode([a])),f=[];switch(u.constructor.name){case"BertTokenizer":f=h.map((a,o)=>o===0||a.startsWith("##")?0:8),h=h.map(a=>a.replace("##",""));break;case"T5Tokenizer":h.length>0&&h.length!==" "&&(h[0]=h[0].replace(/^ /,""));break}self.postMessage({token_ids:p,decoded:h,margins:f})})})(); diff --git a/spaces/XzJosh/Taffy-Bert-VITS2/losses.py b/spaces/XzJosh/Taffy-Bert-VITS2/losses.py deleted file mode 100644 index fb22a0e834dd87edaa37bb8190eee2c3c7abe0d5..0000000000000000000000000000000000000000 --- a/spaces/XzJosh/Taffy-Bert-VITS2/losses.py +++ /dev/null @@ -1,61 +0,0 @@ -import torch -from torch.nn import functional as F - -import commons - - -def feature_loss(fmap_r, fmap_g): - loss = 0 - for dr, dg in zip(fmap_r, fmap_g): - for rl, gl in zip(dr, dg): - rl = rl.float().detach() - gl = gl.float() - loss += torch.mean(torch.abs(rl - gl)) - - return loss * 2 - - -def discriminator_loss(disc_real_outputs, disc_generated_outputs): - loss = 0 - r_losses = [] - g_losses = [] - for dr, dg in zip(disc_real_outputs, disc_generated_outputs): - dr = dr.float() - dg = dg.float() - r_loss = torch.mean((1-dr)**2) - g_loss = torch.mean(dg**2) - loss += (r_loss + g_loss) - r_losses.append(r_loss.item()) - g_losses.append(g_loss.item()) - - return loss, r_losses, g_losses - - -def generator_loss(disc_outputs): - loss = 0 - gen_losses = [] - for dg in disc_outputs: - dg = dg.float() - l = torch.mean((1-dg)**2) - gen_losses.append(l) - loss += l - - return loss, gen_losses - - -def kl_loss(z_p, logs_q, m_p, logs_p, z_mask): - """ - z_p, logs_q: [b, h, t_t] - m_p, logs_p: [b, h, t_t] - """ - z_p = z_p.float() - logs_q = logs_q.float() - m_p = m_p.float() - logs_p = logs_p.float() - z_mask = z_mask.float() - - kl = logs_p - logs_q - 0.5 - kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p) - kl = torch.sum(kl * z_mask) - l = kl / torch.sum(z_mask) - return l diff --git a/spaces/XzJosh/TianDou-Bert-VITS2/models.py b/spaces/XzJosh/TianDou-Bert-VITS2/models.py deleted file mode 100644 index d4afe44d883691610c5903e602a3ca245fcb3a5c..0000000000000000000000000000000000000000 --- a/spaces/XzJosh/TianDou-Bert-VITS2/models.py +++ /dev/null @@ -1,707 +0,0 @@ -import copy -import math -import torch -from torch import nn -from torch.nn import functional as F - -import commons -import modules -import attentions -import monotonic_align - -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm - -from commons import init_weights, get_padding -from text import symbols, num_tones, num_languages -class DurationDiscriminator(nn.Module): #vits2 - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0): - super().__init__() - - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - - self.drop = nn.Dropout(p_dropout) - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_1 = modules.LayerNorm(filter_channels) - self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.norm_2 = modules.LayerNorm(filter_channels) - self.dur_proj = nn.Conv1d(1, filter_channels, 1) - - self.pre_out_conv_1 = nn.Conv1d(2*filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.pre_out_norm_1 = modules.LayerNorm(filter_channels) - self.pre_out_conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2) - self.pre_out_norm_2 = modules.LayerNorm(filter_channels) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, in_channels, 1) - - self.output_layer = nn.Sequential( - nn.Linear(filter_channels, 1), - nn.Sigmoid() - ) - - def forward_probability(self, x, x_mask, dur, g=None): - dur = self.dur_proj(dur) - x = torch.cat([x, dur], dim=1) - x = self.pre_out_conv_1(x * x_mask) - x = torch.relu(x) - x = self.pre_out_norm_1(x) - x = self.drop(x) - x = self.pre_out_conv_2(x * x_mask) - x = torch.relu(x) - x = self.pre_out_norm_2(x) - x = self.drop(x) - x = x * x_mask - x = x.transpose(1, 2) - output_prob = self.output_layer(x) - return output_prob - - def forward(self, x, x_mask, dur_r, dur_hat, g=None): - x = torch.detach(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.conv_1(x * x_mask) - x = torch.relu(x) - x = self.norm_1(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - x = torch.relu(x) - x = self.norm_2(x) - x = self.drop(x) - - output_probs = [] - for dur in [dur_r, dur_hat]: - output_prob = self.forward_probability(x, x_mask, dur, g) - output_probs.append(output_prob) - - return output_probs - -class TransformerCouplingBlock(nn.Module): - def __init__(self, - channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - n_flows=4, - gin_channels=0, - share_parameter=False - ): - - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - - self.wn = attentions.FFT(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = self.gin_channels) if share_parameter else None - - for i in range(n_flows): - self.flows.append( - modules.TransformerCouplingLayer(channels, hidden_channels, kernel_size, n_layers, n_heads, p_dropout, filter_channels, mean_only=True, wn_sharing_parameter=self.wn, gin_channels = self.gin_channels)) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - -class StochasticDurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0): - super().__init__() - filter_channels = in_channels # it needs to be removed from future version. - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.log_flow = modules.Log() - self.flows = nn.ModuleList() - self.flows.append(modules.ElementwiseAffine(2)) - for i in range(n_flows): - self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.flows.append(modules.Flip()) - - self.post_pre = nn.Conv1d(1, filter_channels, 1) - self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - self.post_flows = nn.ModuleList() - self.post_flows.append(modules.ElementwiseAffine(2)) - for i in range(4): - self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3)) - self.post_flows.append(modules.Flip()) - - self.pre = nn.Conv1d(in_channels, filter_channels, 1) - self.proj = nn.Conv1d(filter_channels, filter_channels, 1) - self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout) - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, filter_channels, 1) - - def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0): - x = torch.detach(x) - x = self.pre(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.convs(x, x_mask) - x = self.proj(x) * x_mask - - if not reverse: - flows = self.flows - assert w is not None - - logdet_tot_q = 0 - h_w = self.post_pre(w) - h_w = self.post_convs(h_w, x_mask) - h_w = self.post_proj(h_w) * x_mask - e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask - z_q = e_q - for flow in self.post_flows: - z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w)) - logdet_tot_q += logdet_q - z_u, z1 = torch.split(z_q, [1, 1], 1) - u = torch.sigmoid(z_u) * x_mask - z0 = (w - u) * x_mask - logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2]) - logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q ** 2)) * x_mask, [1, 2]) - logdet_tot_q - - logdet_tot = 0 - z0, logdet = self.log_flow(z0, x_mask) - logdet_tot += logdet - z = torch.cat([z0, z1], 1) - for flow in flows: - z, logdet = flow(z, x_mask, g=x, reverse=reverse) - logdet_tot = logdet_tot + logdet - nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z ** 2)) * x_mask, [1, 2]) - logdet_tot - return nll + logq # [b] - else: - flows = list(reversed(self.flows)) - flows = flows[:-2] + [flows[-1]] # remove a useless vflow - z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale - for flow in flows: - z = flow(z, x_mask, g=x, reverse=reverse) - z0, z1 = torch.split(z, [1, 1], 1) - logw = z0 - return logw - - -class DurationPredictor(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0): - super().__init__() - - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - - self.drop = nn.Dropout(p_dropout) - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2) - self.norm_1 = modules.LayerNorm(filter_channels) - self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2) - self.norm_2 = modules.LayerNorm(filter_channels) - self.proj = nn.Conv1d(filter_channels, 1, 1) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, in_channels, 1) - - def forward(self, x, x_mask, g=None): - x = torch.detach(x) - if g is not None: - g = torch.detach(g) - x = x + self.cond(g) - x = self.conv_1(x * x_mask) - x = torch.relu(x) - x = self.norm_1(x) - x = self.drop(x) - x = self.conv_2(x * x_mask) - x = torch.relu(x) - x = self.norm_2(x) - x = self.drop(x) - x = self.proj(x * x_mask) - return x * x_mask - - -class TextEncoder(nn.Module): - def __init__(self, - n_vocab, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=0): - super().__init__() - self.n_vocab = n_vocab - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.gin_channels = gin_channels - self.emb = nn.Embedding(len(symbols), hidden_channels) - nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5) - self.tone_emb = nn.Embedding(num_tones, hidden_channels) - nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels ** -0.5) - self.language_emb = nn.Embedding(num_languages, hidden_channels) - nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels ** -0.5) - self.bert_proj = nn.Conv1d(1024, hidden_channels, 1) - - self.encoder = attentions.Encoder( - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=self.gin_channels) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, tone, language, bert, g=None): - x = (self.emb(x)+ self.tone_emb(tone)+ self.language_emb(language)+self.bert_proj(bert).transpose(1,2)) * math.sqrt(self.hidden_channels) # [b, t, h] - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - - x = self.encoder(x * x_mask, x_mask, g=g) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return x, m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, - gin_channels=gin_channels, mean_only=True)) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - -class PosteriorEncoder(nn.Module): - def __init__(self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - -class Generator(torch.nn.Module): - def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, - upsample_initial_channel, upsample_kernel_sizes, gin_channels=0): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) - resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append(weight_norm( - ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)), - k, u, padding=(k - u) // 2))) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - print('Removing weight norm...') - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), - norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))), - ]) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList([ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ]) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - -class ReferenceEncoder(nn.Module): - ''' - inputs --- [N, Ty/r, n_mels*r] mels - outputs --- [N, ref_enc_gru_size] - ''' - - def __init__(self, spec_channels, gin_channels=0): - - super().__init__() - self.spec_channels = spec_channels - ref_enc_filters = [32, 32, 64, 64, 128, 128] - K = len(ref_enc_filters) - filters = [1] + ref_enc_filters - convs = [weight_norm(nn.Conv2d(in_channels=filters[i], - out_channels=filters[i + 1], - kernel_size=(3, 3), - stride=(2, 2), - padding=(1, 1))) for i in range(K)] - self.convs = nn.ModuleList(convs) - # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) - - out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K) - self.gru = nn.GRU(input_size=ref_enc_filters[-1] * out_channels, - hidden_size=256 // 2, - batch_first=True) - self.proj = nn.Linear(128, gin_channels) - - def forward(self, inputs, mask=None): - N = inputs.size(0) - out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs] - for conv in self.convs: - out = conv(out) - # out = wn(out) - out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K] - - out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K] - T = out.size(1) - N = out.size(0) - out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K] - - self.gru.flatten_parameters() - memory, out = self.gru(out) # out --- [1, N, 128] - - return self.proj(out.squeeze(0)) - - def calculate_channels(self, L, kernel_size, stride, pad, n_convs): - for i in range(n_convs): - L = (L - kernel_size + 2 * pad) // stride + 1 - return L - - -class SynthesizerTrn(nn.Module): - """ - Synthesizer for Training - """ - - def __init__(self, - n_vocab, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - n_speakers=256, - gin_channels=256, - use_sdp=True, - n_flow_layer = 4, - n_layers_trans_flow = 3, - flow_share_parameter = False, - use_transformer_flow = True, - **kwargs): - - super().__init__() - self.n_vocab = n_vocab - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.n_speakers = n_speakers - self.gin_channels = gin_channels - self.n_layers_trans_flow = n_layers_trans_flow - self.use_spk_conditioned_encoder = kwargs.get("use_spk_conditioned_encoder", True) - self.use_sdp = use_sdp - self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False) - self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01) - self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6) - self.current_mas_noise_scale = self.mas_noise_scale_initial - if self.use_spk_conditioned_encoder and gin_channels > 0: - self.enc_gin_channels = gin_channels - self.enc_p = TextEncoder(n_vocab, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - gin_channels=self.enc_gin_channels) - self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, - upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels) - self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, - gin_channels=gin_channels) - if use_transformer_flow: - self.flow = TransformerCouplingBlock(inter_channels, hidden_channels, filter_channels, n_heads, n_layers_trans_flow, 5, p_dropout, n_flow_layer, gin_channels=gin_channels,share_parameter= flow_share_parameter) - else: - self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, n_flow_layer, gin_channels=gin_channels) - self.sdp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels) - self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels) - - if n_speakers >= 1: - self.emb_g = nn.Embedding(n_speakers, gin_channels) - else: - self.ref_enc = ReferenceEncoder(spec_channels, gin_channels) - - def forward(self, x, x_lengths, y, y_lengths, sid, tone, language, bert): - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1) - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - - with torch.no_grad(): - # negative cross-entropy - s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t] - neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s] - neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), - s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] - neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] - neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s] - neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4 - if self.use_noise_scaled_mas: - epsilon = torch.std(neg_cent) * torch.randn_like(neg_cent) * self.current_mas_noise_scale - neg_cent = neg_cent + epsilon - - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach() - - w = attn.sum(2) - - l_length_sdp = self.sdp(x, x_mask, w, g=g) - l_length_sdp = l_length_sdp / torch.sum(x_mask) - - logw_ = torch.log(w + 1e-6) * x_mask - logw = self.dp(x, x_mask, g=g) - l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(x_mask) # for averaging - - l_length = l_length_dp + l_length_sdp - - # expand prior - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) - - z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size) - o = self.dec(z_slice, g=g) - return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (x, logw, logw_) - - def infer(self, x, x_lengths, sid, tone, language, bert, noise_scale=.667, length_scale=1, noise_scale_w=0.8, max_len=None, sdp_ratio=0,y=None): - #x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert) - # g = self.gst(y) - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1) - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g) - logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (sdp_ratio) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio) - w = torch.exp(logw) * x_mask * length_scale - w_ceil = torch.ceil(w) - y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long() - y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype) - attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) - attn = commons.generate_path(w_ceil, attn_mask) - - m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t'] - logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, - 2) # [b, t', t], [b, t, d] -> [b, d, t'] - - z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale - z = self.flow(z_p, y_mask, g=g, reverse=True) - o = self.dec((z * y_mask)[:, :, :max_len], g=g) - return o, attn, y_mask, (z, z_p, m_p, logs_p) diff --git a/spaces/YONG627/456123/yolov5-code-main/train.py b/spaces/YONG627/456123/yolov5-code-main/train.py deleted file mode 100644 index ab92869d99b616e0e068cc8afeba7389d6ec2f6e..0000000000000000000000000000000000000000 --- a/spaces/YONG627/456123/yolov5-code-main/train.py +++ /dev/null @@ -1,641 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -Train a YOLOv5 model on a custom dataset. -Models and datasets download automatically from the latest YOLOv5 release. - -Usage - Single-GPU training: - $ python train.py --data coco128.yaml --weights yolov5s.pt --img 640 # from pretrained (recommended) - $ python train.py --data coco128.yaml --weights '' --cfg yolov5s.yaml --img 640 # from scratch - -Usage - Multi-GPU DDP training: - $ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 train.py --data coco128.yaml --weights yolov5s.pt --img 640 --device 0,1,2,3 - -Models: https://github.com/ultralytics/yolov5/tree/master/models -Datasets: https://github.com/ultralytics/yolov5/tree/master/data -Tutorial: https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data -""" - -import argparse -import math -import os -os.environ["GIT_PYTHON_REFRESH"] = "quiet" -import random -import subprocess -import sys -import time -from copy import deepcopy -from datetime import datetime -from pathlib import Path - -import numpy as np -import torch -import torch.distributed as dist -import torch.nn as nn -import yaml -from torch.optim import lr_scheduler -from tqdm import tqdm - -FILE = Path(__file__).resolve() -ROOT = FILE.parents[0] # YOLOv5 root directory -if str(ROOT) not in sys.path: - sys.path.append(str(ROOT)) # add ROOT to PATH -ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative - -import val as validate # for end-of-epoch mAP -from models.experimental import attempt_load -from models.yolo import Model -from utils.autoanchor import check_anchors -from utils.autobatch import check_train_batch_size -from utils.callbacks import Callbacks -from utils.dataloaders import create_dataloader -from utils.downloads import attempt_download, is_url -from utils.general import (LOGGER, TQDM_BAR_FORMAT, check_amp, check_dataset, check_file, check_git_info, - check_git_status, check_img_size, check_requirements, check_suffix, check_yaml, colorstr, - get_latest_run, increment_path, init_seeds, intersect_dicts, labels_to_class_weights, - labels_to_image_weights, methods, one_cycle, print_args, print_mutation, strip_optimizer, - yaml_save) -from utils.loggers import Loggers -from utils.loggers.comet.comet_utils import check_comet_resume -from utils.loss import ComputeLoss -from utils.metrics import fitness -from utils.plots import plot_evolve -from utils.torch_utils import (EarlyStopping, ModelEMA, de_parallel, select_device, smart_DDP, smart_optimizer, - smart_resume, torch_distributed_zero_first) - -LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html -RANK = int(os.getenv('RANK', -1)) -WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1)) -GIT_INFO = check_git_info() - - -def train(hyp, opt, device, callbacks): # hyp is path/to/hyp.yaml or hyp dictionary - save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = \ - Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \ - opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze - callbacks.run('on_pretrain_routine_start') - - # Directories - w = save_dir / 'weights' # weights dir - (w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir - last, best = w / 'last.pt', w / 'best.pt' - - # Hyperparameters - if isinstance(hyp, str): - with open(hyp, errors='ignore') as f: - hyp = yaml.safe_load(f) # load hyps dict - LOGGER.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items())) - opt.hyp = hyp.copy() # for saving hyps to checkpoints - - # Save run settings - if not evolve: - yaml_save(save_dir / 'hyp.yaml', hyp) - yaml_save(save_dir / 'opt.yaml', vars(opt)) - - # Loggers - data_dict = None - if RANK in {-1, 0}: - loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance - - # Register actions - for k in methods(loggers): - callbacks.register_action(k, callback=getattr(loggers, k)) - - # Process custom dataset artifact link - data_dict = loggers.remote_dataset - if resume: # If resuming runs from remote artifact - weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size - - # Config - plots = not evolve and not opt.noplots # create plots - cuda = device.type != 'cpu' - init_seeds(opt.seed + 1 + RANK, deterministic=True) - with torch_distributed_zero_first(LOCAL_RANK): - data_dict = data_dict or check_dataset(data) # check if None - train_path, val_path = data_dict['train'], data_dict['val'] - nc = 1 if single_cls else int(data_dict['nc']) # number of classes - names = {0: 'item'} if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names - is_coco = isinstance(val_path, str) and val_path.endswith('coco/val2017.txt') # COCO dataset - - # Model - check_suffix(weights, '.pt') # check weights - pretrained = weights.endswith('.pt') - if pretrained: - with torch_distributed_zero_first(LOCAL_RANK): - weights = attempt_download(weights) # download if not found locally - ckpt = torch.load(weights, map_location='cpu') # load checkpoint to CPU to avoid CUDA memory leak - model = Model(cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create - exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys - csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32 - csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect - model.load_state_dict(csd, strict=False) # load - LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report - else: - model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create - amp = check_amp(model) # check AMP - - # Freeze - freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze - for k, v in model.named_parameters(): - v.requires_grad = True # train all layers - # 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): - LOGGER.info(f'freezing {k}') - v.requires_grad = False - - # Image size - gs = max(int(model.stride.max()), 32) # grid size (max stride) - imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple - - # Batch size - if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size - batch_size = check_train_batch_size(model, imgsz, amp) - loggers.on_params_update({'batch_size': batch_size}) - - # Optimizer - nbs = 64 # nominal batch size - accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing - hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay - optimizer = smart_optimizer(model, opt.optimizer, hyp['lr0'], hyp['momentum'], hyp['weight_decay']) - - # Scheduler - if opt.cos_lr: - lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf'] - else: - lf = lambda x: (1 - x / epochs) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear - scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs) - - # EMA - ema = ModelEMA(model) if RANK in {-1, 0} else None - - # Resume - best_fitness, start_epoch = 0.0, 0 - if pretrained: - if resume: - best_fitness, start_epoch, epochs = smart_resume(ckpt, optimizer, ema, weights, epochs, resume) - del ckpt, csd - - # DP mode - if cuda and RANK == -1 and torch.cuda.device_count() > 1: - LOGGER.warning('WARNING ⚠️ DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n' - 'See Multi-GPU Tutorial at https://github.com/ultralytics/yolov5/issues/475 to get started.') - model = torch.nn.DataParallel(model) - - # SyncBatchNorm - if opt.sync_bn and cuda and RANK != -1: - model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device) - LOGGER.info('Using SyncBatchNorm()') - - # Trainloader - train_loader, dataset = create_dataloader(train_path, - imgsz, - batch_size // WORLD_SIZE, - gs, - single_cls, - hyp=hyp, - augment=True, - cache=None if opt.cache == 'val' else opt.cache, - rect=opt.rect, - rank=LOCAL_RANK, - workers=workers, - image_weights=opt.image_weights, - quad=opt.quad, - prefix=colorstr('train: '), - shuffle=True, - seed=opt.seed) - labels = np.concatenate(dataset.labels, 0) - mlc = int(labels[:, 0].max()) # max label class - assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}' - - # Process 0 - if RANK in {-1, 0}: - val_loader = create_dataloader(val_path, - imgsz, - batch_size // WORLD_SIZE * 2, - gs, - single_cls, - hyp=hyp, - cache=None if noval else opt.cache, - rect=True, - rank=-1, - workers=workers * 2, - pad=0.5, - prefix=colorstr('val: '))[0] - - if not resume: - if not opt.noautoanchor: - check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz) # run AutoAnchor - model.half().float() # pre-reduce anchor precision - - callbacks.run('on_pretrain_routine_end', labels, names) - - # DDP mode - if cuda and RANK != -1: - model = smart_DDP(model) - - # Model attributes - nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps) - hyp['box'] *= 3 / nl # scale to layers - hyp['cls'] *= nc / 80 * 3 / nl # scale to classes and layers - hyp['obj'] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers - hyp['label_smoothing'] = opt.label_smoothing - model.nc = nc # attach number of classes to model - model.hyp = hyp # attach hyperparameters to model - model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights - model.names = names - - # Start training - t0 = time.time() - nb = len(train_loader) # number of batches - nw = max(round(hyp['warmup_epochs'] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations) - # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training - last_opt_step = -1 - maps = np.zeros(nc) # mAP per class - results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls) - scheduler.last_epoch = start_epoch - 1 # do not move - scaler = torch.cuda.amp.GradScaler(enabled=amp) - stopper, stop = EarlyStopping(patience=opt.patience), False - compute_loss = ComputeLoss(model) # init loss class - callbacks.run('on_train_start') - LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n' - f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n' - f"Logging results to {colorstr('bold', save_dir)}\n" - f'Starting training for {epochs} epochs...') - for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------ - callbacks.run('on_train_epoch_start') - model.train() - - # Update image weights (optional, single-GPU only) - if opt.image_weights: - cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights - iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights - dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx - - # Update mosaic border (optional) - # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs) - # dataset.mosaic_border = [b - imgsz, -b] # height, width borders - - mloss = torch.zeros(3, device=device) # mean losses - if RANK != -1: - train_loader.sampler.set_epoch(epoch) - pbar = enumerate(train_loader) - LOGGER.info(('\n' + '%11s' * 7) % ('Epoch', 'GPU_mem', 'box_loss', 'obj_loss', 'cls_loss', 'Instances', 'Size')) - if RANK in {-1, 0}: - pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT) # progress bar - optimizer.zero_grad() - for i, (imgs, targets, paths, _) in pbar: # batch ------------------------------------------------------------- - callbacks.run('on_train_batch_start') - ni = i + nb * epoch # number integrated batches (since train start) - imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0 - - # Warmup - if ni <= nw: - xi = [0, nw] # x interp - # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou) - accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round()) - for j, x in enumerate(optimizer.param_groups): - # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 - x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 0 else 0.0, x['initial_lr'] * lf(epoch)]) - if 'momentum' in x: - x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']]) - - # Multi-scale - if opt.multi_scale: - sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size - sf = sz / max(imgs.shape[2:]) # scale factor - if sf != 1: - ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple) - imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False) - - # Forward - with torch.cuda.amp.autocast(amp): - pred = model(imgs) # forward - loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size - if RANK != -1: - loss *= WORLD_SIZE # gradient averaged between devices in DDP mode - if opt.quad: - loss *= 4. - - # Backward - scaler.scale(loss).backward() - - # Optimize - https://pytorch.org/docs/master/notes/amp_examples.html - if ni - last_opt_step >= accumulate: - scaler.unscale_(optimizer) # unscale gradients - torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients - scaler.step(optimizer) # optimizer.step - scaler.update() - optimizer.zero_grad() - if ema: - ema.update(model) - last_opt_step = ni - - # Log - if RANK in {-1, 0}: - mloss = (mloss * i + loss_items) / (i + 1) # update mean losses - mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB) - pbar.set_description(('%11s' * 2 + '%11.4g' * 5) % - (f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1])) - callbacks.run('on_train_batch_end', model, ni, imgs, targets, paths, list(mloss)) - if callbacks.stop_training: - return - # end batch ------------------------------------------------------------------------------------------------ - - # Scheduler - lr = [x['lr'] for x in optimizer.param_groups] # for loggers - scheduler.step() - - if RANK in {-1, 0}: - # mAP - callbacks.run('on_train_epoch_end', epoch=epoch) - ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights']) - final_epoch = (epoch + 1 == epochs) or stopper.possible_stop - if not noval or final_epoch: # Calculate mAP - results, maps, _ = validate.run(data_dict, - batch_size=batch_size // WORLD_SIZE * 2, - imgsz=imgsz, - half=amp, - model=ema.ema, - single_cls=single_cls, - dataloader=val_loader, - save_dir=save_dir, - plots=False, - callbacks=callbacks, - compute_loss=compute_loss) - - # Update best mAP - fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95] - stop = stopper(epoch=epoch, fitness=fi) # early stop check - if fi > best_fitness: - best_fitness = fi - log_vals = list(mloss) + list(results) + lr - callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi) - - # Save model - if (not nosave) or (final_epoch and not evolve): # if save - ckpt = { - 'epoch': epoch, - 'best_fitness': best_fitness, - 'model': deepcopy(de_parallel(model)).half(), - 'ema': deepcopy(ema.ema).half(), - 'updates': ema.updates, - 'optimizer': optimizer.state_dict(), - 'opt': vars(opt), - 'git': GIT_INFO, # {remote, branch, commit} if a git repo - 'date': datetime.now().isoformat()} - - # Save last, best and delete - torch.save(ckpt, last) - if best_fitness == fi: - torch.save(ckpt, best) - if opt.save_period > 0 and epoch % opt.save_period == 0: - torch.save(ckpt, w / f'epoch{epoch}.pt') - del ckpt - callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi) - - # EarlyStopping - if RANK != -1: # if DDP training - broadcast_list = [stop if RANK == 0 else None] - dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks - if RANK != 0: - stop = broadcast_list[0] - if stop: - break # must break all DDP ranks - - # end epoch ---------------------------------------------------------------------------------------------------- - # end training ----------------------------------------------------------------------------------------------------- - if RANK in {-1, 0}: - LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.') - for f in last, best: - if f.exists(): - strip_optimizer(f) # strip optimizers - if f is best: - LOGGER.info(f'\nValidating {f}...') - results, _, _ = validate.run( - data_dict, - batch_size=batch_size // WORLD_SIZE * 2, - imgsz=imgsz, - model=attempt_load(f, device).half(), - iou_thres=0.65 if is_coco else 0.60, # best pycocotools at iou 0.65 - single_cls=single_cls, - dataloader=val_loader, - save_dir=save_dir, - save_json=is_coco, - verbose=True, - plots=plots, - callbacks=callbacks, - compute_loss=compute_loss) # val best model with plots - if is_coco: - callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi) - - callbacks.run('on_train_end', last, best, epoch, results) - - torch.cuda.empty_cache() - return results - - -def parse_opt(known=False): - parser = argparse.ArgumentParser() - parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='initial weights path') - parser.add_argument('--cfg', type=str, default=ROOT / 'models/yolov5s-mobilenet.yaml', help='model.yaml path') - parser.add_argument('--data', type=str, default=ROOT / 'data/bvn.yaml', help='dataset.yaml path') - parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path') - parser.add_argument('--epochs', type=int, default=100, help='total training epochs') - parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs, -1 for autobatch') - parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)') - parser.add_argument('--rect', action='store_true', help='rectangular training') - parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training') - parser.add_argument('--nosave', action='store_true', help='only save final checkpoint') - parser.add_argument('--noval', action='store_true', help='only validate final epoch') - parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor') - parser.add_argument('--noplots', action='store_true', help='save no plot files') - parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations') - parser.add_argument('--bucket', type=str, default='', help='gsutil bucket') - parser.add_argument('--cache', type=str, nargs='?', const='ram', help='image --cache ram/disk') - parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training') - parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') - parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%') - parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class') - parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer') - parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode') - parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)') - parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name') - parser.add_argument('--name', default='exp', help='save to project/name') - parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') - parser.add_argument('--quad', action='store_true', help='quad dataloader') - parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler') - parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon') - parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)') - parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2') - parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)') - parser.add_argument('--seed', type=int, default=0, help='Global training seed') - parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify') - - # Logger arguments - parser.add_argument('--entity', default=None, help='Entity') - parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='Upload data, "val" option') - parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval') - parser.add_argument('--artifact_alias', type=str, default='latest', help='Version of dataset artifact to use') - - return parser.parse_known_args()[0] if known else parser.parse_args() - - -def main(opt, callbacks=Callbacks()): - # Checks - if RANK in {-1, 0}: - print_args(vars(opt)) - check_git_status() - check_requirements() - - # Resume (from specified or most recent last.pt) - if opt.resume and not check_comet_resume(opt) and not opt.evolve: - last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run()) - opt_yaml = last.parent.parent / 'opt.yaml' # train options yaml - opt_data = opt.data # original dataset - if opt_yaml.is_file(): - with open(opt_yaml, errors='ignore') as f: - d = yaml.safe_load(f) - else: - d = torch.load(last, map_location='cpu')['opt'] - opt = argparse.Namespace(**d) # replace - opt.cfg, opt.weights, opt.resume = '', str(last), True # reinstate - if is_url(opt_data): - opt.data = check_file(opt_data) # avoid HUB resume auth timeout - else: - opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = \ - check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project) # checks - assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified' - if opt.evolve: - if opt.project == str(ROOT / 'runs/train'): # if default project name, rename to runs/evolve - opt.project = str(ROOT / 'runs/evolve') - opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume - if opt.name == 'cfg': - opt.name = Path(opt.cfg).stem # use model.yaml as name - opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) - - # DDP mode - device = select_device(opt.device, batch_size=opt.batch_size) - if LOCAL_RANK != -1: - msg = 'is not compatible with YOLOv5 Multi-GPU DDP training' - assert not opt.image_weights, f'--image-weights {msg}' - assert not opt.evolve, f'--evolve {msg}' - assert opt.batch_size != -1, f'AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size' - assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE' - assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command' - torch.cuda.set_device(LOCAL_RANK) - device = torch.device('cuda', LOCAL_RANK) - dist.init_process_group(backend='nccl' if dist.is_nccl_available() else 'gloo') - - # Train - if not opt.evolve: - train(opt.hyp, opt, device, callbacks) - - # Evolve hyperparameters (optional) - else: - # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit) - meta = { - 'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3) - 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf) - 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1 - 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay - 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok) - 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum - 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr - 'box': (1, 0.02, 0.2), # box loss gain - 'cls': (1, 0.2, 4.0), # cls loss gain - 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight - 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels) - 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight - 'iou_t': (0, 0.1, 0.7), # IoU training threshold - 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold - 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore) - 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5) - 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction) - 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction) - 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction) - 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg) - 'translate': (1, 0.0, 0.9), # image translation (+/- fraction) - 'scale': (1, 0.0, 0.9), # image scale (+/- gain) - 'shear': (1, 0.0, 10.0), # image shear (+/- deg) - 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001 - 'flipud': (1, 0.0, 1.0), # image flip up-down (probability) - 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability) - 'mosaic': (1, 0.0, 1.0), # image mixup (probability) - 'mixup': (1, 0.0, 1.0), # image mixup (probability) - 'copy_paste': (1, 0.0, 1.0)} # segment copy-paste (probability) - - with open(opt.hyp, errors='ignore') as f: - hyp = yaml.safe_load(f) # load hyps dict - if 'anchors' not in hyp: # anchors commented in hyp.yaml - hyp['anchors'] = 3 - if opt.noautoanchor: - del hyp['anchors'], meta['anchors'] - opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch - # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices - evolve_yaml, evolve_csv = save_dir / 'hyp_evolve.yaml', save_dir / 'evolve.csv' - if opt.bucket: - # download evolve.csv if exists - subprocess.run([ - 'gsutil', - 'cp', - f'gs://{opt.bucket}/evolve.csv', - str(evolve_csv),]) - - for _ in range(opt.evolve): # generations to evolve - if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate - # Select parent(s) - parent = 'single' # parent selection method: 'single' or 'weighted' - x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1) - n = min(5, len(x)) # number of previous results to consider - x = x[np.argsort(-fitness(x))][:n] # top n mutations - w = fitness(x) - fitness(x).min() + 1E-6 # weights (sum > 0) - if parent == 'single' or len(x) == 1: - # x = x[random.randint(0, n - 1)] # random selection - x = x[random.choices(range(n), weights=w)[0]] # weighted selection - elif parent == 'weighted': - x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination - - # Mutate - mp, s = 0.8, 0.2 # mutation probability, sigma - npr = np.random - npr.seed(int(time.time())) - g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1 - ng = len(meta) - v = np.ones(ng) - while all(v == 1): # mutate until a change occurs (prevent duplicates) - v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0) - for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300) - hyp[k] = float(x[i + 7] * v[i]) # mutate - - # Constrain to limits - for k, v in meta.items(): - hyp[k] = max(hyp[k], v[1]) # lower limit - hyp[k] = min(hyp[k], v[2]) # upper limit - hyp[k] = round(hyp[k], 5) # significant digits - - # Train mutation - results = train(hyp.copy(), opt, device, callbacks) - callbacks = Callbacks() - # Write mutation results - keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', 'val/box_loss', - 'val/obj_loss', 'val/cls_loss') - print_mutation(keys, results, hyp.copy(), save_dir, opt.bucket) - - # Plot results - plot_evolve(evolve_csv) - LOGGER.info(f'Hyperparameter evolution finished {opt.evolve} generations\n' - f"Results saved to {colorstr('bold', save_dir)}\n" - f'Usage example: $ python train.py --hyp {evolve_yaml}') - - -def run(**kwargs): - # Usage: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt') - opt = parse_opt(True) - for k, v in kwargs.items(): - setattr(opt, k, v) - main(opt) - return opt - - -if __name__ == '__main__': - opt = parse_opt() - main(opt) diff --git a/spaces/Yarumo/prompthero-openjourney-v4/app.py b/spaces/Yarumo/prompthero-openjourney-v4/app.py deleted file mode 100644 index c04b6d45f84686618444749797188ca31fcb9882..0000000000000000000000000000000000000000 --- a/spaces/Yarumo/prompthero-openjourney-v4/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/prompthero/openjourney-v4").launch() \ No newline at end of file diff --git a/spaces/ZilliaxOfficial/nyaru-svc-3.0/inference/slicer.py b/spaces/ZilliaxOfficial/nyaru-svc-3.0/inference/slicer.py deleted file mode 100644 index 35a888b906e7df8634cfdcec914f650c6cefd26a..0000000000000000000000000000000000000000 --- a/spaces/ZilliaxOfficial/nyaru-svc-3.0/inference/slicer.py +++ /dev/null @@ -1,158 +0,0 @@ -import time - -import numpy as np -import torch -import torchaudio -from scipy.ndimage import maximum_filter1d, uniform_filter1d - - -def timeit(func): - def run(*args, **kwargs): - t = time.time() - res = func(*args, **kwargs) - print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t)) - return res - - return run - - -# @timeit -def _window_maximum(arr, win_sz): - return maximum_filter1d(arr, size=win_sz)[win_sz // 2: win_sz // 2 + arr.shape[0] - win_sz + 1] - - -# @timeit -def _window_rms(arr, win_sz): - filtered = np.sqrt(uniform_filter1d(np.power(arr, 2), win_sz) - np.power(uniform_filter1d(arr, win_sz), 2)) - return filtered[win_sz // 2: win_sz // 2 + arr.shape[0] - win_sz + 1] - - -def level2db(levels, eps=1e-12): - return 20 * np.log10(np.clip(levels, a_min=eps, a_max=1)) - - -def _apply_slice(audio, begin, end): - if len(audio.shape) > 1: - return audio[:, begin: end] - else: - return audio[begin: end] - - -class Slicer: - def __init__(self, - sr: int, - db_threshold: float = -40, - min_length: int = 5000, - win_l: int = 300, - win_s: int = 20, - max_silence_kept: int = 500): - self.db_threshold = db_threshold - self.min_samples = round(sr * min_length / 1000) - self.win_ln = round(sr * win_l / 1000) - self.win_sn = round(sr * win_s / 1000) - self.max_silence = round(sr * max_silence_kept / 1000) - if not self.min_samples >= self.win_ln >= self.win_sn: - raise ValueError('The following condition must be satisfied: min_length >= win_l >= win_s') - if not self.max_silence >= self.win_sn: - raise ValueError('The following condition must be satisfied: max_silence_kept >= win_s') - - @timeit - def slice(self, audio): - samples = audio - if samples.shape[0] <= self.min_samples: - return {"0": {"slice": False, "split_time": f"0,{len(audio)}"}} - # get absolute amplitudes - abs_amp = np.abs(samples - np.mean(samples)) - # calculate local maximum with large window - win_max_db = level2db(_window_maximum(abs_amp, win_sz=self.win_ln)) - sil_tags = [] - left = right = 0 - while right < win_max_db.shape[0]: - if win_max_db[right] < self.db_threshold: - right += 1 - elif left == right: - left += 1 - right += 1 - else: - if left == 0: - split_loc_l = left - else: - sil_left_n = min(self.max_silence, (right + self.win_ln - left) // 2) - rms_db_left = level2db(_window_rms(samples[left: left + sil_left_n], win_sz=self.win_sn)) - split_win_l = left + np.argmin(rms_db_left) - split_loc_l = split_win_l + np.argmin(abs_amp[split_win_l: split_win_l + self.win_sn]) - if len(sil_tags) != 0 and split_loc_l - sil_tags[-1][1] < self.min_samples and right < win_max_db.shape[ - 0] - 1: - right += 1 - left = right - continue - if right == win_max_db.shape[0] - 1: - split_loc_r = right + self.win_ln - else: - sil_right_n = min(self.max_silence, (right + self.win_ln - left) // 2) - rms_db_right = level2db(_window_rms(samples[right + self.win_ln - sil_right_n: right + self.win_ln], - win_sz=self.win_sn)) - split_win_r = right + self.win_ln - sil_right_n + np.argmin(rms_db_right) - split_loc_r = split_win_r + np.argmin(abs_amp[split_win_r: split_win_r + self.win_sn]) - sil_tags.append((split_loc_l, split_loc_r)) - right += 1 - left = right - if left != right: - sil_left_n = min(self.max_silence, (right + self.win_ln - left) // 2) - rms_db_left = level2db(_window_rms(samples[left: left + sil_left_n], win_sz=self.win_sn)) - split_win_l = left + np.argmin(rms_db_left) - split_loc_l = split_win_l + np.argmin(abs_amp[split_win_l: split_win_l + self.win_sn]) - sil_tags.append((split_loc_l, samples.shape[0])) - if len(sil_tags) == 0: - return {"0": {"slice": False, "split_time": f"0,{len(audio)}"}} - else: - chunks = [] - # 第一段静音并非从头开始,补上有声片段 - if sil_tags[0][0]: - chunks.append({"slice": False, "split_time": f"0,{sil_tags[0][0]}"}) - for i in range(0, len(sil_tags)): - # 标识有声片段(跳过第一段) - if i: - chunks.append({"slice": False, "split_time": f"{sil_tags[i - 1][1]},{sil_tags[i][0]}"}) - # 标识所有静音片段 - chunks.append({"slice": True, "split_time": f"{sil_tags[i][0]},{sil_tags[i][1]}"}) - # 最后一段静音并非结尾,补上结尾片段 - if sil_tags[-1][1] != len(audio): - chunks.append({"slice": False, "split_time": f"{sil_tags[-1][1]},{len(audio)}"}) - chunk_dict = {} - for i in range(len(chunks)): - chunk_dict[str(i)] = chunks[i] - return chunk_dict - - -def cut(audio_path, db_thresh=-30, min_len=5000, win_l=300, win_s=20, max_sil_kept=500): - audio, sr = torchaudio.load(audio_path) - if len(audio.shape) == 2 and audio.shape[1] >= 2: - audio = torch.mean(audio, dim=0).unsqueeze(0) - audio = audio.cpu().numpy()[0] - - slicer = Slicer( - sr=sr, - db_threshold=db_thresh, - min_length=min_len, - win_l=win_l, - win_s=win_s, - max_silence_kept=max_sil_kept - ) - chunks = slicer.slice(audio) - return chunks - - -def chunks2audio(audio_path, chunks): - chunks = dict(chunks) - audio, sr = torchaudio.load(audio_path) - if len(audio.shape) == 2 and audio.shape[1] >= 2: - audio = torch.mean(audio, dim=0).unsqueeze(0) - audio = audio.cpu().numpy()[0] - result = [] - for k, v in chunks.items(): - tag = v["split_time"].split(",") - result.append((v["slice"], audio[int(tag[0]):int(tag[1])])) - return result, sr - - diff --git a/spaces/Zitang/Self-attention-based-V1MT-motion-model/app.py b/spaces/Zitang/Self-attention-based-V1MT-motion-model/app.py deleted file mode 100644 index e97f7b4ea3463b12b48a08ff2351205c9fbcdac7..0000000000000000000000000000000000000000 --- a/spaces/Zitang/Self-attention-based-V1MT-motion-model/app.py +++ /dev/null @@ -1,128 +0,0 @@ -import gradio as gr -import torch -import math -import cv2 -import os -import sys -import FFV1MT_MS -import flow_tools -import spaces - -@spaces.GPU -def process_images(videos, x, y): - # read video file - cap = cv2.VideoCapture(videos) - # transform images to a list of images ndarray - images = [] - while True: - ret, frame = cap.read() - if ret: - images.append(frame) - else: - break - if len(images) < 11: - print('video is too short') - return - # only use the first 11 frames - images = images[:11] - # transform images to a list of images tensor - images = [torch.from_numpy(img).permute(2, 0, 1).float().to(device).unsqueeze(0) / 255.0 for img in images] - # if the max size of the image is larger than 1024, resize the image to 1024 with same ratio - max_size = max(images[0].shape[2], images[0].shape[3]) - if max_size > 768: - ratio = 768 / max_size - images = [torch.nn.functional.interpolate(img, scale_factor=ratio, mode='bicubic', align_corners=True) for img - in images] - # transform color image to gray image - - result = model.forward_viz(images, layer=7, x=x, y=y) - flow = result['flow'] - attention = result['attention'] - activation = result['activation'] - - return [flow, activation, attention] - - -title = "Modelling Human Visual Motion Processing with Trainable Motion Energy Sensing and a Self-attention Network 🤗 " -description = "## Introduction 🔥🔥🔥\n" \ - " The intersection of cognitive neuroscience and computer vision offers exciting advancements in " \ - "how machines perceive motion. Our research bridges the gap between these fields by proposing a novel " \ - "image-computable model that aligns with human motion perception mechanisms. By integrating trainable" \ - " motion energy sensing with recurrent self-attention networks, we can simulate the complex motion " \ - "processing of the human visual cortex, particularly the V1-MT pathway. Our model not only parallels" \ - " physiological responses in V1 and MT neurons but also replicates human psychophysical responses " \ - "to dynamic stimuli. \n\n\n" \ - "![](https://drive.google.com/uc?id=10PcKzQ9X1nsXKUi8OPR0jN_ZsjlCAV47) \n" \ - "## Environment Configuration 🐡 \n" \ - "To run our model, the basic environment configuration is required:\n" \ - '- Python 3.8 or higher \n' \ - '- Pyotrch 2.0 \n' \ - '- CUDA Toolkit 11.x (for GPU acceleration)\n' \ - '- opencv-python \n' \ - '- Imageio \n' \ - '- Matplotlib \n\n' \ - "## Preprint Paper 📝 \n" \ - "The paper is available at [arXiv](https://arxiv.org/abs/2305.09156) \n" \ - "## Video Presentation 📹 \n" \ - "The video presentation is available at [Video Record](https://recorder-v3.slideslive.com/?share=85662&s=6afe157c-e764-4e3c-9302-2c6dd6887db1). \n" \ - "## Conference Website \n" \ - "The project is presented at [NeurIPS 2023](https://neurips.cc/virtual/2023/poster/70202). \n" \ - "## Below is the interactive demo of our model. You can select the videos examples below or upload your own videos. The model outputs the motion flow field, the activation of the first stage, and the attention map of the second stage." \ - "We also provide two sliders to adjust the location of the attention visualizer. \n" \ - " **Note**: The demo is running on CPU, so it may take a while to process the video. \n" - -examples = [["example_1.mp4", 62, 56], ["example_2.mp4", 59, 55], ["example_3.mp4", 50, 50], ["example_4.mp4", 50, 50], - ["example_5.mp4", 39, 72]] -# examples = [["example_1.mp4", 62, 56]] -md = "## Citation \n" \ - "If you do think this work helps your research, please cite our work as:\n"\ - "```\n"\ - "@inproceedings{ \n"\ - "sun2023modeling,\n"\ - "title={Modeling Human Visual Motion Processing with Trainable Motion Energy Sensing and a Self-attention Network},\n"\ - "author={Zitang Sun and Yen-Ju Chen and Yung-Hao Yang and Shin'ya Nishida},\n"\ - "booktitle={Thirty-seventh Conference on Neural Information Processing Systems},\n"\ - "year={2023},\n"\ - "url={https://openreview.net/forum?id=tRKimbAk5D}\n"\ - "}\n"\ - "```\n"\ - "## Author \n" \ - "This project page is developed by Zitang Sun 📧 (zitangsun96 @ gmail.com)\n" \ - "## LICENSE \n" \ - "This project is licensed under the terms of the MIT license. \n"\ - "## Address 🏡 \n" \ - "[Cognitive Informatics Lab](http://www.cog.ist.i.kyoto-u.ac.jp/en/index.html), Graduate School of Informatics, Kyoto University, Japan \n" - -if __name__ =='__main__': - # torch.cuda.init() - # print(f"Is CUDA available: {torch.cuda.is_available()}") - # # True - # print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}") - # # Tesla T4 - - model = FFV1MT_MS.FFV1DNN() - device = "cuda" if torch.cuda.is_available() else "cpu" - - print('Number fo parameters: {}'.format(model.num_parameters())) - model.to(device) - model_dict = torch.load('Model_example.pth.tar', map_location="cpu")['state_dict'] - # save model - model.load_state_dict(model_dict, strict=True) - model.eval() - - iface = gr.Interface(fn=process_images, - inputs=[gr.Video(label="Upload video or use the example images below"), - gr.Slider(0, 100, label='X location of attention visualizer'), - gr.Slider(0, 100, label='Y location of attention visualizer')], - # out put is three images - outputs=[gr.Image(type="numpy", label="Motion flow field"), - gr.Image(type="numpy", label="Activation of Stage I"), - gr.Image(type="numpy", label="Attention map of Stage II")], - title=title, - description=description, - article=md, - examples=examples) - - iface.launch(debug=True) - - diff --git a/spaces/a-v-bely/russian-task-generator/utilities_option_menu/frontend/dist/js/app.0d11cb9b.js b/spaces/a-v-bely/russian-task-generator/utilities_option_menu/frontend/dist/js/app.0d11cb9b.js deleted file mode 100644 index e20534954620d7ca7e8e7a7d8639204fce247502..0000000000000000000000000000000000000000 --- a/spaces/a-v-bely/russian-task-generator/utilities_option_menu/frontend/dist/js/app.0d11cb9b.js +++ /dev/null @@ -1,18 +0,0 @@ -(function(e){function t(t){for(var r,o,a=t[0],l=t[1],s=t[2],b=0,d=[];b>> load('/path/of/your/file') # file is storaged in disk - >>> load('https://path/of/your/file') # file is storaged in Internet - >>> load('s3://path/of/your/file') # file is storaged in petrel - - Returns: - The content from the file. - """ - if isinstance(file, Path): - file = str(file) - if file_format is None and is_str(file): - file_format = file.split('.')[-1] - if file_format not in file_handlers: - raise TypeError(f'Unsupported format: {file_format}') - - handler = file_handlers[file_format] - if is_str(file): - file_client = FileClient.infer_client(file_client_args, file) - if handler.str_like: - with StringIO(file_client.get_text(file)) as f: - obj = handler.load_from_fileobj(f, **kwargs) - else: - with BytesIO(file_client.get(file)) as f: - obj = handler.load_from_fileobj(f, **kwargs) - elif hasattr(file, 'read'): - obj = handler.load_from_fileobj(file, **kwargs) - else: - raise TypeError('"file" must be a filepath str or a file-object') - return obj - - -def dump(obj, file=None, file_format=None, file_client_args=None, **kwargs): - """Dump data to json/yaml/pickle strings or files. - - This method provides a unified api for dumping data as strings or to files, - and also supports custom arguments for each file format. - - Note: - In v1.3.16 and later, ``dump`` supports dumping data as strings or to - files which is saved to different backends. - - Args: - obj (any): The python object to be dumped. - file (str or :obj:`Path` or file-like object, optional): If not - specified, then the object is dumped to a str, otherwise to a file - specified by the filename or file-like object. - file_format (str, optional): Same as :func:`load`. - file_client_args (dict, optional): Arguments to instantiate a - FileClient. See :class:`mmcv.fileio.FileClient` for details. - Default: None. - - Examples: - >>> dump('hello world', '/path/of/your/file') # disk - >>> dump('hello world', 's3://path/of/your/file') # ceph or petrel - - Returns: - bool: True for success, False otherwise. - """ - if isinstance(file, Path): - file = str(file) - if file_format is None: - if is_str(file): - file_format = file.split('.')[-1] - elif file is None: - raise ValueError( - 'file_format must be specified since file is None') - if file_format not in file_handlers: - raise TypeError(f'Unsupported format: {file_format}') - - handler = file_handlers[file_format] - if file is None: - return handler.dump_to_str(obj, **kwargs) - elif is_str(file): - file_client = FileClient.infer_client(file_client_args, file) - if handler.str_like: - with StringIO() as f: - handler.dump_to_fileobj(obj, f, **kwargs) - file_client.put_text(f.getvalue(), file) - else: - with BytesIO() as f: - handler.dump_to_fileobj(obj, f, **kwargs) - file_client.put(f.getvalue(), file) - elif hasattr(file, 'write'): - handler.dump_to_fileobj(obj, file, **kwargs) - else: - raise TypeError('"file" must be a filename str or a file-object') - - -def _register_handler(handler, file_formats): - """Register a handler for some file extensions. - - Args: - handler (:obj:`BaseFileHandler`): Handler to be registered. - file_formats (str or list[str]): File formats to be handled by this - handler. - """ - if not isinstance(handler, BaseFileHandler): - raise TypeError( - f'handler must be a child of BaseFileHandler, not {type(handler)}') - if isinstance(file_formats, str): - file_formats = [file_formats] - if not is_list_of(file_formats, str): - raise TypeError('file_formats must be a str or a list of str') - for ext in file_formats: - file_handlers[ext] = handler - - -def register_handler(file_formats, **kwargs): - - def wrap(cls): - _register_handler(cls(**kwargs), file_formats) - return cls - - return wrap diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/default_constructor.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/default_constructor.py deleted file mode 100644 index 3f1f5b44168768dfda3947393a63a6cf9cf50b41..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/default_constructor.py +++ /dev/null @@ -1,44 +0,0 @@ -from .builder import RUNNER_BUILDERS, RUNNERS - - -@RUNNER_BUILDERS.register_module() -class DefaultRunnerConstructor: - """Default constructor for runners. - - Custom existing `Runner` like `EpocBasedRunner` though `RunnerConstructor`. - For example, We can inject some new properties and functions for `Runner`. - - Example: - >>> from annotator.uniformer.mmcv.runner import RUNNER_BUILDERS, build_runner - >>> # Define a new RunnerReconstructor - >>> @RUNNER_BUILDERS.register_module() - >>> class MyRunnerConstructor: - ... def __init__(self, runner_cfg, default_args=None): - ... if not isinstance(runner_cfg, dict): - ... raise TypeError('runner_cfg should be a dict', - ... f'but got {type(runner_cfg)}') - ... self.runner_cfg = runner_cfg - ... self.default_args = default_args - ... - ... def __call__(self): - ... runner = RUNNERS.build(self.runner_cfg, - ... default_args=self.default_args) - ... # Add new properties for existing runner - ... runner.my_name = 'my_runner' - ... runner.my_function = lambda self: print(self.my_name) - ... ... - >>> # build your runner - >>> runner_cfg = dict(type='EpochBasedRunner', max_epochs=40, - ... constructor='MyRunnerConstructor') - >>> runner = build_runner(runner_cfg) - """ - - def __init__(self, runner_cfg, default_args=None): - if not isinstance(runner_cfg, dict): - raise TypeError('runner_cfg should be a dict', - f'but got {type(runner_cfg)}') - self.runner_cfg = runner_cfg - self.default_args = default_args - - def __call__(self): - return RUNNERS.build(self.runner_cfg, default_args=self.default_args) diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/hooks/hook.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/hooks/hook.py deleted file mode 100644 index b8855c107727ecf85b917c890fc8b7f6359238a4..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/runner/hooks/hook.py +++ /dev/null @@ -1,92 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from annotator.uniformer.mmcv.utils import Registry, is_method_overridden - -HOOKS = Registry('hook') - - -class Hook: - stages = ('before_run', 'before_train_epoch', 'before_train_iter', - 'after_train_iter', 'after_train_epoch', 'before_val_epoch', - 'before_val_iter', 'after_val_iter', 'after_val_epoch', - 'after_run') - - def before_run(self, runner): - pass - - def after_run(self, runner): - pass - - def before_epoch(self, runner): - pass - - def after_epoch(self, runner): - pass - - def before_iter(self, runner): - pass - - def after_iter(self, runner): - pass - - def before_train_epoch(self, runner): - self.before_epoch(runner) - - def before_val_epoch(self, runner): - self.before_epoch(runner) - - def after_train_epoch(self, runner): - self.after_epoch(runner) - - def after_val_epoch(self, runner): - self.after_epoch(runner) - - def before_train_iter(self, runner): - self.before_iter(runner) - - def before_val_iter(self, runner): - self.before_iter(runner) - - def after_train_iter(self, runner): - self.after_iter(runner) - - def after_val_iter(self, runner): - self.after_iter(runner) - - def every_n_epochs(self, runner, n): - return (runner.epoch + 1) % n == 0 if n > 0 else False - - def every_n_inner_iters(self, runner, n): - return (runner.inner_iter + 1) % n == 0 if n > 0 else False - - def every_n_iters(self, runner, n): - return (runner.iter + 1) % n == 0 if n > 0 else False - - def end_of_epoch(self, runner): - return runner.inner_iter + 1 == len(runner.data_loader) - - def is_last_epoch(self, runner): - return runner.epoch + 1 == runner._max_epochs - - def is_last_iter(self, runner): - return runner.iter + 1 == runner._max_iters - - def get_triggered_stages(self): - trigger_stages = set() - for stage in Hook.stages: - if is_method_overridden(stage, Hook, self): - trigger_stages.add(stage) - - # some methods will be triggered in multi stages - # use this dict to map method to stages. - method_stages_map = { - 'before_epoch': ['before_train_epoch', 'before_val_epoch'], - 'after_epoch': ['after_train_epoch', 'after_val_epoch'], - 'before_iter': ['before_train_iter', 'before_val_iter'], - 'after_iter': ['after_train_iter', 'after_val_iter'], - } - - for method, map_stages in method_stages_map.items(): - if is_method_overridden(method, Hook, self): - trigger_stages.update(map_stages) - - return [stage for stage in Hook.stages if stage in trigger_stages] diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmseg/core/seg/sampler/ohem_pixel_sampler.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmseg/core/seg/sampler/ohem_pixel_sampler.py deleted file mode 100644 index 88bb10d44026ba9f21756eaea9e550841cd59b9f..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmseg/core/seg/sampler/ohem_pixel_sampler.py +++ /dev/null @@ -1,76 +0,0 @@ -import torch -import torch.nn.functional as F - -from ..builder import PIXEL_SAMPLERS -from .base_pixel_sampler import BasePixelSampler - - -@PIXEL_SAMPLERS.register_module() -class OHEMPixelSampler(BasePixelSampler): - """Online Hard Example Mining Sampler for segmentation. - - Args: - context (nn.Module): The context of sampler, subclass of - :obj:`BaseDecodeHead`. - thresh (float, optional): The threshold for hard example selection. - Below which, are prediction with low confidence. If not - specified, the hard examples will be pixels of top ``min_kept`` - loss. Default: None. - min_kept (int, optional): The minimum number of predictions to keep. - Default: 100000. - """ - - def __init__(self, context, thresh=None, min_kept=100000): - super(OHEMPixelSampler, self).__init__() - self.context = context - assert min_kept > 1 - self.thresh = thresh - self.min_kept = min_kept - - def sample(self, seg_logit, seg_label): - """Sample pixels that have high loss or with low prediction confidence. - - Args: - seg_logit (torch.Tensor): segmentation logits, shape (N, C, H, W) - seg_label (torch.Tensor): segmentation label, shape (N, 1, H, W) - - Returns: - torch.Tensor: segmentation weight, shape (N, H, W) - """ - with torch.no_grad(): - assert seg_logit.shape[2:] == seg_label.shape[2:] - assert seg_label.shape[1] == 1 - seg_label = seg_label.squeeze(1).long() - batch_kept = self.min_kept * seg_label.size(0) - valid_mask = seg_label != self.context.ignore_index - seg_weight = seg_logit.new_zeros(size=seg_label.size()) - valid_seg_weight = seg_weight[valid_mask] - if self.thresh is not None: - seg_prob = F.softmax(seg_logit, dim=1) - - tmp_seg_label = seg_label.clone().unsqueeze(1) - tmp_seg_label[tmp_seg_label == self.context.ignore_index] = 0 - seg_prob = seg_prob.gather(1, tmp_seg_label).squeeze(1) - sort_prob, sort_indices = seg_prob[valid_mask].sort() - - if sort_prob.numel() > 0: - min_threshold = sort_prob[min(batch_kept, - sort_prob.numel() - 1)] - else: - min_threshold = 0.0 - threshold = max(min_threshold, self.thresh) - valid_seg_weight[seg_prob[valid_mask] < threshold] = 1. - else: - losses = self.context.loss_decode( - seg_logit, - seg_label, - weight=None, - ignore_index=self.context.ignore_index, - reduction_override='none') - # faster than topk according to https://github.com/pytorch/pytorch/issues/22812 # noqa - _, sort_indices = losses[valid_mask].sort(descending=True) - valid_seg_weight[sort_indices[:batch_kept]] = 1. - - seg_weight[valid_mask] = valid_seg_weight - - return seg_weight diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer_base/mmcv/cnn/bricks/conv_module.py b/spaces/abhishek/sketch-to-image/annotator/uniformer_base/mmcv/cnn/bricks/conv_module.py deleted file mode 100644 index e60e7e62245071c77b652093fddebff3948d7c3e..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer_base/mmcv/cnn/bricks/conv_module.py +++ /dev/null @@ -1,206 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import warnings - -import torch.nn as nn - -from annotator.uniformer.mmcv.utils import _BatchNorm, _InstanceNorm -from ..utils import constant_init, kaiming_init -from .activation import build_activation_layer -from .conv import build_conv_layer -from .norm import build_norm_layer -from .padding import build_padding_layer -from .registry import PLUGIN_LAYERS - - -@PLUGIN_LAYERS.register_module() -class ConvModule(nn.Module): - """A conv block that bundles conv/norm/activation layers. - - This block simplifies the usage of convolution layers, which are commonly - used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU). - It is based upon three build methods: `build_conv_layer()`, - `build_norm_layer()` and `build_activation_layer()`. - - Besides, we add some additional features in this module. - 1. Automatically set `bias` of the conv layer. - 2. Spectral norm is supported. - 3. More padding modes are supported. Before PyTorch 1.5, nn.Conv2d only - supports zero and circular padding, and we add "reflect" padding mode. - - Args: - in_channels (int): Number of channels in the input feature map. - Same as that in ``nn._ConvNd``. - out_channels (int): Number of channels produced by the convolution. - Same as that in ``nn._ConvNd``. - kernel_size (int | tuple[int]): Size of the convolving kernel. - Same as that in ``nn._ConvNd``. - stride (int | tuple[int]): Stride of the convolution. - Same as that in ``nn._ConvNd``. - padding (int | tuple[int]): Zero-padding added to both sides of - the input. Same as that in ``nn._ConvNd``. - dilation (int | tuple[int]): Spacing between kernel elements. - Same as that in ``nn._ConvNd``. - groups (int): Number of blocked connections from input channels to - output channels. Same as that in ``nn._ConvNd``. - bias (bool | str): If specified as `auto`, it will be decided by the - norm_cfg. Bias will be set as True if `norm_cfg` is None, otherwise - False. Default: "auto". - conv_cfg (dict): Config dict for convolution layer. Default: None, - which means using conv2d. - norm_cfg (dict): Config dict for normalization layer. Default: None. - act_cfg (dict): Config dict for activation layer. - Default: dict(type='ReLU'). - inplace (bool): Whether to use inplace mode for activation. - Default: True. - with_spectral_norm (bool): Whether use spectral norm in conv module. - Default: False. - padding_mode (str): If the `padding_mode` has not been supported by - current `Conv2d` in PyTorch, we will use our own padding layer - instead. Currently, we support ['zeros', 'circular'] with official - implementation and ['reflect'] with our own implementation. - Default: 'zeros'. - order (tuple[str]): The order of conv/norm/activation layers. It is a - sequence of "conv", "norm" and "act". Common examples are - ("conv", "norm", "act") and ("act", "conv", "norm"). - Default: ('conv', 'norm', 'act'). - """ - - _abbr_ = 'conv_block' - - def __init__(self, - in_channels, - out_channels, - kernel_size, - stride=1, - padding=0, - dilation=1, - groups=1, - bias='auto', - conv_cfg=None, - norm_cfg=None, - act_cfg=dict(type='ReLU'), - inplace=True, - with_spectral_norm=False, - padding_mode='zeros', - order=('conv', 'norm', 'act')): - super(ConvModule, self).__init__() - assert conv_cfg is None or isinstance(conv_cfg, dict) - assert norm_cfg is None or isinstance(norm_cfg, dict) - assert act_cfg is None or isinstance(act_cfg, dict) - official_padding_mode = ['zeros', 'circular'] - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - self.act_cfg = act_cfg - self.inplace = inplace - self.with_spectral_norm = with_spectral_norm - self.with_explicit_padding = padding_mode not in official_padding_mode - self.order = order - assert isinstance(self.order, tuple) and len(self.order) == 3 - assert set(order) == set(['conv', 'norm', 'act']) - - self.with_norm = norm_cfg is not None - self.with_activation = act_cfg is not None - # if the conv layer is before a norm layer, bias is unnecessary. - if bias == 'auto': - bias = not self.with_norm - self.with_bias = bias - - if self.with_explicit_padding: - pad_cfg = dict(type=padding_mode) - self.padding_layer = build_padding_layer(pad_cfg, padding) - - # reset padding to 0 for conv module - conv_padding = 0 if self.with_explicit_padding else padding - # build convolution layer - self.conv = build_conv_layer( - conv_cfg, - in_channels, - out_channels, - kernel_size, - stride=stride, - padding=conv_padding, - dilation=dilation, - groups=groups, - bias=bias) - # export the attributes of self.conv to a higher level for convenience - self.in_channels = self.conv.in_channels - self.out_channels = self.conv.out_channels - self.kernel_size = self.conv.kernel_size - self.stride = self.conv.stride - self.padding = padding - self.dilation = self.conv.dilation - self.transposed = self.conv.transposed - self.output_padding = self.conv.output_padding - self.groups = self.conv.groups - - if self.with_spectral_norm: - self.conv = nn.utils.spectral_norm(self.conv) - - # build normalization layers - if self.with_norm: - # norm layer is after conv layer - if order.index('norm') > order.index('conv'): - norm_channels = out_channels - else: - norm_channels = in_channels - self.norm_name, norm = build_norm_layer(norm_cfg, norm_channels) - self.add_module(self.norm_name, norm) - if self.with_bias: - if isinstance(norm, (_BatchNorm, _InstanceNorm)): - warnings.warn( - 'Unnecessary conv bias before batch/instance norm') - else: - self.norm_name = None - - # build activation layer - if self.with_activation: - act_cfg_ = act_cfg.copy() - # nn.Tanh has no 'inplace' argument - if act_cfg_['type'] not in [ - 'Tanh', 'PReLU', 'Sigmoid', 'HSigmoid', 'Swish' - ]: - act_cfg_.setdefault('inplace', inplace) - self.activate = build_activation_layer(act_cfg_) - - # Use msra init by default - self.init_weights() - - @property - def norm(self): - if self.norm_name: - return getattr(self, self.norm_name) - else: - return None - - def init_weights(self): - # 1. It is mainly for customized conv layers with their own - # initialization manners by calling their own ``init_weights()``, - # and we do not want ConvModule to override the initialization. - # 2. For customized conv layers without their own initialization - # manners (that is, they don't have their own ``init_weights()``) - # and PyTorch's conv layers, they will be initialized by - # this method with default ``kaiming_init``. - # Note: For PyTorch's conv layers, they will be overwritten by our - # initialization implementation using default ``kaiming_init``. - if not hasattr(self.conv, 'init_weights'): - if self.with_activation and self.act_cfg['type'] == 'LeakyReLU': - nonlinearity = 'leaky_relu' - a = self.act_cfg.get('negative_slope', 0.01) - else: - nonlinearity = 'relu' - a = 0 - kaiming_init(self.conv, a=a, nonlinearity=nonlinearity) - if self.with_norm: - constant_init(self.norm, 1, bias=0) - - def forward(self, x, activate=True, norm=True): - for layer in self.order: - if layer == 'conv': - if self.with_explicit_padding: - x = self.padding_layer(x) - x = self.conv(x) - elif layer == 'norm' and norm and self.with_norm: - x = self.norm(x) - elif layer == 'act' and activate and self.with_activation: - x = self.activate(x) - return x diff --git a/spaces/abionchito/rvc-models/vc_infer_pipeline.py b/spaces/abionchito/rvc-models/vc_infer_pipeline.py deleted file mode 100644 index c26d45068f9b6bf2b194b13c3c89f8a06347c124..0000000000000000000000000000000000000000 --- a/spaces/abionchito/rvc-models/vc_infer_pipeline.py +++ /dev/null @@ -1,306 +0,0 @@ -import numpy as np, parselmouth, torch, pdb -from time import time as ttime -import torch.nn.functional as F -from config import x_pad, x_query, x_center, x_max -import scipy.signal as signal -import pyworld, os, traceback, faiss -from scipy import signal - -bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000) - - -class VC(object): - def __init__(self, tgt_sr, device, is_half): - self.sr = 16000 # hubert输入采样率 - self.window = 160 # 每帧点数 - self.t_pad = self.sr * x_pad # 每条前后pad时间 - self.t_pad_tgt = tgt_sr * x_pad - self.t_pad2 = self.t_pad * 2 - self.t_query = self.sr * x_query # 查询切点前后查询时间 - self.t_center = self.sr * x_center # 查询切点位置 - self.t_max = self.sr * x_max # 免查询时长阈值 - self.device = device - self.is_half = is_half - - def get_f0(self, x, p_len, f0_up_key, f0_method, inp_f0=None): - time_step = self.window / self.sr * 1000 - f0_min = 50 - f0_max = 1100 - f0_mel_min = 1127 * np.log(1 + f0_min / 700) - f0_mel_max = 1127 * np.log(1 + f0_max / 700) - if f0_method == "pm": - f0 = ( - parselmouth.Sound(x, self.sr) - .to_pitch_ac( - time_step=time_step / 1000, - voicing_threshold=0.6, - pitch_floor=f0_min, - pitch_ceiling=f0_max, - ) - .selected_array["frequency"] - ) - pad_size = (p_len - len(f0) + 1) // 2 - if pad_size > 0 or p_len - len(f0) - pad_size > 0: - f0 = np.pad( - f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant" - ) - elif f0_method == "harvest": - f0, t = pyworld.harvest( - x.astype(np.double), - fs=self.sr, - f0_ceil=f0_max, - f0_floor=f0_min, - frame_period=10, - ) - f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr) - f0 = signal.medfilt(f0, 3) - f0 *= pow(2, f0_up_key / 12) - # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) - tf0 = self.sr // self.window # 每秒f0点数 - if inp_f0 is not None: - delta_t = np.round( - (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1 - ).astype("int16") - replace_f0 = np.interp( - list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1] - ) - shape = f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)].shape[0] - f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)] = replace_f0[:shape] - # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()])) - f0bak = f0.copy() - f0_mel = 1127 * np.log(1 + f0 / 700) - f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / ( - f0_mel_max - f0_mel_min - ) + 1 - f0_mel[f0_mel <= 1] = 1 - f0_mel[f0_mel > 255] = 255 - f0_coarse = np.rint(f0_mel).astype(np.int) - return f0_coarse, f0bak # 1-0 - - def vc( - self, - model, - net_g, - sid, - audio0, - pitch, - pitchf, - times, - index, - big_npy, - index_rate, - ): # ,file_index,file_big_npy - feats = torch.from_numpy(audio0) - if self.is_half: - feats = feats.half() - else: - feats = feats.float() - if feats.dim() == 2: # double channels - feats = feats.mean(-1) - assert feats.dim() == 1, feats.dim() - feats = feats.view(1, -1) - padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False) - - inputs = { - "source": feats.to(self.device), - "padding_mask": padding_mask, - "output_layer": 9, # layer 9 - } - t0 = ttime() - with torch.no_grad(): - logits = model.extract_features(**inputs) - feats = model.final_proj(logits[0]) - - if ( - isinstance(index, type(None)) == False - and isinstance(big_npy, type(None)) == False - and index_rate != 0 - ): - npy = feats[0].cpu().numpy() - if self.is_half: - npy = npy.astype("float32") - _, I = index.search(npy, 1) - npy = big_npy[I.squeeze()] - if self.is_half: - npy = npy.astype("float16") - feats = ( - torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate - + (1 - index_rate) * feats - ) - - feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1) - t1 = ttime() - p_len = audio0.shape[0] // self.window - if feats.shape[1] < p_len: - p_len = feats.shape[1] - if pitch != None and pitchf != None: - pitch = pitch[:, :p_len] - pitchf = pitchf[:, :p_len] - p_len = torch.tensor([p_len], device=self.device).long() - with torch.no_grad(): - if pitch != None and pitchf != None: - audio1 = ( - (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0] * 32768) - .data.cpu() - .float() - .numpy() - .astype(np.int16) - ) - else: - audio1 = ( - (net_g.infer(feats, p_len, sid)[0][0, 0] * 32768) - .data.cpu() - .float() - .numpy() - .astype(np.int16) - ) - del feats, p_len, padding_mask - if torch.cuda.is_available(): - torch.cuda.empty_cache() - t2 = ttime() - times[0] += t1 - t0 - times[2] += t2 - t1 - return audio1 - - def pipeline( - self, - model, - net_g, - sid, - audio, - times, - f0_up_key, - f0_method, - file_index, - file_big_npy, - index_rate, - if_f0, - f0_file=None, - ): - if ( - file_big_npy != "" - and file_index != "" - and os.path.exists(file_big_npy) == True - and os.path.exists(file_index) == True - and index_rate != 0 - ): - try: - index = faiss.read_index(file_index) - big_npy = np.load(file_big_npy) - except: - traceback.print_exc() - index = big_npy = None - else: - index = big_npy = None - print("Feature retrieval library doesn't exist or ratio is 0") - audio = signal.filtfilt(bh, ah, audio) - audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect") - opt_ts = [] - if audio_pad.shape[0] > self.t_max: - audio_sum = np.zeros_like(audio) - for i in range(self.window): - audio_sum += audio_pad[i : i - self.window] - for t in range(self.t_center, audio.shape[0], self.t_center): - opt_ts.append( - t - - self.t_query - + np.where( - np.abs(audio_sum[t - self.t_query : t + self.t_query]) - == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min() - )[0][0] - ) - s = 0 - audio_opt = [] - t = None - t1 = ttime() - audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect") - p_len = audio_pad.shape[0] // self.window - inp_f0 = None - if hasattr(f0_file, "name") == True: - try: - with open(f0_file.name, "r") as f: - lines = f.read().strip("\n").split("\n") - inp_f0 = [] - for line in lines: - inp_f0.append([float(i) for i in line.split(",")]) - inp_f0 = np.array(inp_f0, dtype="float32") - except: - traceback.print_exc() - sid = torch.tensor(sid, device=self.device).unsqueeze(0).long() - pitch, pitchf = None, None - if if_f0 == 1: - pitch, pitchf = self.get_f0(audio_pad, p_len, f0_up_key, f0_method, inp_f0) - pitch = pitch[:p_len] - pitchf = pitchf[:p_len] - pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long() - pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float() - t2 = ttime() - times[1] += t2 - t1 - for t in opt_ts: - t = t // self.window * self.window - if if_f0 == 1: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[s : t + self.t_pad2 + self.window], - pitch[:, s // self.window : (t + self.t_pad2) // self.window], - pitchf[:, s // self.window : (t + self.t_pad2) // self.window], - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - else: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[s : t + self.t_pad2 + self.window], - None, - None, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - s = t - if if_f0 == 1: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[t:], - pitch[:, t // self.window :] if t is not None else pitch, - pitchf[:, t // self.window :] if t is not None else pitchf, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - else: - audio_opt.append( - self.vc( - model, - net_g, - sid, - audio_pad[t:], - None, - None, - times, - index, - big_npy, - index_rate, - )[self.t_pad_tgt : -self.t_pad_tgt] - ) - audio_opt = np.concatenate(audio_opt) - del pitch, pitchf, sid - if torch.cuda.is_available(): - torch.cuda.empty_cache() - return audio_opt diff --git a/spaces/abrar-lohia/text-2-character-anim/VQTrans/VQ_eval.py b/spaces/abrar-lohia/text-2-character-anim/VQTrans/VQ_eval.py deleted file mode 100644 index f1b7f269e344f730797eba13a45c9672f323b9f5..0000000000000000000000000000000000000000 --- a/spaces/abrar-lohia/text-2-character-anim/VQTrans/VQ_eval.py +++ /dev/null @@ -1,95 +0,0 @@ -import os -import json - -import torch -from torch.utils.tensorboard import SummaryWriter -import numpy as np -import models.vqvae as vqvae -import options.option_vq as option_vq -import utils.utils_model as utils_model -from dataset import dataset_TM_eval -import utils.eval_trans as eval_trans -from options.get_eval_option import get_opt -from models.evaluator_wrapper import EvaluatorModelWrapper -import warnings -warnings.filterwarnings('ignore') -import numpy as np -##### ---- Exp dirs ---- ##### -args = option_vq.get_args_parser() -torch.manual_seed(args.seed) - -args.out_dir = os.path.join(args.out_dir, f'{args.exp_name}') -os.makedirs(args.out_dir, exist_ok = True) - -##### ---- Logger ---- ##### -logger = utils_model.get_logger(args.out_dir) -writer = SummaryWriter(args.out_dir) -logger.info(json.dumps(vars(args), indent=4, sort_keys=True)) - - -from utils.word_vectorizer import WordVectorizer -w_vectorizer = WordVectorizer('./glove', 'our_vab') - - -dataset_opt_path = 'checkpoints/kit/Comp_v6_KLD005/opt.txt' if args.dataname == 'kit' else 'checkpoints/t2m/Comp_v6_KLD005/opt.txt' - -wrapper_opt = get_opt(dataset_opt_path, torch.device('cuda')) -eval_wrapper = EvaluatorModelWrapper(wrapper_opt) - - -##### ---- Dataloader ---- ##### -args.nb_joints = 21 if args.dataname == 'kit' else 22 - -val_loader = dataset_TM_eval.DATALoader(args.dataname, True, 32, w_vectorizer, unit_length=2**args.down_t) - -##### ---- Network ---- ##### -net = vqvae.HumanVQVAE(args, ## use args to define different parameters in different quantizers - args.nb_code, - args.code_dim, - args.output_emb_width, - args.down_t, - args.stride_t, - args.width, - args.depth, - args.dilation_growth_rate, - args.vq_act, - args.vq_norm) - -if args.resume_pth : - logger.info('loading checkpoint from {}'.format(args.resume_pth)) - ckpt = torch.load(args.resume_pth, map_location='cpu') - net.load_state_dict(ckpt['net'], strict=True) -net.train() -net.cuda() - -fid = [] -div = [] -top1 = [] -top2 = [] -top3 = [] -matching = [] -repeat_time = 20 -for i in range(repeat_time): - best_fid, best_iter, best_div, best_top1, best_top2, best_top3, best_matching, writer, logger = eval_trans.evaluation_vqvae(args.out_dir, val_loader, net, logger, writer, 0, best_fid=1000, best_iter=0, best_div=100, best_top1=0, best_top2=0, best_top3=0, best_matching=100, eval_wrapper=eval_wrapper, draw=False, save=False, savenpy=(i==0)) - fid.append(best_fid) - div.append(best_div) - top1.append(best_top1) - top2.append(best_top2) - top3.append(best_top3) - matching.append(best_matching) -print('final result:') -print('fid: ', sum(fid)/repeat_time) -print('div: ', sum(div)/repeat_time) -print('top1: ', sum(top1)/repeat_time) -print('top2: ', sum(top2)/repeat_time) -print('top3: ', sum(top3)/repeat_time) -print('matching: ', sum(matching)/repeat_time) - -fid = np.array(fid) -div = np.array(div) -top1 = np.array(top1) -top2 = np.array(top2) -top3 = np.array(top3) -matching = np.array(matching) -msg_final = f"FID. {np.mean(fid):.3f}, conf. {np.std(fid)*1.96/np.sqrt(repeat_time):.3f}, Diversity. {np.mean(div):.3f}, conf. {np.std(div)*1.96/np.sqrt(repeat_time):.3f}, TOP1. {np.mean(top1):.3f}, conf. {np.std(top1)*1.96/np.sqrt(repeat_time):.3f}, TOP2. {np.mean(top2):.3f}, conf. {np.std(top2)*1.96/np.sqrt(repeat_time):.3f}, TOP3. {np.mean(top3):.3f}, conf. {np.std(top3)*1.96/np.sqrt(repeat_time):.3f}, Matching. {np.mean(matching):.3f}, conf. {np.std(matching)*1.96/np.sqrt(repeat_time):.3f}" -logger.info(msg_final) \ No newline at end of file diff --git a/spaces/abrar-lohia/text-2-character-anim/pyrender/build/lib/pyrender/camera.py b/spaces/abrar-lohia/text-2-character-anim/pyrender/build/lib/pyrender/camera.py deleted file mode 100644 index e019358039033c3a372c990ebad3151258c3651d..0000000000000000000000000000000000000000 --- a/spaces/abrar-lohia/text-2-character-anim/pyrender/build/lib/pyrender/camera.py +++ /dev/null @@ -1,437 +0,0 @@ -"""Virtual cameras compliant with the glTF 2.0 specification as described at -https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-camera - -Author: Matthew Matl -""" -import abc -import numpy as np -import six -import sys - -from .constants import DEFAULT_Z_NEAR, DEFAULT_Z_FAR - - -@six.add_metaclass(abc.ABCMeta) -class Camera(object): - """Abstract base class for all cameras. - - Note - ---- - Camera poses are specified in the OpenGL format, - where the z axis points away from the view direction and the - x and y axes point to the right and up in the image plane, respectively. - - Parameters - ---------- - znear : float - The floating-point distance to the near clipping plane. - zfar : float - The floating-point distance to the far clipping plane. - ``zfar`` must be greater than ``znear``. - name : str, optional - The user-defined name of this object. - """ - - def __init__(self, - znear=DEFAULT_Z_NEAR, - zfar=DEFAULT_Z_FAR, - name=None): - self.name = name - self.znear = znear - self.zfar = zfar - - @property - def name(self): - """str : The user-defined name of this object. - """ - return self._name - - @name.setter - def name(self, value): - if value is not None: - value = str(value) - self._name = value - - @property - def znear(self): - """float : The distance to the near clipping plane. - """ - return self._znear - - @znear.setter - def znear(self, value): - value = float(value) - if value < 0: - raise ValueError('z-near must be >= 0.0') - self._znear = value - - @property - def zfar(self): - """float : The distance to the far clipping plane. - """ - return self._zfar - - @zfar.setter - def zfar(self, value): - value = float(value) - if value <= 0 or value <= self.znear: - raise ValueError('zfar must be >0 and >znear') - self._zfar = value - - @abc.abstractmethod - def get_projection_matrix(self, width=None, height=None): - """Return the OpenGL projection matrix for this camera. - - Parameters - ---------- - width : int - Width of the current viewport, in pixels. - height : int - Height of the current viewport, in pixels. - """ - pass - - -class PerspectiveCamera(Camera): - - """A perspective camera for perspective projection. - - Parameters - ---------- - yfov : float - The floating-point vertical field of view in radians. - znear : float - The floating-point distance to the near clipping plane. - If not specified, defaults to 0.05. - zfar : float, optional - The floating-point distance to the far clipping plane. - ``zfar`` must be greater than ``znear``. - If None, the camera uses an infinite projection matrix. - aspectRatio : float, optional - The floating-point aspect ratio of the field of view. - If not specified, the camera uses the viewport's aspect ratio. - name : str, optional - The user-defined name of this object. - """ - - def __init__(self, - yfov, - znear=DEFAULT_Z_NEAR, - zfar=None, - aspectRatio=None, - name=None): - super(PerspectiveCamera, self).__init__( - znear=znear, - zfar=zfar, - name=name, - ) - - self.yfov = yfov - self.aspectRatio = aspectRatio - - @property - def yfov(self): - """float : The vertical field of view in radians. - """ - return self._yfov - - @yfov.setter - def yfov(self, value): - value = float(value) - if value <= 0.0: - raise ValueError('Field of view must be positive') - self._yfov = value - - @property - def zfar(self): - """float : The distance to the far clipping plane. - """ - return self._zfar - - @zfar.setter - def zfar(self, value): - if value is not None: - value = float(value) - if value <= 0 or value <= self.znear: - raise ValueError('zfar must be >0 and >znear') - self._zfar = value - - @property - def aspectRatio(self): - """float : The ratio of the width to the height of the field of view. - """ - return self._aspectRatio - - @aspectRatio.setter - def aspectRatio(self, value): - if value is not None: - value = float(value) - if value <= 0.0: - raise ValueError('Aspect ratio must be positive') - self._aspectRatio = value - - def get_projection_matrix(self, width=None, height=None): - """Return the OpenGL projection matrix for this camera. - - Parameters - ---------- - width : int - Width of the current viewport, in pixels. - height : int - Height of the current viewport, in pixels. - """ - aspect_ratio = self.aspectRatio - if aspect_ratio is None: - if width is None or height is None: - raise ValueError('Aspect ratio of camera must be defined') - aspect_ratio = float(width) / float(height) - - a = aspect_ratio - t = np.tan(self.yfov / 2.0) - n = self.znear - f = self.zfar - - P = np.zeros((4,4)) - P[0][0] = 1.0 / (a * t) - P[1][1] = 1.0 / t - P[3][2] = -1.0 - - if f is None: - P[2][2] = -1.0 - P[2][3] = -2.0 * n - else: - P[2][2] = (f + n) / (n - f) - P[2][3] = (2 * f * n) / (n - f) - - return P - - -class OrthographicCamera(Camera): - """An orthographic camera for orthographic projection. - - Parameters - ---------- - xmag : float - The floating-point horizontal magnification of the view. - ymag : float - The floating-point vertical magnification of the view. - znear : float - The floating-point distance to the near clipping plane. - If not specified, defaults to 0.05. - zfar : float - The floating-point distance to the far clipping plane. - ``zfar`` must be greater than ``znear``. - If not specified, defaults to 100.0. - name : str, optional - The user-defined name of this object. - """ - - def __init__(self, - xmag, - ymag, - znear=DEFAULT_Z_NEAR, - zfar=DEFAULT_Z_FAR, - name=None): - super(OrthographicCamera, self).__init__( - znear=znear, - zfar=zfar, - name=name, - ) - - self.xmag = xmag - self.ymag = ymag - - @property - def xmag(self): - """float : The horizontal magnification of the view. - """ - return self._xmag - - @xmag.setter - def xmag(self, value): - value = float(value) - if value <= 0.0: - raise ValueError('X magnification must be positive') - self._xmag = value - - @property - def ymag(self): - """float : The vertical magnification of the view. - """ - return self._ymag - - @ymag.setter - def ymag(self, value): - value = float(value) - if value <= 0.0: - raise ValueError('Y magnification must be positive') - self._ymag = value - - @property - def znear(self): - """float : The distance to the near clipping plane. - """ - return self._znear - - @znear.setter - def znear(self, value): - value = float(value) - if value <= 0: - raise ValueError('z-near must be > 0.0') - self._znear = value - - def get_projection_matrix(self, width=None, height=None): - """Return the OpenGL projection matrix for this camera. - - Parameters - ---------- - width : int - Width of the current viewport, in pixels. - Unused in this function. - height : int - Height of the current viewport, in pixels. - Unused in this function. - """ - xmag = self.xmag - ymag = self.ymag - - # If screen width/height defined, rescale xmag - if width is not None and height is not None: - xmag = width / height * ymag - - n = self.znear - f = self.zfar - P = np.zeros((4,4)) - P[0][0] = 1.0 / xmag - P[1][1] = 1.0 / ymag - P[2][2] = 2.0 / (n - f) - P[2][3] = (f + n) / (n - f) - P[3][3] = 1.0 - return P - - -class IntrinsicsCamera(Camera): - """A perspective camera with custom intrinsics. - - Parameters - ---------- - fx : float - X-axis focal length in pixels. - fy : float - Y-axis focal length in pixels. - cx : float - X-axis optical center in pixels. - cy : float - Y-axis optical center in pixels. - znear : float - The floating-point distance to the near clipping plane. - If not specified, defaults to 0.05. - zfar : float - The floating-point distance to the far clipping plane. - ``zfar`` must be greater than ``znear``. - If not specified, defaults to 100.0. - name : str, optional - The user-defined name of this object. - """ - - def __init__(self, - fx, - fy, - cx, - cy, - znear=DEFAULT_Z_NEAR, - zfar=DEFAULT_Z_FAR, - name=None): - super(IntrinsicsCamera, self).__init__( - znear=znear, - zfar=zfar, - name=name, - ) - - self.fx = fx - self.fy = fy - self.cx = cx - self.cy = cy - - @property - def fx(self): - """float : X-axis focal length in meters. - """ - return self._fx - - @fx.setter - def fx(self, value): - self._fx = float(value) - - @property - def fy(self): - """float : Y-axis focal length in meters. - """ - return self._fy - - @fy.setter - def fy(self, value): - self._fy = float(value) - - @property - def cx(self): - """float : X-axis optical center in pixels. - """ - return self._cx - - @cx.setter - def cx(self, value): - self._cx = float(value) - - @property - def cy(self): - """float : Y-axis optical center in pixels. - """ - return self._cy - - @cy.setter - def cy(self, value): - self._cy = float(value) - - def get_projection_matrix(self, width, height): - """Return the OpenGL projection matrix for this camera. - - Parameters - ---------- - width : int - Width of the current viewport, in pixels. - height : int - Height of the current viewport, in pixels. - """ - width = float(width) - height = float(height) - - cx, cy = self.cx, self.cy - fx, fy = self.fx, self.fy - if sys.platform == 'darwin': - cx = self.cx * 2.0 - cy = self.cy * 2.0 - fx = self.fx * 2.0 - fy = self.fy * 2.0 - - P = np.zeros((4,4)) - P[0][0] = 2.0 * fx / width - P[1][1] = 2.0 * fy / height - P[0][2] = 1.0 - 2.0 * cx / width - P[1][2] = 2.0 * cy / height - 1.0 - P[3][2] = -1.0 - - n = self.znear - f = self.zfar - if f is None: - P[2][2] = -1.0 - P[2][3] = -2.0 * n - else: - P[2][2] = (f + n) / (n - f) - P[2][3] = (2 * f * n) / (n - f) - - return P - - -__all__ = ['Camera', 'PerspectiveCamera', 'OrthographicCamera', - 'IntrinsicsCamera'] diff --git a/spaces/aditi2222/sdffvb/app.py b/spaces/aditi2222/sdffvb/app.py deleted file mode 100644 index 60f32eb3f3a4d735e97bc2bd2ad2f19c05bb431e..0000000000000000000000000000000000000000 --- a/spaces/aditi2222/sdffvb/app.py +++ /dev/null @@ -1,8 +0,0 @@ -# For this demo we're using Gradio, Hugging Face Spaces, Pytorch and Hugging Face Transformers -import gradio as gr -from gradio.mix import Parallel, Series - # Summarizes Meeting Transcripts using Google Research's PEGASUS library -summarizer = gr.Interface.load("huggingface/t5-base") -output_text = gr.outputs.Textbox() -# Displays the end results to a webpage (i.e. here HuggingFace Spaces) -Series(summarizer, inputs = gr.inputs.Textbox(lines=10, label="Meeting Transcript")).launch() diff --git a/spaces/ajitrajasekharan/NER-Biomedical-PHI-Ensemble/README.md b/spaces/ajitrajasekharan/NER-Biomedical-PHI-Ensemble/README.md deleted file mode 100644 index 7a2dcae65b0f5adfef69a05b84c02efb43b8bc15..0000000000000000000000000000000000000000 --- a/spaces/ajitrajasekharan/NER-Biomedical-PHI-Ensemble/README.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: NER Biomedical PHI Ensemble -emoji: 🌖 -colorFrom: indigo -colorTo: green -sdk: streamlit -app_file: app.py -pinned: false -license: mit ---- - -# Configuration - -`title`: _string_ -Display title for the Space - -`emoji`: _string_ -Space emoji (emoji-only character allowed) - -`colorFrom`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`colorTo`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`sdk`: _string_ -Can be either `gradio`, `streamlit`, or `static` - -`sdk_version` : _string_ -Only applicable for `streamlit` SDK. -See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions. - -`app_file`: _string_ -Path to your main application file (which contains either `gradio` or `streamlit` Python code, or `static` html code). -Path is relative to the root of the repository. - -`models`: _List[string]_ -HF model IDs (like "gpt2" or "deepset/roberta-base-squad2") used in the Space. -Will be parsed automatically from your code if not specified here. - -`datasets`: _List[string]_ -HF dataset IDs (like "common_voice" or "oscar-corpus/OSCAR-2109") used in the Space. -Will be parsed automatically from your code if not specified here. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/akhaliq/JoJoGAN/model.py b/spaces/akhaliq/JoJoGAN/model.py deleted file mode 100644 index 497bf78d57c54d58cd3b55f26c718be2470a04f1..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/JoJoGAN/model.py +++ /dev/null @@ -1,688 +0,0 @@ -import math -import random -import functools -import operator - -import torch -from torch import nn -from torch.nn import functional as F -from torch.autograd import Function - -from op import conv2d_gradfix -if torch.cuda.is_available(): - from op.fused_act import FusedLeakyReLU, fused_leaky_relu - from op.upfirdn2d import upfirdn2d -else: - from op.fused_act_cpu import FusedLeakyReLU, fused_leaky_relu - from op.upfirdn2d_cpu import upfirdn2d - - -class PixelNorm(nn.Module): - def __init__(self): - super().__init__() - - def forward(self, input): - return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8) - - -def make_kernel(k): - k = torch.tensor(k, dtype=torch.float32) - - if k.ndim == 1: - k = k[None, :] * k[:, None] - - k /= k.sum() - - return k - - -class Upsample(nn.Module): - def __init__(self, kernel, factor=2): - super().__init__() - - self.factor = factor - kernel = make_kernel(kernel) * (factor ** 2) - self.register_buffer("kernel", kernel) - - p = kernel.shape[0] - factor - - pad0 = (p + 1) // 2 + factor - 1 - pad1 = p // 2 - - self.pad = (pad0, pad1) - - def forward(self, input): - out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=self.pad) - - return out - - -class Downsample(nn.Module): - def __init__(self, kernel, factor=2): - super().__init__() - - self.factor = factor - kernel = make_kernel(kernel) - self.register_buffer("kernel", kernel) - - p = kernel.shape[0] - factor - - pad0 = (p + 1) // 2 - pad1 = p // 2 - - self.pad = (pad0, pad1) - - def forward(self, input): - out = upfirdn2d(input, self.kernel, up=1, down=self.factor, pad=self.pad) - - return out - - -class Blur(nn.Module): - def __init__(self, kernel, pad, upsample_factor=1): - super().__init__() - - kernel = make_kernel(kernel) - - if upsample_factor > 1: - kernel = kernel * (upsample_factor ** 2) - - self.register_buffer("kernel", kernel) - - self.pad = pad - - def forward(self, input): - out = upfirdn2d(input, self.kernel, pad=self.pad) - - return out - - -class EqualConv2d(nn.Module): - def __init__( - self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True - ): - super().__init__() - - self.weight = nn.Parameter( - torch.randn(out_channel, in_channel, kernel_size, kernel_size) - ) - self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2) - - self.stride = stride - self.padding = padding - - if bias: - self.bias = nn.Parameter(torch.zeros(out_channel)) - - else: - self.bias = None - - def forward(self, input): - out = conv2d_gradfix.conv2d( - input, - self.weight * self.scale, - bias=self.bias, - stride=self.stride, - padding=self.padding, - ) - - return out - - def __repr__(self): - return ( - f"{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]}," - f" {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})" - ) - - -class EqualLinear(nn.Module): - def __init__( - self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None - ): - super().__init__() - - self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul)) - - if bias: - self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init)) - - else: - self.bias = None - - self.activation = activation - - self.scale = (1 / math.sqrt(in_dim)) * lr_mul - self.lr_mul = lr_mul - - def forward(self, input): - if self.activation: - out = F.linear(input, self.weight * self.scale) - out = fused_leaky_relu(out, self.bias * self.lr_mul) - - else: - out = F.linear( - input, self.weight * self.scale, bias=self.bias * self.lr_mul - ) - - return out - - def __repr__(self): - return ( - f"{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})" - ) - - -class ModulatedConv2d(nn.Module): - def __init__( - self, - in_channel, - out_channel, - kernel_size, - style_dim, - demodulate=True, - upsample=False, - downsample=False, - blur_kernel=[1, 3, 3, 1], - fused=True, - ): - super().__init__() - - self.eps = 1e-8 - self.kernel_size = kernel_size - self.in_channel = in_channel - self.out_channel = out_channel - self.upsample = upsample - self.downsample = downsample - - if upsample: - factor = 2 - p = (len(blur_kernel) - factor) - (kernel_size - 1) - pad0 = (p + 1) // 2 + factor - 1 - pad1 = p // 2 + 1 - - self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor=factor) - - if downsample: - factor = 2 - p = (len(blur_kernel) - factor) + (kernel_size - 1) - pad0 = (p + 1) // 2 - pad1 = p // 2 - - self.blur = Blur(blur_kernel, pad=(pad0, pad1)) - - fan_in = in_channel * kernel_size ** 2 - self.scale = 1 / math.sqrt(fan_in) - self.padding = kernel_size // 2 - - self.weight = nn.Parameter( - torch.randn(1, out_channel, in_channel, kernel_size, kernel_size) - ) - - self.modulation = EqualLinear(style_dim, in_channel, bias_init=1) - - self.demodulate = demodulate - self.fused = fused - - def __repr__(self): - return ( - f"{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, " - f"upsample={self.upsample}, downsample={self.downsample})" - ) - - def forward(self, input, style): - batch, in_channel, height, width = input.shape - - if not self.fused: - weight = self.scale * self.weight.squeeze(0) - style = self.modulation(style) - - if self.demodulate: - w = weight.unsqueeze(0) * style.view(batch, 1, in_channel, 1, 1) - dcoefs = (w.square().sum((2, 3, 4)) + 1e-8).rsqrt() - - input = input * style.reshape(batch, in_channel, 1, 1) - - if self.upsample: - weight = weight.transpose(0, 1) - out = conv2d_gradfix.conv_transpose2d( - input, weight, padding=0, stride=2 - ) - out = self.blur(out) - - elif self.downsample: - input = self.blur(input) - out = conv2d_gradfix.conv2d(input, weight, padding=0, stride=2) - - else: - out = conv2d_gradfix.conv2d(input, weight, padding=self.padding) - - if self.demodulate: - out = out * dcoefs.view(batch, -1, 1, 1) - - return out - - style = self.modulation(style).view(batch, 1, in_channel, 1, 1) - weight = self.scale * self.weight * style - - if self.demodulate: - demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-8) - weight = weight * demod.view(batch, self.out_channel, 1, 1, 1) - - weight = weight.view( - batch * self.out_channel, in_channel, self.kernel_size, self.kernel_size - ) - - if self.upsample: - input = input.view(1, batch * in_channel, height, width) - weight = weight.view( - batch, self.out_channel, in_channel, self.kernel_size, self.kernel_size - ) - weight = weight.transpose(1, 2).reshape( - batch * in_channel, self.out_channel, self.kernel_size, self.kernel_size - ) - out = conv2d_gradfix.conv_transpose2d( - input, weight, padding=0, stride=2, groups=batch - ) - _, _, height, width = out.shape - out = out.view(batch, self.out_channel, height, width) - out = self.blur(out) - - elif self.downsample: - input = self.blur(input) - _, _, height, width = input.shape - input = input.view(1, batch * in_channel, height, width) - out = conv2d_gradfix.conv2d( - input, weight, padding=0, stride=2, groups=batch - ) - _, _, height, width = out.shape - out = out.view(batch, self.out_channel, height, width) - - else: - input = input.view(1, batch * in_channel, height, width) - out = conv2d_gradfix.conv2d( - input, weight, padding=self.padding, groups=batch - ) - _, _, height, width = out.shape - out = out.view(batch, self.out_channel, height, width) - - return out - - -class NoiseInjection(nn.Module): - def __init__(self): - super().__init__() - - self.weight = nn.Parameter(torch.zeros(1)) - - def forward(self, image, noise=None): - if noise is None: - batch, _, height, width = image.shape - noise = image.new_empty(batch, 1, height, width).normal_() - - return image + self.weight * noise - - -class ConstantInput(nn.Module): - def __init__(self, channel, size=4): - super().__init__() - - self.input = nn.Parameter(torch.randn(1, channel, size, size)) - - def forward(self, input): - batch = input.shape[0] - out = self.input.repeat(batch, 1, 1, 1) - - return out - - -class StyledConv(nn.Module): - def __init__( - self, - in_channel, - out_channel, - kernel_size, - style_dim, - upsample=False, - blur_kernel=[1, 3, 3, 1], - demodulate=True, - ): - super().__init__() - - self.conv = ModulatedConv2d( - in_channel, - out_channel, - kernel_size, - style_dim, - upsample=upsample, - blur_kernel=blur_kernel, - demodulate=demodulate, - ) - - self.noise = NoiseInjection() - # self.bias = nn.Parameter(torch.zeros(1, out_channel, 1, 1)) - # self.activate = ScaledLeakyReLU(0.2) - self.activate = FusedLeakyReLU(out_channel) - - def forward(self, input, style, noise=None): - out = self.conv(input, style) - out = self.noise(out, noise=noise) - # out = out + self.bias - out = self.activate(out) - - return out - - -class ToRGB(nn.Module): - def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]): - super().__init__() - - if upsample: - self.upsample = Upsample(blur_kernel) - - self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate=False) - self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) - - def forward(self, input, style, skip=None): - out = self.conv(input, style) - out = out + self.bias - - if skip is not None: - skip = self.upsample(skip) - - out = out + skip - - return out - - -class Generator(nn.Module): - def __init__( - self, - size, - style_dim, - n_mlp, - channel_multiplier=2, - blur_kernel=[1, 3, 3, 1], - lr_mlp=0.01, - ): - super().__init__() - - self.size = size - - self.style_dim = style_dim - - layers = [PixelNorm()] - - for i in range(n_mlp): - layers.append( - EqualLinear( - style_dim, style_dim, lr_mul=lr_mlp, activation="fused_lrelu" - ) - ) - - self.style = nn.Sequential(*layers) - - self.channels = { - 4: 512, - 8: 512, - 16: 512, - 32: 512, - 64: 256 * channel_multiplier, - 128: 128 * channel_multiplier, - 256: 64 * channel_multiplier, - 512: 32 * channel_multiplier, - 1024: 16 * channel_multiplier, - } - - self.input = ConstantInput(self.channels[4]) - self.conv1 = StyledConv( - self.channels[4], self.channels[4], 3, style_dim, blur_kernel=blur_kernel - ) - self.to_rgb1 = ToRGB(self.channels[4], style_dim, upsample=False) - - self.log_size = int(math.log(size, 2)) - self.num_layers = (self.log_size - 2) * 2 + 1 - - self.convs = nn.ModuleList() - self.upsamples = nn.ModuleList() - self.to_rgbs = nn.ModuleList() - self.noises = nn.Module() - - in_channel = self.channels[4] - - for layer_idx in range(self.num_layers): - res = (layer_idx + 5) // 2 - shape = [1, 1, 2 ** res, 2 ** res] - self.noises.register_buffer(f"noise_{layer_idx}", torch.randn(*shape)) - - for i in range(3, self.log_size + 1): - out_channel = self.channels[2 ** i] - - self.convs.append( - StyledConv( - in_channel, - out_channel, - 3, - style_dim, - upsample=True, - blur_kernel=blur_kernel, - ) - ) - - self.convs.append( - StyledConv( - out_channel, out_channel, 3, style_dim, blur_kernel=blur_kernel - ) - ) - - self.to_rgbs.append(ToRGB(out_channel, style_dim)) - - in_channel = out_channel - - self.n_latent = self.log_size * 2 - 2 - - def make_noise(self): - device = self.input.input.device - - noises = [torch.randn(1, 1, 2 ** 2, 2 ** 2, device=device)] - - for i in range(3, self.log_size + 1): - for _ in range(2): - noises.append(torch.randn(1, 1, 2 ** i, 2 ** i, device=device)) - - return noises - - @torch.no_grad() - def mean_latent(self, n_latent): - latent_in = torch.randn( - n_latent, self.style_dim, device=self.input.input.device - ) - latent = self.style(latent_in).mean(0, keepdim=True) - - return latent - - @torch.no_grad() - def get_latent(self, input): - return self.style(input) - - def forward( - self, - styles, - return_latents=False, - inject_index=None, - truncation=1, - truncation_latent=None, - input_is_latent=False, - noise=None, - randomize_noise=True, - ): - - if noise is None: - if randomize_noise: - noise = [None] * self.num_layers - else: - noise = [ - getattr(self.noises, f"noise_{i}") for i in range(self.num_layers) - ] - - if not input_is_latent: - styles = [self.style(s) for s in styles] - - if truncation < 1: - style_t = [] - - for style in styles: - style_t.append( - truncation_latent + truncation * (style - truncation_latent) - ) - - styles = style_t - latent = styles[0].unsqueeze(1).repeat(1, self.n_latent, 1) - else: - latent = styles - - out = self.input(latent) - out = self.conv1(out, latent[:, 0], noise=noise[0]) - - skip = self.to_rgb1(out, latent[:, 1]) - - i = 1 - for conv1, conv2, noise1, noise2, to_rgb in zip( - self.convs[::2], self.convs[1::2], noise[1::2], noise[2::2], self.to_rgbs - ): - out = conv1(out, latent[:, i], noise=noise1) - out = conv2(out, latent[:, i + 1], noise=noise2) - skip = to_rgb(out, latent[:, i + 2], skip) - - i += 2 - - image = skip - - return image - - -class ConvLayer(nn.Sequential): - def __init__( - self, - in_channel, - out_channel, - kernel_size, - downsample=False, - blur_kernel=[1, 3, 3, 1], - bias=True, - activate=True, - ): - layers = [] - - if downsample: - factor = 2 - p = (len(blur_kernel) - factor) + (kernel_size - 1) - pad0 = (p + 1) // 2 - pad1 = p // 2 - - layers.append(Blur(blur_kernel, pad=(pad0, pad1))) - - stride = 2 - self.padding = 0 - - else: - stride = 1 - self.padding = kernel_size // 2 - - layers.append( - EqualConv2d( - in_channel, - out_channel, - kernel_size, - padding=self.padding, - stride=stride, - bias=bias and not activate, - ) - ) - - if activate: - layers.append(FusedLeakyReLU(out_channel, bias=bias)) - - super().__init__(*layers) - - -class ResBlock(nn.Module): - def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]): - super().__init__() - - self.conv1 = ConvLayer(in_channel, in_channel, 3) - self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True) - - self.skip = ConvLayer( - in_channel, out_channel, 1, downsample=True, activate=False, bias=False - ) - - def forward(self, input): - out = self.conv1(input) - out = self.conv2(out) - - skip = self.skip(input) - out = (out + skip) / math.sqrt(2) - - return out - - -class Discriminator(nn.Module): - def __init__(self, size, channel_multiplier=2, blur_kernel=[1, 3, 3, 1]): - super().__init__() - - channels = { - 4: 512, - 8: 512, - 16: 512, - 32: 512, - 64: 256 * channel_multiplier, - 128: 128 * channel_multiplier, - 256: 64 * channel_multiplier, - 512: 32 * channel_multiplier, - 1024: 16 * channel_multiplier, - } - - convs = [ConvLayer(3, channels[size], 1)] - - log_size = int(math.log(size, 2)) - - in_channel = channels[size] - - for i in range(log_size, 2, -1): - out_channel = channels[2 ** (i - 1)] - - convs.append(ResBlock(in_channel, out_channel, blur_kernel)) - - in_channel = out_channel - - self.convs = nn.Sequential(*convs) - - self.stddev_group = 4 - self.stddev_feat = 1 - - self.final_conv = ConvLayer(in_channel + 1, channels[4], 3) - self.final_linear = nn.Sequential( - EqualLinear(channels[4] * 4 * 4, channels[4], activation="fused_lrelu"), - EqualLinear(channels[4], 1), - ) - - def forward(self, input): - out = self.convs(input) - - batch, channel, height, width = out.shape - group = min(batch, self.stddev_group) - stddev = out.view( - group, -1, self.stddev_feat, channel // self.stddev_feat, height, width - ) - stddev = torch.sqrt(stddev.var(0, unbiased=False) + 1e-8) - stddev = stddev.mean([2, 3, 4], keepdims=True).squeeze(2) - stddev = stddev.repeat(group, 1, height, width) - out = torch.cat([out, stddev], 1) - - out = self.final_conv(out) - - out = out.view(batch, -1) - out = self.final_linear(out) - - return out - diff --git a/spaces/akhaliq/small-stable-diffusion-v0/README.md b/spaces/akhaliq/small-stable-diffusion-v0/README.md deleted file mode 100644 index 763bb5e0414f5bd9802c84f9f7d312fbc1c5d90c..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/small-stable-diffusion-v0/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Small Stable Diffusion V0 -emoji: 💻 -colorFrom: indigo -colorTo: yellow -sdk: gradio -sdk_version: 3.16.2 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/pep517/compat.py b/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/pep517/compat.py deleted file mode 100644 index 730ef5ffaa1a57580bd6a4626e223735633ee049..0000000000000000000000000000000000000000 --- a/spaces/alexray/btc_predictor/venv/lib/python3.10/site-packages/pip/_vendor/pep517/compat.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Python 2/3 compatibility""" -import io -import json -import sys - - -# Handle reading and writing JSON in UTF-8, on Python 3 and 2. - -if sys.version_info[0] >= 3: - # Python 3 - def write_json(obj, path, **kwargs): - with open(path, 'w', encoding='utf-8') as f: - json.dump(obj, f, **kwargs) - - def read_json(path): - with open(path, 'r', encoding='utf-8') as f: - return json.load(f) - -else: - # Python 2 - def write_json(obj, path, **kwargs): - with open(path, 'wb') as f: - json.dump(obj, f, encoding='utf-8', **kwargs) - - def read_json(path): - with open(path, 'rb') as f: - return json.load(f) - - -# FileNotFoundError - -try: - FileNotFoundError = FileNotFoundError -except NameError: - FileNotFoundError = IOError - - -if sys.version_info < (3, 6): - from toml import load as _toml_load # noqa: F401 - - def toml_load(f): - w = io.TextIOWrapper(f, encoding="utf8", newline="") - try: - return _toml_load(w) - finally: - w.detach() - - from toml import TomlDecodeError as TOMLDecodeError # noqa: F401 -else: - from pip._vendor.tomli import load as toml_load # noqa: F401 - from pip._vendor.tomli import TOMLDecodeError # noqa: F401 diff --git a/spaces/almakedon/faster-whisper-webui/src/utils.py b/spaces/almakedon/faster-whisper-webui/src/utils.py deleted file mode 100644 index 576244c9cf8b8e8aa888b0a51312ddf56db928ce..0000000000000000000000000000000000000000 --- a/spaces/almakedon/faster-whisper-webui/src/utils.py +++ /dev/null @@ -1,245 +0,0 @@ -import textwrap -import unicodedata -import re - -import zlib -from typing import Iterator, TextIO, Union -import tqdm - -import urllib3 - - -def exact_div(x, y): - assert x % y == 0 - return x // y - - -def str2bool(string): - str2val = {"True": True, "False": False} - if string in str2val: - return str2val[string] - else: - raise ValueError(f"Expected one of {set(str2val.keys())}, got {string}") - - -def optional_int(string): - return None if string == "None" else int(string) - - -def optional_float(string): - return None if string == "None" else float(string) - - -def compression_ratio(text) -> float: - return len(text) / len(zlib.compress(text.encode("utf-8"))) - - -def format_timestamp(seconds: float, always_include_hours: bool = False, fractionalSeperator: str = '.'): - assert seconds >= 0, "non-negative timestamp expected" - milliseconds = round(seconds * 1000.0) - - hours = milliseconds // 3_600_000 - milliseconds -= hours * 3_600_000 - - minutes = milliseconds // 60_000 - milliseconds -= minutes * 60_000 - - seconds = milliseconds // 1_000 - milliseconds -= seconds * 1_000 - - hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else "" - return f"{hours_marker}{minutes:02d}:{seconds:02d}{fractionalSeperator}{milliseconds:03d}" - - -def write_txt(transcript: Iterator[dict], file: TextIO): - for segment in transcript: - print(segment['text'].strip(), file=file, flush=True) - - -def write_vtt(transcript: Iterator[dict], file: TextIO, - maxLineWidth=None, highlight_words: bool = False): - iterator = __subtitle_preprocessor_iterator(transcript, maxLineWidth, highlight_words) - - print("WEBVTT\n", file=file) - - for segment in iterator: - text = segment['text'].replace('-->', '->') - - print( - f"{format_timestamp(segment['start'])} --> {format_timestamp(segment['end'])}\n" - f"{text}\n", - file=file, - flush=True, - ) - -def write_srt(transcript: Iterator[dict], file: TextIO, - maxLineWidth=None, highlight_words: bool = False): - """ - Write a transcript to a file in SRT format. - Example usage: - from pathlib import Path - from whisper.utils import write_srt - result = transcribe(model, audio_path, temperature=temperature, **args) - # save SRT - audio_basename = Path(audio_path).stem - with open(Path(output_dir) / (audio_basename + ".srt"), "w", encoding="utf-8") as srt: - write_srt(result["segments"], file=srt) - """ - iterator = __subtitle_preprocessor_iterator(transcript, maxLineWidth, highlight_words) - - for i, segment in enumerate(iterator, start=1): - text = segment['text'].replace('-->', '->') - - # write srt lines - print( - f"{i}\n" - f"{format_timestamp(segment['start'], always_include_hours=True, fractionalSeperator=',')} --> " - f"{format_timestamp(segment['end'], always_include_hours=True, fractionalSeperator=',')}\n" - f"{text}\n", - file=file, - flush=True, - ) - -def __subtitle_preprocessor_iterator(transcript: Iterator[dict], maxLineWidth: int = None, highlight_words: bool = False): - for segment in transcript: - words = segment.get('words', []) - - if len(words) == 0: - # Yield the segment as-is or processed - if maxLineWidth is None or maxLineWidth < 0: - yield segment - else: - yield { - 'start': segment['start'], - 'end': segment['end'], - 'text': process_text(segment['text'].strip(), maxLineWidth) - } - # We are done - continue - - subtitle_start = segment['start'] - subtitle_end = segment['end'] - - text_words = [ this_word["word"] for this_word in words ] - subtitle_text = __join_words(text_words, maxLineWidth) - - # Iterate over the words in the segment - if highlight_words: - last = subtitle_start - - for i, this_word in enumerate(words): - start = this_word['start'] - end = this_word['end'] - - if last != start: - # Display the text up to this point - yield { - 'start': last, - 'end': start, - 'text': subtitle_text - } - - # Display the text with the current word highlighted - yield { - 'start': start, - 'end': end, - 'text': __join_words( - [ - { - "word": re.sub(r"^(\s*)(.*)$", r"\1\2", word) - if j == i - else word, - # The HTML tags and are not displayed, - # # so they should not be counted in the word length - "length": len(word) - } for j, word in enumerate(text_words) - ], maxLineWidth) - } - last = end - - if last != subtitle_end: - # Display the last part of the text - yield { - 'start': last, - 'end': subtitle_end, - 'text': subtitle_text - } - - # Just return the subtitle text - else: - yield { - 'start': subtitle_start, - 'end': subtitle_end, - 'text': subtitle_text - } - -def __join_words(words: Iterator[Union[str, dict]], maxLineWidth: int = None): - if maxLineWidth is None or maxLineWidth < 0: - return " ".join(words) - - lines = [] - current_line = "" - current_length = 0 - - for entry in words: - # Either accept a string or a dict with a 'word' and 'length' field - if isinstance(entry, dict): - word = entry['word'] - word_length = entry['length'] - else: - word = entry - word_length = len(word) - - if current_length > 0 and current_length + word_length > maxLineWidth: - lines.append(current_line) - current_line = "" - current_length = 0 - - current_length += word_length - # The word will be prefixed with a space by Whisper, so we don't need to add one here - current_line += word - - if len(current_line) > 0: - lines.append(current_line) - - return "\n".join(lines) - -def process_text(text: str, maxLineWidth=None): - if (maxLineWidth is None or maxLineWidth < 0): - return text - - lines = textwrap.wrap(text, width=maxLineWidth, tabsize=4) - return '\n'.join(lines) - -def slugify(value, allow_unicode=False): - """ - Taken from https://github.com/django/django/blob/master/django/utils/text.py - Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated - dashes to single dashes. Remove characters that aren't alphanumerics, - underscores, or hyphens. Convert to lowercase. Also strip leading and - trailing whitespace, dashes, and underscores. - """ - value = str(value) - if allow_unicode: - value = unicodedata.normalize('NFKC', value) - else: - value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') - value = re.sub(r'[^\w\s-]', '', value.lower()) - return re.sub(r'[-\s]+', '-', value).strip('-_') - -def download_file(url: str, destination: str): - with urllib3.request.urlopen(url) as source, open(destination, "wb") as output: - with tqdm( - total=int(source.info().get("Content-Length")), - ncols=80, - unit="iB", - unit_scale=True, - unit_divisor=1024, - ) as loop: - while True: - buffer = source.read(8192) - if not buffer: - break - - output.write(buffer) - loop.update(len(buffer)) \ No newline at end of file diff --git a/spaces/amankishore/sjc/sd1/ldm/modules/x_transformer.py b/spaces/amankishore/sjc/sd1/ldm/modules/x_transformer.py deleted file mode 100644 index 5fc15bf9cfe0111a910e7de33d04ffdec3877576..0000000000000000000000000000000000000000 --- a/spaces/amankishore/sjc/sd1/ldm/modules/x_transformer.py +++ /dev/null @@ -1,641 +0,0 @@ -"""shout-out to https://github.com/lucidrains/x-transformers/tree/main/x_transformers""" -import torch -from torch import nn, einsum -import torch.nn.functional as F -from functools import partial -from inspect import isfunction -from collections import namedtuple -from einops import rearrange, repeat, reduce - -# constants - -DEFAULT_DIM_HEAD = 64 - -Intermediates = namedtuple('Intermediates', [ - 'pre_softmax_attn', - 'post_softmax_attn' -]) - -LayerIntermediates = namedtuple('Intermediates', [ - 'hiddens', - 'attn_intermediates' -]) - - -class AbsolutePositionalEmbedding(nn.Module): - def __init__(self, dim, max_seq_len): - super().__init__() - self.emb = nn.Embedding(max_seq_len, dim) - self.init_() - - def init_(self): - nn.init.normal_(self.emb.weight, std=0.02) - - def forward(self, x): - n = torch.arange(x.shape[1], device=x.device) - return self.emb(n)[None, :, :] - - -class FixedPositionalEmbedding(nn.Module): - def __init__(self, dim): - super().__init__() - inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim)) - self.register_buffer('inv_freq', inv_freq) - - def forward(self, x, seq_dim=1, offset=0): - t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq) + offset - sinusoid_inp = torch.einsum('i , j -> i j', t, self.inv_freq) - emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1) - return emb[None, :, :] - - -# helpers - -def exists(val): - return val is not None - - -def default(val, d): - if exists(val): - return val - return d() if isfunction(d) else d - - -def always(val): - def inner(*args, **kwargs): - return val - return inner - - -def not_equals(val): - def inner(x): - return x != val - return inner - - -def equals(val): - def inner(x): - return x == val - return inner - - -def max_neg_value(tensor): - return -torch.finfo(tensor.dtype).max - - -# keyword argument helpers - -def pick_and_pop(keys, d): - values = list(map(lambda key: d.pop(key), keys)) - return dict(zip(keys, values)) - - -def group_dict_by_key(cond, d): - return_val = [dict(), dict()] - for key in d.keys(): - match = bool(cond(key)) - ind = int(not match) - return_val[ind][key] = d[key] - return (*return_val,) - - -def string_begins_with(prefix, str): - return str.startswith(prefix) - - -def group_by_key_prefix(prefix, d): - return group_dict_by_key(partial(string_begins_with, prefix), d) - - -def groupby_prefix_and_trim(prefix, d): - kwargs_with_prefix, kwargs = group_dict_by_key(partial(string_begins_with, prefix), d) - kwargs_without_prefix = dict(map(lambda x: (x[0][len(prefix):], x[1]), tuple(kwargs_with_prefix.items()))) - return kwargs_without_prefix, kwargs - - -# classes -class Scale(nn.Module): - def __init__(self, value, fn): - super().__init__() - self.value = value - self.fn = fn - - def forward(self, x, **kwargs): - x, *rest = self.fn(x, **kwargs) - return (x * self.value, *rest) - - -class Rezero(nn.Module): - def __init__(self, fn): - super().__init__() - self.fn = fn - self.g = nn.Parameter(torch.zeros(1)) - - def forward(self, x, **kwargs): - x, *rest = self.fn(x, **kwargs) - return (x * self.g, *rest) - - -class ScaleNorm(nn.Module): - def __init__(self, dim, eps=1e-5): - super().__init__() - self.scale = dim ** -0.5 - self.eps = eps - self.g = nn.Parameter(torch.ones(1)) - - def forward(self, x): - norm = torch.norm(x, dim=-1, keepdim=True) * self.scale - return x / norm.clamp(min=self.eps) * self.g - - -class RMSNorm(nn.Module): - def __init__(self, dim, eps=1e-8): - super().__init__() - self.scale = dim ** -0.5 - self.eps = eps - self.g = nn.Parameter(torch.ones(dim)) - - def forward(self, x): - norm = torch.norm(x, dim=-1, keepdim=True) * self.scale - return x / norm.clamp(min=self.eps) * self.g - - -class Residual(nn.Module): - def forward(self, x, residual): - return x + residual - - -class GRUGating(nn.Module): - def __init__(self, dim): - super().__init__() - self.gru = nn.GRUCell(dim, dim) - - def forward(self, x, residual): - gated_output = self.gru( - rearrange(x, 'b n d -> (b n) d'), - rearrange(residual, 'b n d -> (b n) d') - ) - - return gated_output.reshape_as(x) - - -# feedforward - -class GEGLU(nn.Module): - def __init__(self, dim_in, dim_out): - super().__init__() - self.proj = nn.Linear(dim_in, dim_out * 2) - - def forward(self, x): - x, gate = self.proj(x).chunk(2, dim=-1) - return x * F.gelu(gate) - - -class FeedForward(nn.Module): - def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.): - super().__init__() - inner_dim = int(dim * mult) - dim_out = default(dim_out, dim) - project_in = nn.Sequential( - nn.Linear(dim, inner_dim), - nn.GELU() - ) if not glu else GEGLU(dim, inner_dim) - - self.net = nn.Sequential( - project_in, - nn.Dropout(dropout), - nn.Linear(inner_dim, dim_out) - ) - - def forward(self, x): - return self.net(x) - - -# attention. -class Attention(nn.Module): - def __init__( - self, - dim, - dim_head=DEFAULT_DIM_HEAD, - heads=8, - causal=False, - mask=None, - talking_heads=False, - sparse_topk=None, - use_entmax15=False, - num_mem_kv=0, - dropout=0., - on_attn=False - ): - super().__init__() - if use_entmax15: - raise NotImplementedError("Check out entmax activation instead of softmax activation!") - self.scale = dim_head ** -0.5 - self.heads = heads - self.causal = causal - self.mask = mask - - inner_dim = dim_head * heads - - self.to_q = nn.Linear(dim, inner_dim, bias=False) - self.to_k = nn.Linear(dim, inner_dim, bias=False) - self.to_v = nn.Linear(dim, inner_dim, bias=False) - self.dropout = nn.Dropout(dropout) - - # talking heads - self.talking_heads = talking_heads - if talking_heads: - self.pre_softmax_proj = nn.Parameter(torch.randn(heads, heads)) - self.post_softmax_proj = nn.Parameter(torch.randn(heads, heads)) - - # explicit topk sparse attention - self.sparse_topk = sparse_topk - - # entmax - #self.attn_fn = entmax15 if use_entmax15 else F.softmax - self.attn_fn = F.softmax - - # add memory key / values - self.num_mem_kv = num_mem_kv - if num_mem_kv > 0: - self.mem_k = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head)) - self.mem_v = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head)) - - # attention on attention - self.attn_on_attn = on_attn - self.to_out = nn.Sequential(nn.Linear(inner_dim, dim * 2), nn.GLU()) if on_attn else nn.Linear(inner_dim, dim) - - def forward( - self, - x, - context=None, - mask=None, - context_mask=None, - rel_pos=None, - sinusoidal_emb=None, - prev_attn=None, - mem=None - ): - b, n, _, h, talking_heads, device = *x.shape, self.heads, self.talking_heads, x.device - kv_input = default(context, x) - - q_input = x - k_input = kv_input - v_input = kv_input - - if exists(mem): - k_input = torch.cat((mem, k_input), dim=-2) - v_input = torch.cat((mem, v_input), dim=-2) - - if exists(sinusoidal_emb): - # in shortformer, the query would start at a position offset depending on the past cached memory - offset = k_input.shape[-2] - q_input.shape[-2] - q_input = q_input + sinusoidal_emb(q_input, offset=offset) - k_input = k_input + sinusoidal_emb(k_input) - - q = self.to_q(q_input) - k = self.to_k(k_input) - v = self.to_v(v_input) - - q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), (q, k, v)) - - input_mask = None - if any(map(exists, (mask, context_mask))): - q_mask = default(mask, lambda: torch.ones((b, n), device=device).bool()) - k_mask = q_mask if not exists(context) else context_mask - k_mask = default(k_mask, lambda: torch.ones((b, k.shape[-2]), device=device).bool()) - q_mask = rearrange(q_mask, 'b i -> b () i ()') - k_mask = rearrange(k_mask, 'b j -> b () () j') - input_mask = q_mask * k_mask - - if self.num_mem_kv > 0: - mem_k, mem_v = map(lambda t: repeat(t, 'h n d -> b h n d', b=b), (self.mem_k, self.mem_v)) - k = torch.cat((mem_k, k), dim=-2) - v = torch.cat((mem_v, v), dim=-2) - if exists(input_mask): - input_mask = F.pad(input_mask, (self.num_mem_kv, 0), value=True) - - dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale - mask_value = max_neg_value(dots) - - if exists(prev_attn): - dots = dots + prev_attn - - pre_softmax_attn = dots - - if talking_heads: - dots = einsum('b h i j, h k -> b k i j', dots, self.pre_softmax_proj).contiguous() - - if exists(rel_pos): - dots = rel_pos(dots) - - if exists(input_mask): - dots.masked_fill_(~input_mask, mask_value) - del input_mask - - if self.causal: - i, j = dots.shape[-2:] - r = torch.arange(i, device=device) - mask = rearrange(r, 'i -> () () i ()') < rearrange(r, 'j -> () () () j') - mask = F.pad(mask, (j - i, 0), value=False) - dots.masked_fill_(mask, mask_value) - del mask - - if exists(self.sparse_topk) and self.sparse_topk < dots.shape[-1]: - top, _ = dots.topk(self.sparse_topk, dim=-1) - vk = top[..., -1].unsqueeze(-1).expand_as(dots) - mask = dots < vk - dots.masked_fill_(mask, mask_value) - del mask - - attn = self.attn_fn(dots, dim=-1) - post_softmax_attn = attn - - attn = self.dropout(attn) - - if talking_heads: - attn = einsum('b h i j, h k -> b k i j', attn, self.post_softmax_proj).contiguous() - - out = einsum('b h i j, b h j d -> b h i d', attn, v) - out = rearrange(out, 'b h n d -> b n (h d)') - - intermediates = Intermediates( - pre_softmax_attn=pre_softmax_attn, - post_softmax_attn=post_softmax_attn - ) - - return self.to_out(out), intermediates - - -class AttentionLayers(nn.Module): - def __init__( - self, - dim, - depth, - heads=8, - causal=False, - cross_attend=False, - only_cross=False, - use_scalenorm=False, - use_rmsnorm=False, - use_rezero=False, - rel_pos_num_buckets=32, - rel_pos_max_distance=128, - position_infused_attn=False, - custom_layers=None, - sandwich_coef=None, - par_ratio=None, - residual_attn=False, - cross_residual_attn=False, - macaron=False, - pre_norm=True, - gate_residual=False, - **kwargs - ): - super().__init__() - ff_kwargs, kwargs = groupby_prefix_and_trim('ff_', kwargs) - attn_kwargs, _ = groupby_prefix_and_trim('attn_', kwargs) - - dim_head = attn_kwargs.get('dim_head', DEFAULT_DIM_HEAD) - - self.dim = dim - self.depth = depth - self.layers = nn.ModuleList([]) - - self.has_pos_emb = position_infused_attn - self.pia_pos_emb = FixedPositionalEmbedding(dim) if position_infused_attn else None - self.rotary_pos_emb = always(None) - - assert rel_pos_num_buckets <= rel_pos_max_distance, 'number of relative position buckets must be less than the relative position max distance' - self.rel_pos = None - - self.pre_norm = pre_norm - - self.residual_attn = residual_attn - self.cross_residual_attn = cross_residual_attn - - norm_class = ScaleNorm if use_scalenorm else nn.LayerNorm - norm_class = RMSNorm if use_rmsnorm else norm_class - norm_fn = partial(norm_class, dim) - - norm_fn = nn.Identity if use_rezero else norm_fn - branch_fn = Rezero if use_rezero else None - - if cross_attend and not only_cross: - default_block = ('a', 'c', 'f') - elif cross_attend and only_cross: - default_block = ('c', 'f') - else: - default_block = ('a', 'f') - - if macaron: - default_block = ('f',) + default_block - - if exists(custom_layers): - layer_types = custom_layers - elif exists(par_ratio): - par_depth = depth * len(default_block) - assert 1 < par_ratio <= par_depth, 'par ratio out of range' - default_block = tuple(filter(not_equals('f'), default_block)) - par_attn = par_depth // par_ratio - depth_cut = par_depth * 2 // 3 # 2 / 3 attention layer cutoff suggested by PAR paper - par_width = (depth_cut + depth_cut // par_attn) // par_attn - assert len(default_block) <= par_width, 'default block is too large for par_ratio' - par_block = default_block + ('f',) * (par_width - len(default_block)) - par_head = par_block * par_attn - layer_types = par_head + ('f',) * (par_depth - len(par_head)) - elif exists(sandwich_coef): - assert sandwich_coef > 0 and sandwich_coef <= depth, 'sandwich coefficient should be less than the depth' - layer_types = ('a',) * sandwich_coef + default_block * (depth - sandwich_coef) + ('f',) * sandwich_coef - else: - layer_types = default_block * depth - - self.layer_types = layer_types - self.num_attn_layers = len(list(filter(equals('a'), layer_types))) - - for layer_type in self.layer_types: - if layer_type == 'a': - layer = Attention(dim, heads=heads, causal=causal, **attn_kwargs) - elif layer_type == 'c': - layer = Attention(dim, heads=heads, **attn_kwargs) - elif layer_type == 'f': - layer = FeedForward(dim, **ff_kwargs) - layer = layer if not macaron else Scale(0.5, layer) - else: - raise Exception(f'invalid layer type {layer_type}') - - if isinstance(layer, Attention) and exists(branch_fn): - layer = branch_fn(layer) - - if gate_residual: - residual_fn = GRUGating(dim) - else: - residual_fn = Residual() - - self.layers.append(nn.ModuleList([ - norm_fn(), - layer, - residual_fn - ])) - - def forward( - self, - x, - context=None, - mask=None, - context_mask=None, - mems=None, - return_hiddens=False - ): - hiddens = [] - intermediates = [] - prev_attn = None - prev_cross_attn = None - - mems = mems.copy() if exists(mems) else [None] * self.num_attn_layers - - for ind, (layer_type, (norm, block, residual_fn)) in enumerate(zip(self.layer_types, self.layers)): - is_last = ind == (len(self.layers) - 1) - - if layer_type == 'a': - hiddens.append(x) - layer_mem = mems.pop(0) - - residual = x - - if self.pre_norm: - x = norm(x) - - if layer_type == 'a': - out, inter = block(x, mask=mask, sinusoidal_emb=self.pia_pos_emb, rel_pos=self.rel_pos, - prev_attn=prev_attn, mem=layer_mem) - elif layer_type == 'c': - out, inter = block(x, context=context, mask=mask, context_mask=context_mask, prev_attn=prev_cross_attn) - elif layer_type == 'f': - out = block(x) - - x = residual_fn(out, residual) - - if layer_type in ('a', 'c'): - intermediates.append(inter) - - if layer_type == 'a' and self.residual_attn: - prev_attn = inter.pre_softmax_attn - elif layer_type == 'c' and self.cross_residual_attn: - prev_cross_attn = inter.pre_softmax_attn - - if not self.pre_norm and not is_last: - x = norm(x) - - if return_hiddens: - intermediates = LayerIntermediates( - hiddens=hiddens, - attn_intermediates=intermediates - ) - - return x, intermediates - - return x - - -class Encoder(AttentionLayers): - def __init__(self, **kwargs): - assert 'causal' not in kwargs, 'cannot set causality on encoder' - super().__init__(causal=False, **kwargs) - - - -class TransformerWrapper(nn.Module): - def __init__( - self, - *, - num_tokens, - max_seq_len, - attn_layers, - emb_dim=None, - max_mem_len=0., - emb_dropout=0., - num_memory_tokens=None, - tie_embedding=False, - use_pos_emb=True - ): - super().__init__() - assert isinstance(attn_layers, AttentionLayers), 'attention layers must be one of Encoder or Decoder' - - dim = attn_layers.dim - emb_dim = default(emb_dim, dim) - - self.max_seq_len = max_seq_len - self.max_mem_len = max_mem_len - self.num_tokens = num_tokens - - self.token_emb = nn.Embedding(num_tokens, emb_dim) - self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) if ( - use_pos_emb and not attn_layers.has_pos_emb) else always(0) - self.emb_dropout = nn.Dropout(emb_dropout) - - self.project_emb = nn.Linear(emb_dim, dim) if emb_dim != dim else nn.Identity() - self.attn_layers = attn_layers - self.norm = nn.LayerNorm(dim) - - self.init_() - - self.to_logits = nn.Linear(dim, num_tokens) if not tie_embedding else lambda t: t @ self.token_emb.weight.t() - - # memory tokens (like [cls]) from Memory Transformers paper - num_memory_tokens = default(num_memory_tokens, 0) - self.num_memory_tokens = num_memory_tokens - if num_memory_tokens > 0: - self.memory_tokens = nn.Parameter(torch.randn(num_memory_tokens, dim)) - - # let funnel encoder know number of memory tokens, if specified - if hasattr(attn_layers, 'num_memory_tokens'): - attn_layers.num_memory_tokens = num_memory_tokens - - def init_(self): - nn.init.normal_(self.token_emb.weight, std=0.02) - - def forward( - self, - x, - return_embeddings=False, - mask=None, - return_mems=False, - return_attn=False, - mems=None, - **kwargs - ): - b, n, device, num_mem = *x.shape, x.device, self.num_memory_tokens - x = self.token_emb(x) - x += self.pos_emb(x) - x = self.emb_dropout(x) - - x = self.project_emb(x) - - if num_mem > 0: - mem = repeat(self.memory_tokens, 'n d -> b n d', b=b) - x = torch.cat((mem, x), dim=1) - - # auto-handle masking after appending memory tokens - if exists(mask): - mask = F.pad(mask, (num_mem, 0), value=True) - - x, intermediates = self.attn_layers(x, mask=mask, mems=mems, return_hiddens=True, **kwargs) - x = self.norm(x) - - mem, x = x[:, :num_mem], x[:, num_mem:] - - out = self.to_logits(x) if not return_embeddings else x - - if return_mems: - hiddens = intermediates.hiddens - new_mems = list(map(lambda pair: torch.cat(pair, dim=-2), zip(mems, hiddens))) if exists(mems) else hiddens - new_mems = list(map(lambda t: t[..., -self.max_mem_len:, :].detach(), new_mems)) - return out, new_mems - - if return_attn: - attn_maps = list(map(lambda t: t.post_softmax_attn, intermediates.attn_intermediates)) - return out, attn_maps - - return out - diff --git a/spaces/arch-123/bingo/src/components/chat-list.tsx b/spaces/arch-123/bingo/src/components/chat-list.tsx deleted file mode 100644 index 624a78ef0d7be0f1192cf02a81e2e9cf214cb193..0000000000000000000000000000000000000000 --- a/spaces/arch-123/bingo/src/components/chat-list.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import React from 'react' - -import { Separator } from '@/components/ui/separator' -import { ChatMessage } from '@/components/chat-message' -import { ChatMessageModel } from '@/lib/bots/bing/types' - -export interface ChatList { - messages: ChatMessageModel[] -} - -export function ChatList({ messages }: ChatList) { - if (!messages.length) { - return null - } - - return ( -
- {messages.map((message, index) => ( - - - {index < messages.length - 1 && ( - - )} - - ))} -
- ) -} diff --git a/spaces/arch-123/bingo/src/components/header.tsx b/spaces/arch-123/bingo/src/components/header.tsx deleted file mode 100644 index dc298b722154d1ac6d7a7e148204605562d6cc58..0000000000000000000000000000000000000000 --- a/spaces/arch-123/bingo/src/components/header.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as React from 'react' -import { UserMenu } from './user-menu' - -export async function Header() { - return ( -
-
- -
-
- ) -} diff --git a/spaces/artificialguybr/video-dubbing/TTS/TTS/vc/modules/freevc/wavlm/__init__.py b/spaces/artificialguybr/video-dubbing/TTS/TTS/vc/modules/freevc/wavlm/__init__.py deleted file mode 100644 index 6edada407b2210b5b99f6628e4f765a24c4d3dcb..0000000000000000000000000000000000000000 --- a/spaces/artificialguybr/video-dubbing/TTS/TTS/vc/modules/freevc/wavlm/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -import os -import urllib.request - -import torch - -from TTS.utils.generic_utils import get_user_data_dir -from TTS.vc.modules.freevc.wavlm.wavlm import WavLM, WavLMConfig - -model_uri = "https://github.com/coqui-ai/TTS/releases/download/v0.13.0_models/WavLM-Large.pt" - - -def get_wavlm(device="cpu"): - """Download the model and return the model object.""" - - output_path = get_user_data_dir("tts") - - output_path = os.path.join(output_path, "wavlm") - if not os.path.exists(output_path): - os.makedirs(output_path) - - output_path = os.path.join(output_path, "WavLM-Large.pt") - if not os.path.exists(output_path): - print(f" > Downloading WavLM model to {output_path} ...") - urllib.request.urlretrieve(model_uri, output_path) - - checkpoint = torch.load(output_path, map_location=torch.device(device)) - cfg = WavLMConfig(checkpoint["cfg"]) - wavlm = WavLM(cfg).to(device) - wavlm.load_state_dict(checkpoint["model"]) - wavlm.eval() - return wavlm - - -if __name__ == "__main__": - wavlm = get_wavlm() diff --git a/spaces/artificialguybr/video-dubbing/whisper/README.md b/spaces/artificialguybr/video-dubbing/whisper/README.md deleted file mode 100644 index 20532574c3fa8060f24f6e8f2362e695368db03b..0000000000000000000000000000000000000000 --- a/spaces/artificialguybr/video-dubbing/whisper/README.md +++ /dev/null @@ -1,147 +0,0 @@ -# Whisper - -[[Blog]](https://openai.com/blog/whisper) -[[Paper]](https://arxiv.org/abs/2212.04356) -[[Model card]](https://github.com/openai/whisper/blob/main/model-card.md) -[[Colab example]](https://colab.research.google.com/github/openai/whisper/blob/master/notebooks/LibriSpeech.ipynb) - -Whisper is a general-purpose speech recognition model. It is trained on a large dataset of diverse audio and is also a multitasking model that can perform multilingual speech recognition, speech translation, and language identification. - - -## Approach - -![Approach](https://raw.githubusercontent.com/openai/whisper/main/approach.png) - -A Transformer sequence-to-sequence model is trained on various speech processing tasks, including multilingual speech recognition, speech translation, spoken language identification, and voice activity detection. These tasks are jointly represented as a sequence of tokens to be predicted by the decoder, allowing a single model to replace many stages of a traditional speech-processing pipeline. The multitask training format uses a set of special tokens that serve as task specifiers or classification targets. - - -## Setup - -We used Python 3.9.9 and [PyTorch](https://pytorch.org/) 1.10.1 to train and test our models, but the codebase is expected to be compatible with Python 3.8-3.11 and recent PyTorch versions. The codebase also depends on a few Python packages, most notably [OpenAI's tiktoken](https://github.com/openai/tiktoken) for their fast tokenizer implementation. You can download and install (or update to) the latest release of Whisper with the following command: - - pip install -U openai-whisper - -Alternatively, the following command will pull and install the latest commit from this repository, along with its Python dependencies: - - pip install git+https://github.com/openai/whisper.git - -To update the package to the latest version of this repository, please run: - - pip install --upgrade --no-deps --force-reinstall git+https://github.com/openai/whisper.git - -It also requires the command-line tool [`ffmpeg`](https://ffmpeg.org/) to be installed on your system, which is available from most package managers: - -```bash -# on Ubuntu or Debian -sudo apt update && sudo apt install ffmpeg - -# on Arch Linux -sudo pacman -S ffmpeg - -# on MacOS using Homebrew (https://brew.sh/) -brew install ffmpeg - -# on Windows using Chocolatey (https://chocolatey.org/) -choco install ffmpeg - -# on Windows using Scoop (https://scoop.sh/) -scoop install ffmpeg -``` - -You may need [`rust`](http://rust-lang.org) installed as well, in case [tiktoken](https://github.com/openai/tiktoken) does not provide a pre-built wheel for your platform. If you see installation errors during the `pip install` command above, please follow the [Getting started page](https://www.rust-lang.org/learn/get-started) to install Rust development environment. Additionally, you may need to configure the `PATH` environment variable, e.g. `export PATH="$HOME/.cargo/bin:$PATH"`. If the installation fails with `No module named 'setuptools_rust'`, you need to install `setuptools_rust`, e.g. by running: - -```bash -pip install setuptools-rust -``` - - -## Available models and languages - -There are five model sizes, four with English-only versions, offering speed and accuracy tradeoffs. Below are the names of the available models and their approximate memory requirements and relative speed. - - -| Size | Parameters | English-only model | Multilingual model | Required VRAM | Relative speed | -|:------:|:----------:|:------------------:|:------------------:|:-------------:|:--------------:| -| tiny | 39 M | `tiny.en` | `tiny` | ~1 GB | ~32x | -| base | 74 M | `base.en` | `base` | ~1 GB | ~16x | -| small | 244 M | `small.en` | `small` | ~2 GB | ~6x | -| medium | 769 M | `medium.en` | `medium` | ~5 GB | ~2x | -| large | 1550 M | N/A | `large` | ~10 GB | 1x | - -The `.en` models for English-only applications tend to perform better, especially for the `tiny.en` and `base.en` models. We observed that the difference becomes less significant for the `small.en` and `medium.en` models. - -Whisper's performance varies widely depending on the language. The figure below shows a WER (Word Error Rate) breakdown by languages of the Fleurs dataset using the `large-v2` model (The smaller the numbers, the better the performance). Additional WER scores corresponding to the other models and datasets can be found in Appendix D.1, D.2, and D.4. Meanwhile, more BLEU (Bilingual Evaluation Understudy) scores can be found in Appendix D.3. Both are found in [the paper](https://arxiv.org/abs/2212.04356). - -![WER breakdown by language](https://raw.githubusercontent.com/openai/whisper/main/language-breakdown.svg) - - - -## Command-line usage - -The following command will transcribe speech in audio files, using the `medium` model: - - whisper audio.flac audio.mp3 audio.wav --model medium - -The default setting (which selects the `small` model) works well for transcribing English. To transcribe an audio file containing non-English speech, you can specify the language using the `--language` option: - - whisper japanese.wav --language Japanese - -Adding `--task translate` will translate the speech into English: - - whisper japanese.wav --language Japanese --task translate - -Run the following to view all available options: - - whisper --help - -See [tokenizer.py](https://github.com/openai/whisper/blob/main/whisper/tokenizer.py) for the list of all available languages. - - -## Python usage - -Transcription can also be performed within Python: - -```python -import whisper - -model = whisper.load_model("base") -result = model.transcribe("audio.mp3") -print(result["text"]) -``` - -Internally, the `transcribe()` method reads the entire file and processes the audio with a sliding 30-second window, performing autoregressive sequence-to-sequence predictions on each window. - -Below is an example usage of `whisper.detect_language()` and `whisper.decode()` which provide lower-level access to the model. - -```python -import whisper - -model = whisper.load_model("base") - -# load audio and pad/trim it to fit 30 seconds -audio = whisper.load_audio("audio.mp3") -audio = whisper.pad_or_trim(audio) - -# make log-Mel spectrogram and move to the same device as the model -mel = whisper.log_mel_spectrogram(audio).to(model.device) - -# detect the spoken language -_, probs = model.detect_language(mel) -print(f"Detected language: {max(probs, key=probs.get)}") - -# decode the audio -options = whisper.DecodingOptions() -result = whisper.decode(model, mel, options) - -# print the recognized text -print(result.text) -``` - -## More examples - -Please use the [🙌 Show and tell](https://github.com/openai/whisper/discussions/categories/show-and-tell) category in Discussions for sharing more example usages of Whisper and third-party extensions such as web demos, integrations with other tools, ports for different platforms, etc. - - -## License - -Whisper's code and model weights are released under the MIT License. See [LICENSE](https://github.com/openai/whisper/blob/main/LICENSE) for further details. diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/Hash/SHA512.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/Hash/SHA512.py deleted file mode 100644 index 403fe45e3281ab8280219604a60df2027490fb6a..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Crypto/Hash/SHA512.py +++ /dev/null @@ -1,204 +0,0 @@ -# -*- coding: utf-8 -*- -# -# =================================================================== -# The contents of this file are dedicated to the public domain. To -# the extent that dedication to the public domain is not available, -# everyone is granted a worldwide, perpetual, royalty-free, -# non-exclusive license to exercise all rights associated with the -# contents of this file for any purpose whatsoever. -# No rights are reserved. -# -# 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. -# =================================================================== - -from Crypto.Util.py3compat import bord - -from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, - VoidPointer, SmartPointer, - create_string_buffer, - get_raw_buffer, c_size_t, - c_uint8_ptr) - -_raw_sha512_lib = load_pycryptodome_raw_lib("Crypto.Hash._SHA512", - """ - int SHA512_init(void **shaState, - size_t digest_size); - int SHA512_destroy(void *shaState); - int SHA512_update(void *hs, - const uint8_t *buf, - size_t len); - int SHA512_digest(const void *shaState, - uint8_t *digest, - size_t digest_size); - int SHA512_copy(const void *src, void *dst); - - int SHA512_pbkdf2_hmac_assist(const void *inner, - const void *outer, - const uint8_t *first_digest, - uint8_t *final_digest, - size_t iterations, - size_t digest_size); - """) - -class SHA512Hash(object): - """A SHA-512 hash object (possibly in its truncated version SHA-512/224 or - SHA-512/256. - Do not instantiate directly. Use the :func:`new` function. - - :ivar oid: ASN.1 Object ID - :vartype oid: string - - :ivar block_size: the size in bytes of the internal message block, - input to the compression function - :vartype block_size: integer - - :ivar digest_size: the size in bytes of the resulting hash - :vartype digest_size: integer - """ - - # The internal block size of the hash algorithm in bytes. - block_size = 128 - - def __init__(self, data, truncate): - self._truncate = truncate - - if truncate is None: - self.oid = "2.16.840.1.101.3.4.2.3" - self.digest_size = 64 - elif truncate == "224": - self.oid = "2.16.840.1.101.3.4.2.5" - self.digest_size = 28 - elif truncate == "256": - self.oid = "2.16.840.1.101.3.4.2.6" - self.digest_size = 32 - else: - raise ValueError("Incorrect truncation length. It must be '224' or '256'.") - - state = VoidPointer() - result = _raw_sha512_lib.SHA512_init(state.address_of(), - c_size_t(self.digest_size)) - if result: - raise ValueError("Error %d while instantiating SHA-512" - % result) - self._state = SmartPointer(state.get(), - _raw_sha512_lib.SHA512_destroy) - if data: - self.update(data) - - def update(self, data): - """Continue hashing of a message by consuming the next chunk of data. - - Args: - data (byte string/byte array/memoryview): The next chunk of the message being hashed. - """ - - result = _raw_sha512_lib.SHA512_update(self._state.get(), - c_uint8_ptr(data), - c_size_t(len(data))) - if result: - raise ValueError("Error %d while hashing data with SHA512" - % result) - - def digest(self): - """Return the **binary** (non-printable) digest of the message that has been hashed so far. - - :return: The hash digest, computed over the data processed so far. - Binary form. - :rtype: byte string - """ - - bfr = create_string_buffer(self.digest_size) - result = _raw_sha512_lib.SHA512_digest(self._state.get(), - bfr, - c_size_t(self.digest_size)) - if result: - raise ValueError("Error %d while making SHA512 digest" - % result) - - return get_raw_buffer(bfr) - - def hexdigest(self): - """Return the **printable** digest of the message that has been hashed so far. - - :return: The hash digest, computed over the data processed so far. - Hexadecimal encoded. - :rtype: string - """ - - return "".join(["%02x" % bord(x) for x in self.digest()]) - - def copy(self): - """Return a copy ("clone") of the hash object. - - The copy will have the same internal state as the original hash - object. - This can be used to efficiently compute the digests of strings that - share a common initial substring. - - :return: A hash object of the same type - """ - - clone = SHA512Hash(None, self._truncate) - result = _raw_sha512_lib.SHA512_copy(self._state.get(), - clone._state.get()) - if result: - raise ValueError("Error %d while copying SHA512" % result) - return clone - - def new(self, data=None): - """Create a fresh SHA-512 hash object.""" - - return SHA512Hash(data, self._truncate) - - -def new(data=None, truncate=None): - """Create a new hash object. - - Args: - data (bytes/bytearray/memoryview): - Optional. The very first chunk of the message to hash. - It is equivalent to an early call to :meth:`SHA512Hash.update`. - truncate (string): - Optional. The desired length of the digest. It can be either "224" or - "256". If not present, the digest is 512 bits long. - Passing this parameter is **not** equivalent to simply truncating - the output digest. - - :Return: A :class:`SHA512Hash` hash object - """ - - return SHA512Hash(data, truncate) - - -# The size of the full SHA-512 hash in bytes. -digest_size = 64 - -# The internal block size of the hash algorithm in bytes. -block_size = 128 - - -def _pbkdf2_hmac_assist(inner, outer, first_digest, iterations): - """Compute the expensive inner loop in PBKDF-HMAC.""" - - assert iterations > 0 - - bfr = create_string_buffer(len(first_digest)); - result = _raw_sha512_lib.SHA512_pbkdf2_hmac_assist( - inner._state.get(), - outer._state.get(), - first_digest, - bfr, - c_size_t(iterations), - c_size_t(len(first_digest))) - - if result: - raise ValueError("Error %d with PBKDF2-HMAC assist for SHA512" % result) - - return get_raw_buffer(bfr) diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Compiler/ModuleNode.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Compiler/ModuleNode.py deleted file mode 100644 index f89af8ca5db64cfa004bad5df6e0b5b7b15d2443..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/Cython/Compiler/ModuleNode.py +++ /dev/null @@ -1,3222 +0,0 @@ -# -# Module parse tree node -# - -from __future__ import absolute_import - -import cython -cython.declare(Naming=object, Options=object, PyrexTypes=object, TypeSlots=object, - error=object, warning=object, py_object_type=object, UtilityCode=object, - EncodedString=object, re=object) - -from collections import defaultdict -import json -import operator -import os -import re - -from .PyrexTypes import CPtrType -from . import Future -from . import Annotate -from . import Code -from . import Naming -from . import Nodes -from . import Options -from . import TypeSlots -from . import PyrexTypes -from . import Pythran - -from .Errors import error, warning -from .PyrexTypes import py_object_type -from ..Utils import open_new_file, replace_suffix, decode_filename, build_hex_version -from .Code import UtilityCode, IncludeCode -from .StringEncoding import EncodedString -from .Pythran import has_np_pythran - -def check_c_declarations_pxd(module_node): - module_node.scope.check_c_classes_pxd() - return module_node - - -def check_c_declarations(module_node): - module_node.scope.check_c_classes() - module_node.scope.check_c_functions() - return module_node - - -def generate_c_code_config(env, options): - if Options.annotate or options.annotate: - emit_linenums = False - else: - emit_linenums = options.emit_linenums - - return Code.CCodeConfig( - emit_linenums=emit_linenums, - emit_code_comments=env.directives['emit_code_comments'], - c_line_in_traceback=options.c_line_in_traceback) - - -class ModuleNode(Nodes.Node, Nodes.BlockNode): - # doc string or None - # body StatListNode - # - # referenced_modules [ModuleScope] - # full_module_name string - # - # scope The module scope. - # compilation_source A CompilationSource (see Main) - # directives Top-level compiler directives - - child_attrs = ["body"] - directives = None - - def merge_in(self, tree, scope, merge_scope=False): - # Merges in the contents of another tree, and possibly scope. With the - # current implementation below, this must be done right prior - # to code generation. - # - # Note: This way of doing it seems strange -- I believe the - # right concept is to split ModuleNode into a ModuleNode and a - # CodeGenerator, and tell that CodeGenerator to generate code - # from multiple sources. - assert isinstance(self.body, Nodes.StatListNode) - if isinstance(tree, Nodes.StatListNode): - self.body.stats.extend(tree.stats) - else: - self.body.stats.append(tree) - - self.scope.utility_code_list.extend(scope.utility_code_list) - - for inc in scope.c_includes.values(): - self.scope.process_include(inc) - - def extend_if_not_in(L1, L2): - for x in L2: - if x not in L1: - L1.append(x) - - extend_if_not_in(self.scope.included_files, scope.included_files) - - if merge_scope: - # Ensure that we don't generate import code for these entries! - for entry in scope.c_class_entries: - entry.type.module_name = self.full_module_name - entry.type.scope.directives["internal"] = True - - self.scope.merge_in(scope) - - def analyse_declarations(self, env): - if has_np_pythran(env): - Pythran.include_pythran_generic(env) - if self.directives: - env.old_style_globals = self.directives['old_style_globals'] - if not Options.docstrings: - env.doc = self.doc = None - elif Options.embed_pos_in_docstring: - env.doc = EncodedString(u'File: %s (starting at line %s)' % Nodes.relative_position(self.pos)) - if self.doc is not None: - env.doc = EncodedString(env.doc + u'\n' + self.doc) - env.doc.encoding = self.doc.encoding - else: - env.doc = self.doc - env.directives = self.directives - - self.body.analyse_declarations(env) - - def prepare_utility_code(self): - # prepare any utility code that must be created before code generation - # specifically: CythonUtilityCode - env = self.scope - if env.has_import_star: - self.create_import_star_conversion_utility_code(env) - for name, entry in sorted(env.entries.items()): - if (entry.create_wrapper and entry.scope is env - and entry.is_type and entry.type.is_enum): - entry.type.create_type_wrapper(env) - - def process_implementation(self, options, result): - env = self.scope - env.return_type = PyrexTypes.c_void_type - self.referenced_modules = [] - self.find_referenced_modules(env, self.referenced_modules, {}) - self.sort_cdef_classes(env) - self.generate_c_code(env, options, result) - self.generate_h_code(env, options, result) - self.generate_api_code(env, options, result) - - def has_imported_c_functions(self): - for module in self.referenced_modules: - for entry in module.cfunc_entries: - if entry.defined_in_pxd: - return 1 - return 0 - - def generate_h_code(self, env, options, result): - def h_entries(entries, api=0, pxd=0): - return [entry for entry in entries - if ((entry.visibility == 'public') or - (api and entry.api) or - (pxd and entry.defined_in_pxd))] - h_types = h_entries(env.type_entries, api=1) - h_vars = h_entries(env.var_entries) - h_funcs = h_entries(env.cfunc_entries) - h_extension_types = h_entries(env.c_class_entries) - if h_types or h_vars or h_funcs or h_extension_types: - result.h_file = replace_suffix(result.c_file, ".h") - h_code = Code.CCodeWriter() - c_code_config = generate_c_code_config(env, options) - Code.GlobalState(h_code, self, c_code_config) - if options.generate_pxi: - result.i_file = replace_suffix(result.c_file, ".pxi") - i_code = Code.PyrexCodeWriter(result.i_file) - else: - i_code = None - - h_code.put_generated_by() - h_guard = Naming.h_guard_prefix + self.api_name(env) - h_code.put_h_guard(h_guard) - h_code.putln("") - h_code.putln('#include "Python.h"') - self.generate_type_header_code(h_types, h_code) - if options.capi_reexport_cincludes: - self.generate_includes(env, [], h_code) - h_code.putln("") - api_guard = Naming.api_guard_prefix + self.api_name(env) - h_code.putln("#ifndef %s" % api_guard) - h_code.putln("") - self.generate_extern_c_macro_definition(h_code) - h_code.putln("") - self.generate_dl_import_macro(h_code) - if h_extension_types: - h_code.putln("") - for entry in h_extension_types: - self.generate_cclass_header_code(entry.type, h_code) - if i_code: - self.generate_cclass_include_code(entry.type, i_code) - if h_funcs: - h_code.putln("") - for entry in h_funcs: - self.generate_public_declaration(entry, h_code, i_code) - if h_vars: - h_code.putln("") - for entry in h_vars: - self.generate_public_declaration(entry, h_code, i_code) - h_code.putln("") - h_code.putln("#endif /* !%s */" % api_guard) - h_code.putln("") - h_code.putln("/* WARNING: the interface of the module init function changed in CPython 3.5. */") - h_code.putln("/* It now returns a PyModuleDef instance instead of a PyModule instance. */") - h_code.putln("") - h_code.putln("#if PY_MAJOR_VERSION < 3") - h_code.putln("PyMODINIT_FUNC init%s(void);" % env.module_name) - h_code.putln("#else") - h_code.putln("PyMODINIT_FUNC %s(void);" % self.mod_init_func_cname('PyInit', env)) - h_code.putln("#endif") - h_code.putln("") - h_code.putln("#endif /* !%s */" % h_guard) - - f = open_new_file(result.h_file) - try: - h_code.copyto(f) - finally: - f.close() - - def generate_public_declaration(self, entry, h_code, i_code): - h_code.putln("%s %s;" % ( - Naming.extern_c_macro, - entry.type.declaration_code(entry.cname))) - if i_code: - i_code.putln("cdef extern %s" % ( - entry.type.declaration_code(entry.cname, pyrex=1))) - - def api_name(self, env): - return env.qualified_name.replace(".", "__") - - def generate_api_code(self, env, options, result): - def api_entries(entries, pxd=0): - return [entry for entry in entries - if entry.api or (pxd and entry.defined_in_pxd)] - api_vars = api_entries(env.var_entries) - api_funcs = api_entries(env.cfunc_entries) - api_extension_types = api_entries(env.c_class_entries) - if api_vars or api_funcs or api_extension_types: - result.api_file = replace_suffix(result.c_file, "_api.h") - h_code = Code.CCodeWriter() - c_code_config = generate_c_code_config(env, options) - Code.GlobalState(h_code, self, c_code_config) - h_code.put_generated_by() - api_guard = Naming.api_guard_prefix + self.api_name(env) - h_code.put_h_guard(api_guard) - # Work around https://bugs.python.org/issue4709 - h_code.putln('#ifdef __MINGW64__') - h_code.putln('#define MS_WIN64') - h_code.putln('#endif') - - h_code.putln('#include "Python.h"') - if result.h_file: - h_code.putln('#include "%s"' % os.path.basename(result.h_file)) - if api_extension_types: - h_code.putln("") - for entry in api_extension_types: - type = entry.type - h_code.putln("static PyTypeObject *%s = 0;" % type.typeptr_cname) - h_code.putln("#define %s (*%s)" % ( - type.typeobj_cname, type.typeptr_cname)) - if api_funcs: - h_code.putln("") - for entry in api_funcs: - type = CPtrType(entry.type) - cname = env.mangle(Naming.func_prefix_api, entry.name) - h_code.putln("static %s = 0;" % type.declaration_code(cname)) - h_code.putln("#define %s %s" % (entry.name, cname)) - if api_vars: - h_code.putln("") - for entry in api_vars: - type = CPtrType(entry.type) - cname = env.mangle(Naming.varptr_prefix_api, entry.name) - h_code.putln("static %s = 0;" % type.declaration_code(cname)) - h_code.putln("#define %s (*%s)" % (entry.name, cname)) - h_code.put(UtilityCode.load_as_string("PyIdentifierFromString", "ImportExport.c")[0]) - if api_vars: - h_code.put(UtilityCode.load_as_string("VoidPtrImport", "ImportExport.c")[1]) - if api_funcs: - h_code.put(UtilityCode.load_as_string("FunctionImport", "ImportExport.c")[1]) - if api_extension_types: - h_code.put(UtilityCode.load_as_string("TypeImport", "ImportExport.c")[0]) - h_code.put(UtilityCode.load_as_string("TypeImport", "ImportExport.c")[1]) - h_code.putln("") - h_code.putln("static int import_%s(void) {" % self.api_name(env)) - h_code.putln("PyObject *module = 0;") - h_code.putln('module = PyImport_ImportModule("%s");' % env.qualified_name) - h_code.putln("if (!module) goto bad;") - for entry in api_funcs: - cname = env.mangle(Naming.func_prefix_api, entry.name) - sig = entry.type.signature_string() - h_code.putln( - 'if (__Pyx_ImportFunction(module, "%s", (void (**)(void))&%s, "%s") < 0) goto bad;' - % (entry.name, cname, sig)) - for entry in api_vars: - cname = env.mangle(Naming.varptr_prefix_api, entry.name) - sig = entry.type.empty_declaration_code() - h_code.putln( - 'if (__Pyx_ImportVoidPtr(module, "%s", (void **)&%s, "%s") < 0) goto bad;' - % (entry.name, cname, sig)) - with ModuleImportGenerator(h_code, imported_modules={env.qualified_name: 'module'}) as import_generator: - for entry in api_extension_types: - self.generate_type_import_call(entry.type, h_code, import_generator, error_code="goto bad;") - h_code.putln("Py_DECREF(module); module = 0;") - h_code.putln("return 0;") - h_code.putln("bad:") - h_code.putln("Py_XDECREF(module);") - h_code.putln("return -1;") - h_code.putln("}") - h_code.putln("") - h_code.putln("#endif /* !%s */" % api_guard) - - f = open_new_file(result.api_file) - try: - h_code.copyto(f) - finally: - f.close() - - def generate_cclass_header_code(self, type, h_code): - h_code.putln("%s %s %s;" % ( - Naming.extern_c_macro, - PyrexTypes.public_decl("PyTypeObject", "DL_IMPORT"), - type.typeobj_cname)) - - def generate_cclass_include_code(self, type, i_code): - i_code.putln("cdef extern class %s.%s:" % ( - type.module_name, type.name)) - i_code.indent() - var_entries = type.scope.var_entries - if var_entries: - for entry in var_entries: - i_code.putln("cdef %s" % ( - entry.type.declaration_code(entry.cname, pyrex=1))) - else: - i_code.putln("pass") - i_code.dedent() - - def generate_c_code(self, env, options, result): - modules = self.referenced_modules - - if Options.annotate or options.annotate: - rootwriter = Annotate.AnnotationCCodeWriter() - else: - rootwriter = Code.CCodeWriter() - - c_code_config = generate_c_code_config(env, options) - - globalstate = Code.GlobalState( - rootwriter, self, - code_config=c_code_config, - common_utility_include_dir=options.common_utility_include_dir, - ) - globalstate.initialize_main_c_code() - h_code = globalstate['h_code'] - - self.generate_module_preamble(env, options, modules, result.embedded_metadata, h_code) - - globalstate.module_pos = self.pos - globalstate.directives = self.directives - - globalstate.use_utility_code(refnanny_utility_code) - - code = globalstate['before_global_var'] - code.putln('#define __Pyx_MODULE_NAME "%s"' % self.full_module_name) - module_is_main = "%s%s" % (Naming.module_is_main, self.full_module_name.replace('.', '__')) - code.putln("extern int %s;" % module_is_main) - code.putln("int %s = 0;" % module_is_main) - code.putln("") - code.putln("/* Implementation of '%s' */" % env.qualified_name) - - code = globalstate['late_includes'] - code.putln("/* Late includes */") - self.generate_includes(env, modules, code, early=False) - - code = globalstate['all_the_rest'] - - self.generate_cached_builtins_decls(env, code) - self.generate_lambda_definitions(env, code) - # generate normal variable and function definitions - self.generate_variable_definitions(env, code) - - self.body.generate_function_definitions(env, code) - - code.mark_pos(None) - self.generate_typeobj_definitions(env, code) - self.generate_method_table(env, code) - if env.has_import_star: - self.generate_import_star(env, code) - self.generate_pymoduledef_struct(env, code) - - # initialise the macro to reduce the code size of one-time functionality - code.putln(UtilityCode.load_as_string("SmallCodeConfig", "ModuleSetupCode.c")[0].strip()) - - # init_globals is inserted before this - self.generate_module_init_func(modules[:-1], env, globalstate['init_module']) - self.generate_module_cleanup_func(env, globalstate['cleanup_module']) - if Options.embed: - self.generate_main_method(env, globalstate['main_method']) - self.generate_filename_table(globalstate['filename_table']) - - self.generate_declarations_for_modules(env, modules, globalstate) - h_code.write('\n') - - for utilcode in env.utility_code_list[:]: - globalstate.use_utility_code(utilcode) - globalstate.finalize_main_c_code() - - f = open_new_file(result.c_file) - try: - rootwriter.copyto(f) - finally: - f.close() - result.c_file_generated = 1 - if options.gdb_debug: - self._serialize_lineno_map(env, rootwriter) - if Options.annotate or options.annotate: - self._generate_annotations(rootwriter, result, options) - - def _generate_annotations(self, rootwriter, result, options): - self.annotate(rootwriter) - - coverage_xml_filename = Options.annotate_coverage_xml or options.annotate_coverage_xml - if coverage_xml_filename and os.path.exists(coverage_xml_filename): - try: - import xml.etree.cElementTree as ET - except ImportError: - import xml.etree.ElementTree as ET - coverage_xml = ET.parse(coverage_xml_filename).getroot() - if hasattr(coverage_xml, 'iter'): - iterator = coverage_xml.iter() # Python 2.7 & 3.2+ - else: - iterator = coverage_xml.getiterator() - for el in iterator: - el.tail = None # save some memory - else: - coverage_xml = None - - rootwriter.save_annotation(result.main_source_file, result.c_file, coverage_xml=coverage_xml) - - # if we included files, additionally generate one annotation file for each - if not self.scope.included_files: - return - - search_include_file = self.scope.context.search_include_directories - target_dir = os.path.abspath(os.path.dirname(result.c_file)) - for included_file in self.scope.included_files: - target_file = os.path.abspath(os.path.join(target_dir, included_file)) - target_file_dir = os.path.dirname(target_file) - if not target_file_dir.startswith(target_dir): - # any other directories may not be writable => avoid trying - continue - source_file = search_include_file(included_file, "", self.pos, include=True) - if not source_file: - continue - if target_file_dir != target_dir and not os.path.exists(target_file_dir): - try: - os.makedirs(target_file_dir) - except OSError as e: - import errno - if e.errno != errno.EEXIST: - raise - rootwriter.save_annotation(source_file, target_file, coverage_xml=coverage_xml) - - def _serialize_lineno_map(self, env, ccodewriter): - tb = env.context.gdb_debug_outputwriter - markers = ccodewriter.buffer.allmarkers() - - d = defaultdict(list) - for c_lineno, cython_lineno in enumerate(markers): - if cython_lineno > 0: - d[cython_lineno].append(c_lineno + 1) - - tb.start('LineNumberMapping') - for cython_lineno, c_linenos in sorted(d.items()): - tb.add_entry( - 'LineNumber', - c_linenos=' '.join(map(str, c_linenos)), - cython_lineno=str(cython_lineno), - ) - tb.end('LineNumberMapping') - tb.serialize() - - def find_referenced_modules(self, env, module_list, modules_seen): - if env not in modules_seen: - modules_seen[env] = 1 - for imported_module in env.cimported_modules: - self.find_referenced_modules(imported_module, module_list, modules_seen) - module_list.append(env) - - def sort_types_by_inheritance(self, type_dict, type_order, getkey): - # copy the types into a list moving each parent type before - # its first child - type_list = [] - for i, key in enumerate(type_order): - new_entry = type_dict[key] - - # collect all base classes to check for children - hierarchy = set() - base = new_entry - while base: - base_type = base.type.base_type - if not base_type: - break - base_key = getkey(base_type) - hierarchy.add(base_key) - base = type_dict.get(base_key) - new_entry.base_keys = hierarchy - - # find the first (sub-)subclass and insert before that - for j in range(i): - entry = type_list[j] - if key in entry.base_keys: - type_list.insert(j, new_entry) - break - else: - type_list.append(new_entry) - return type_list - - def sort_type_hierarchy(self, module_list, env): - # poor developer's OrderedDict - vtab_dict, vtab_dict_order = {}, [] - vtabslot_dict, vtabslot_dict_order = {}, [] - - for module in module_list: - for entry in module.c_class_entries: - if entry.used and not entry.in_cinclude: - type = entry.type - key = type.vtabstruct_cname - if not key: - continue - if key in vtab_dict: - # FIXME: this should *never* happen, but apparently it does - # for Cython generated utility code - from .UtilityCode import NonManglingModuleScope - assert isinstance(entry.scope, NonManglingModuleScope), str(entry.scope) - assert isinstance(vtab_dict[key].scope, NonManglingModuleScope), str(vtab_dict[key].scope) - else: - vtab_dict[key] = entry - vtab_dict_order.append(key) - all_defined_here = module is env - for entry in module.type_entries: - if entry.used and (all_defined_here or entry.defined_in_pxd): - type = entry.type - if type.is_extension_type and not entry.in_cinclude: - type = entry.type - key = type.objstruct_cname - assert key not in vtabslot_dict, key - vtabslot_dict[key] = entry - vtabslot_dict_order.append(key) - - def vtabstruct_cname(entry_type): - return entry_type.vtabstruct_cname - vtab_list = self.sort_types_by_inheritance( - vtab_dict, vtab_dict_order, vtabstruct_cname) - - def objstruct_cname(entry_type): - return entry_type.objstruct_cname - vtabslot_list = self.sort_types_by_inheritance( - vtabslot_dict, vtabslot_dict_order, objstruct_cname) - - return (vtab_list, vtabslot_list) - - def sort_cdef_classes(self, env): - key_func = operator.attrgetter('objstruct_cname') - entry_dict, entry_order = {}, [] - for entry in env.c_class_entries: - key = key_func(entry.type) - assert key not in entry_dict, key - entry_dict[key] = entry - entry_order.append(key) - env.c_class_entries[:] = self.sort_types_by_inheritance( - entry_dict, entry_order, key_func) - - def generate_type_definitions(self, env, modules, vtab_list, vtabslot_list, code): - # TODO: Why are these separated out? - for entry in vtabslot_list: - self.generate_objstruct_predeclaration(entry.type, code) - vtabslot_entries = set(vtabslot_list) - ctuple_names = set() - for module in modules: - definition = module is env - type_entries = [] - for entry in module.type_entries: - if entry.type.is_ctuple and entry.used: - if entry.name not in ctuple_names: - ctuple_names.add(entry.name) - type_entries.append(entry) - elif definition or entry.defined_in_pxd: - type_entries.append(entry) - type_entries = [t for t in type_entries if t not in vtabslot_entries] - self.generate_type_header_code(type_entries, code) - for entry in vtabslot_list: - self.generate_objstruct_definition(entry.type, code) - self.generate_typeobj_predeclaration(entry, code) - for entry in vtab_list: - self.generate_typeobj_predeclaration(entry, code) - self.generate_exttype_vtable_struct(entry, code) - self.generate_exttype_vtabptr_declaration(entry, code) - self.generate_exttype_final_methods_declaration(entry, code) - - def generate_declarations_for_modules(self, env, modules, globalstate): - typecode = globalstate['type_declarations'] - typecode.putln("") - typecode.putln("/*--- Type declarations ---*/") - # This is to work around the fact that array.h isn't part of the C-API, - # but we need to declare it earlier than utility code. - if 'cpython.array' in [m.qualified_name for m in modules]: - typecode.putln('#ifndef _ARRAYARRAY_H') - typecode.putln('struct arrayobject;') - typecode.putln('typedef struct arrayobject arrayobject;') - typecode.putln('#endif') - vtab_list, vtabslot_list = self.sort_type_hierarchy(modules, env) - self.generate_type_definitions( - env, modules, vtab_list, vtabslot_list, typecode) - modulecode = globalstate['module_declarations'] - for module in modules: - defined_here = module is env - modulecode.putln("") - modulecode.putln("/* Module declarations from '%s' */" % module.qualified_name) - self.generate_c_class_declarations(module, modulecode, defined_here) - self.generate_cvariable_declarations(module, modulecode, defined_here) - self.generate_cfunction_declarations(module, modulecode, defined_here) - - def _put_setup_code(self, code, name): - code.put(UtilityCode.load_as_string(name, "ModuleSetupCode.c")[1]) - - def generate_module_preamble(self, env, options, cimported_modules, metadata, code): - code.put_generated_by() - if metadata: - code.putln("/* BEGIN: Cython Metadata") - code.putln(json.dumps(metadata, indent=4, sort_keys=True)) - code.putln("END: Cython Metadata */") - code.putln("") - - code.putln("#ifndef PY_SSIZE_T_CLEAN") - code.putln("#define PY_SSIZE_T_CLEAN") - code.putln("#endif /* PY_SSIZE_T_CLEAN */") - - for inc in sorted(env.c_includes.values(), key=IncludeCode.sortkey): - if inc.location == inc.INITIAL: - inc.write(code) - code.putln("#ifndef Py_PYTHON_H") - code.putln(" #error Python headers needed to compile C extensions, " - "please install development version of Python.") - code.putln("#elif PY_VERSION_HEX < 0x02060000 || " - "(0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000)") - code.putln(" #error Cython requires Python 2.6+ or Python 3.3+.") - code.putln("#else") - code.globalstate["end"].putln("#endif /* Py_PYTHON_H */") - - from .. import __version__ - code.putln('#define CYTHON_ABI "%s"' % __version__.replace('.', '_')) - code.putln('#define CYTHON_HEX_VERSION %s' % build_hex_version(__version__)) - code.putln("#define CYTHON_FUTURE_DIVISION %d" % ( - Future.division in env.context.future_directives)) - - self._put_setup_code(code, "CModulePreamble") - if env.context.options.cplus: - self._put_setup_code(code, "CppInitCode") - else: - self._put_setup_code(code, "CInitCode") - self._put_setup_code(code, "PythonCompatibility") - self._put_setup_code(code, "MathInitCode") - - # Using "(void)cname" to prevent "unused" warnings. - if options.c_line_in_traceback: - cinfo = "%s = %s; (void)%s; " % (Naming.clineno_cname, Naming.line_c_macro, Naming.clineno_cname) - else: - cinfo = "" - code.putln("#define __PYX_MARK_ERR_POS(f_index, lineno) \\") - code.putln(" { %s = %s[f_index]; (void)%s; %s = lineno; (void)%s; %s}" % ( - Naming.filename_cname, Naming.filetable_cname, Naming.filename_cname, - Naming.lineno_cname, Naming.lineno_cname, - cinfo - )) - code.putln("#define __PYX_ERR(f_index, lineno, Ln_error) \\") - code.putln(" { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; }") - - code.putln("") - self.generate_extern_c_macro_definition(code) - code.putln("") - - code.putln("#define %s" % Naming.h_guard_prefix + self.api_name(env)) - code.putln("#define %s" % Naming.api_guard_prefix + self.api_name(env)) - code.putln("/* Early includes */") - self.generate_includes(env, cimported_modules, code, late=False) - code.putln("") - code.putln("#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS)") - code.putln("#define CYTHON_WITHOUT_ASSERTIONS") - code.putln("#endif") - code.putln("") - - if env.directives['ccomplex']: - code.putln("") - code.putln("#if !defined(CYTHON_CCOMPLEX)") - code.putln("#define CYTHON_CCOMPLEX 1") - code.putln("#endif") - code.putln("") - code.put(UtilityCode.load_as_string("UtilityFunctionPredeclarations", "ModuleSetupCode.c")[0]) - - c_string_type = env.directives['c_string_type'] - c_string_encoding = env.directives['c_string_encoding'] - if c_string_type not in ('bytes', 'bytearray') and not c_string_encoding: - error(self.pos, "a default encoding must be provided if c_string_type is not a byte type") - code.putln('#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII %s' % int(c_string_encoding == 'ascii')) - code.putln('#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 %s' % - int(c_string_encoding.replace('-', '').lower() == 'utf8')) - if c_string_encoding == 'default': - code.putln('#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 1') - else: - code.putln('#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT ' - '(PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8)') - code.putln('#define __PYX_DEFAULT_STRING_ENCODING "%s"' % c_string_encoding) - if c_string_type == 'bytearray': - c_string_func_name = 'ByteArray' - else: - c_string_func_name = c_string_type.title() - code.putln('#define __Pyx_PyObject_FromString __Pyx_Py%s_FromString' % c_string_func_name) - code.putln('#define __Pyx_PyObject_FromStringAndSize __Pyx_Py%s_FromStringAndSize' % c_string_func_name) - code.put(UtilityCode.load_as_string("TypeConversions", "TypeConversion.c")[0]) - - # These utility functions are assumed to exist and used elsewhere. - PyrexTypes.c_long_type.create_to_py_utility_code(env) - PyrexTypes.c_long_type.create_from_py_utility_code(env) - PyrexTypes.c_int_type.create_from_py_utility_code(env) - - code.put(Nodes.branch_prediction_macros) - code.putln('static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }') - code.putln('') - code.putln('static PyObject *%s = NULL;' % env.module_cname) - code.putln('static PyObject *%s;' % env.module_dict_cname) - code.putln('static PyObject *%s;' % Naming.builtins_cname) - code.putln('static PyObject *%s = NULL;' % Naming.cython_runtime_cname) - code.putln('static PyObject *%s;' % Naming.empty_tuple) - code.putln('static PyObject *%s;' % Naming.empty_bytes) - code.putln('static PyObject *%s;' % Naming.empty_unicode) - if Options.pre_import is not None: - code.putln('static PyObject *%s;' % Naming.preimport_cname) - code.putln('static int %s;' % Naming.lineno_cname) - code.putln('static int %s = 0;' % Naming.clineno_cname) - code.putln('static const char * %s= %s;' % (Naming.cfilenm_cname, Naming.file_c_macro)) - code.putln('static const char *%s;' % Naming.filename_cname) - - env.use_utility_code(UtilityCode.load_cached("FastTypeChecks", "ModuleSetupCode.c")) - if has_np_pythran(env): - env.use_utility_code(UtilityCode.load_cached("PythranConversion", "CppSupport.cpp")) - - def generate_extern_c_macro_definition(self, code): - name = Naming.extern_c_macro - code.putln("#ifndef %s" % name) - code.putln(" #ifdef __cplusplus") - code.putln(' #define %s extern "C"' % name) - code.putln(" #else") - code.putln(" #define %s extern" % name) - code.putln(" #endif") - code.putln("#endif") - - def generate_dl_import_macro(self, code): - code.putln("#ifndef DL_IMPORT") - code.putln(" #define DL_IMPORT(_T) _T") - code.putln("#endif") - - def generate_includes(self, env, cimported_modules, code, early=True, late=True): - includes = [] - for inc in sorted(env.c_includes.values(), key=IncludeCode.sortkey): - if inc.location == inc.EARLY: - if early: - inc.write(code) - elif inc.location == inc.LATE: - if late: - inc.write(code) - if early: - code.putln_openmp("#include ") - - def generate_filename_table(self, code): - from os.path import isabs, basename - code.putln("") - code.putln("static const char *%s[] = {" % Naming.filetable_cname) - if code.globalstate.filename_list: - for source_desc in code.globalstate.filename_list: - file_path = source_desc.get_filenametable_entry() - if isabs(file_path): - file_path = basename(file_path) # never include absolute paths - escaped_filename = file_path.replace("\\", "\\\\").replace('"', r'\"') - code.putln('"%s",' % escaped_filename) - else: - # Some C compilers don't like an empty array - code.putln("0") - code.putln("};") - - def generate_type_predeclarations(self, env, code): - pass - - def generate_type_header_code(self, type_entries, code): - # Generate definitions of structs/unions/enums/typedefs/objstructs. - #self.generate_gcc33_hack(env, code) # Is this still needed? - # Forward declarations - for entry in type_entries: - if not entry.in_cinclude: - #print "generate_type_header_code:", entry.name, repr(entry.type) ### - type = entry.type - if type.is_typedef: # Must test this first! - pass - elif type.is_struct_or_union or type.is_cpp_class: - self.generate_struct_union_predeclaration(entry, code) - elif type.is_ctuple and entry.used: - self.generate_struct_union_predeclaration(entry.type.struct_entry, code) - elif type.is_extension_type: - self.generate_objstruct_predeclaration(type, code) - # Actual declarations - for entry in type_entries: - if not entry.in_cinclude: - #print "generate_type_header_code:", entry.name, repr(entry.type) ### - type = entry.type - if type.is_typedef: # Must test this first! - self.generate_typedef(entry, code) - elif type.is_enum: - self.generate_enum_definition(entry, code) - elif type.is_struct_or_union: - self.generate_struct_union_definition(entry, code) - elif type.is_ctuple and entry.used: - self.generate_struct_union_definition(entry.type.struct_entry, code) - elif type.is_cpp_class: - self.generate_cpp_class_definition(entry, code) - elif type.is_extension_type: - self.generate_objstruct_definition(type, code) - - def generate_gcc33_hack(self, env, code): - # Workaround for spurious warning generation in gcc 3.3 - code.putln("") - for entry in env.c_class_entries: - type = entry.type - if not type.typedef_flag: - name = type.objstruct_cname - if name.startswith("__pyx_"): - tail = name[6:] - else: - tail = name - code.putln("typedef struct %s __pyx_gcc33_%s;" % ( - name, tail)) - - def generate_typedef(self, entry, code): - base_type = entry.type.typedef_base_type - if base_type.is_numeric: - try: - writer = code.globalstate['numeric_typedefs'] - except KeyError: - writer = code - else: - writer = code - writer.mark_pos(entry.pos) - writer.putln("typedef %s;" % base_type.declaration_code(entry.cname)) - - def sue_predeclaration(self, type, kind, name): - if type.typedef_flag: - return "%s %s;\ntypedef %s %s %s;" % ( - kind, name, - kind, name, name) - else: - return "%s %s;" % (kind, name) - - def generate_struct_union_predeclaration(self, entry, code): - type = entry.type - if type.is_cpp_class and type.templates: - code.putln("template " % ", typename ".join( - [T.empty_declaration_code() for T in type.templates])) - code.putln(self.sue_predeclaration(type, type.kind, type.cname)) - - def sue_header_footer(self, type, kind, name): - header = "%s %s {" % (kind, name) - footer = "};" - return header, footer - - def generate_struct_union_definition(self, entry, code): - code.mark_pos(entry.pos) - type = entry.type - scope = type.scope - if scope: - kind = type.kind - packed = type.is_struct and type.packed - if packed: - kind = "%s %s" % (type.kind, "__Pyx_PACKED") - code.globalstate.use_utility_code(packed_struct_utility_code) - header, footer = \ - self.sue_header_footer(type, kind, type.cname) - if packed: - code.putln("#if defined(__SUNPRO_C)") - code.putln(" #pragma pack(1)") - code.putln("#elif !defined(__GNUC__)") - code.putln(" #pragma pack(push, 1)") - code.putln("#endif") - code.putln(header) - var_entries = scope.var_entries - if not var_entries: - error(entry.pos, "Empty struct or union definition not allowed outside a 'cdef extern from' block") - for attr in var_entries: - code.putln( - "%s;" % attr.type.declaration_code(attr.cname)) - code.putln(footer) - if packed: - code.putln("#if defined(__SUNPRO_C)") - code.putln(" #pragma pack()") - code.putln("#elif !defined(__GNUC__)") - code.putln(" #pragma pack(pop)") - code.putln("#endif") - - def generate_cpp_class_definition(self, entry, code): - code.mark_pos(entry.pos) - type = entry.type - scope = type.scope - if scope: - if type.templates: - code.putln("template " % ", class ".join( - [T.empty_declaration_code() for T in type.templates])) - # Just let everything be public. - code.put("struct %s" % type.cname) - if type.base_classes: - base_class_decl = ", public ".join( - [base_class.empty_declaration_code() for base_class in type.base_classes]) - code.put(" : public %s" % base_class_decl) - code.putln(" {") - py_attrs = [e for e in scope.entries.values() - if e.type.is_pyobject and not e.is_inherited] - has_virtual_methods = False - constructor = None - destructor = None - for attr in scope.var_entries: - if attr.type.is_cfunction and attr.type.is_static_method: - code.put("static ") - elif attr.name == "": - constructor = attr - elif attr.name == "": - destructor = attr - elif attr.type.is_cfunction: - code.put("virtual ") - has_virtual_methods = True - code.putln("%s;" % attr.type.declaration_code(attr.cname)) - is_implementing = 'init_module' in code.globalstate.parts - if constructor or py_attrs: - if constructor: - arg_decls = [] - arg_names = [] - for arg in constructor.type.original_args[ - :len(constructor.type.args)-constructor.type.optional_arg_count]: - arg_decls.append(arg.declaration_code()) - arg_names.append(arg.cname) - if constructor.type.optional_arg_count: - arg_decls.append(constructor.type.op_arg_struct.declaration_code(Naming.optional_args_cname)) - arg_names.append(Naming.optional_args_cname) - if not arg_decls: - arg_decls = ["void"] - else: - arg_decls = ["void"] - arg_names = [] - if is_implementing: - code.putln("%s(%s) {" % (type.cname, ", ".join(arg_decls))) - if py_attrs: - code.put_ensure_gil() - for attr in py_attrs: - code.put_init_var_to_py_none(attr, nanny=False); - if constructor: - code.putln("%s(%s);" % (constructor.cname, ", ".join(arg_names))) - if py_attrs: - code.put_release_ensured_gil() - code.putln("}") - else: - code.putln("%s(%s);" % (type.cname, ", ".join(arg_decls))) - if destructor or py_attrs or has_virtual_methods: - if has_virtual_methods: - code.put("virtual ") - if is_implementing: - code.putln("~%s() {" % type.cname) - if py_attrs: - code.put_ensure_gil() - if destructor: - code.putln("%s();" % destructor.cname) - if py_attrs: - for attr in py_attrs: - code.put_var_xdecref(attr, nanny=False); - code.put_release_ensured_gil() - code.putln("}") - else: - code.putln("~%s();" % type.cname) - if py_attrs: - # Also need copy constructor and assignment operators. - if is_implementing: - code.putln("%s(const %s& __Pyx_other) {" % (type.cname, type.cname)) - code.put_ensure_gil() - for attr in scope.var_entries: - if not attr.type.is_cfunction: - code.putln("%s = __Pyx_other.%s;" % (attr.cname, attr.cname)) - code.put_var_incref(attr, nanny=False) - code.put_release_ensured_gil() - code.putln("}") - code.putln("%s& operator=(const %s& __Pyx_other) {" % (type.cname, type.cname)) - code.putln("if (this != &__Pyx_other) {") - code.put_ensure_gil() - for attr in scope.var_entries: - if not attr.type.is_cfunction: - code.put_var_xdecref(attr, nanny=False); - code.putln("%s = __Pyx_other.%s;" % (attr.cname, attr.cname)) - code.put_var_incref(attr, nanny=False) - code.put_release_ensured_gil() - code.putln("}") - code.putln("return *this;") - code.putln("}") - else: - code.putln("%s(const %s& __Pyx_other);" % (type.cname, type.cname)) - code.putln("%s& operator=(const %s& __Pyx_other);" % (type.cname, type.cname)) - code.putln("};") - - def generate_enum_definition(self, entry, code): - code.mark_pos(entry.pos) - type = entry.type - name = entry.cname or entry.name or "" - header, footer = self.sue_header_footer(type, "enum", name) - code.putln(header) - enum_values = entry.enum_values - if not enum_values: - error(entry.pos, "Empty enum definition not allowed outside a 'cdef extern from' block") - else: - last_entry = enum_values[-1] - # this does not really generate code, just builds the result value - for value_entry in enum_values: - if value_entry.value_node is not None: - value_entry.value_node.generate_evaluation_code(code) - - for value_entry in enum_values: - if value_entry.value_node is None: - value_code = value_entry.cname - else: - value_code = ("%s = %s" % ( - value_entry.cname, - value_entry.value_node.result())) - if value_entry is not last_entry: - value_code += "," - code.putln(value_code) - code.putln(footer) - if entry.type.typedef_flag: - # Not pre-declared. - code.putln("typedef enum %s %s;" % (name, name)) - - def generate_typeobj_predeclaration(self, entry, code): - code.putln("") - name = entry.type.typeobj_cname - if name: - if entry.visibility == 'extern' and not entry.in_cinclude: - code.putln("%s %s %s;" % ( - Naming.extern_c_macro, - PyrexTypes.public_decl("PyTypeObject", "DL_IMPORT"), - name)) - elif entry.visibility == 'public': - code.putln("%s %s %s;" % ( - Naming.extern_c_macro, - PyrexTypes.public_decl("PyTypeObject", "DL_EXPORT"), - name)) - # ??? Do we really need the rest of this? ??? - #else: - # code.putln("static PyTypeObject %s;" % name) - - def generate_exttype_vtable_struct(self, entry, code): - if not entry.used: - return - - code.mark_pos(entry.pos) - # Generate struct declaration for an extension type's vtable. - type = entry.type - scope = type.scope - - self.specialize_fused_types(scope) - - if type.vtabstruct_cname: - code.putln("") - code.putln("struct %s {" % type.vtabstruct_cname) - if type.base_type and type.base_type.vtabstruct_cname: - code.putln("struct %s %s;" % ( - type.base_type.vtabstruct_cname, - Naming.obj_base_cname)) - for method_entry in scope.cfunc_entries: - if not method_entry.is_inherited: - code.putln("%s;" % method_entry.type.declaration_code("(*%s)" % method_entry.cname)) - code.putln("};") - - def generate_exttype_vtabptr_declaration(self, entry, code): - if not entry.used: - return - - code.mark_pos(entry.pos) - # Generate declaration of pointer to an extension type's vtable. - type = entry.type - if type.vtabptr_cname: - code.putln("static struct %s *%s;" % ( - type.vtabstruct_cname, - type.vtabptr_cname)) - - def generate_exttype_final_methods_declaration(self, entry, code): - if not entry.used: - return - - code.mark_pos(entry.pos) - # Generate final methods prototypes - type = entry.type - for method_entry in entry.type.scope.cfunc_entries: - if not method_entry.is_inherited and method_entry.final_func_cname: - declaration = method_entry.type.declaration_code( - method_entry.final_func_cname) - modifiers = code.build_function_modifiers(method_entry.func_modifiers) - code.putln("static %s%s;" % (modifiers, declaration)) - - def generate_objstruct_predeclaration(self, type, code): - if not type.scope: - return - code.putln(self.sue_predeclaration(type, "struct", type.objstruct_cname)) - - def generate_objstruct_definition(self, type, code): - code.mark_pos(type.pos) - # Generate object struct definition for an - # extension type. - if not type.scope: - return # Forward declared but never defined - header, footer = \ - self.sue_header_footer(type, "struct", type.objstruct_cname) - code.putln(header) - base_type = type.base_type - if base_type: - basestruct_cname = base_type.objstruct_cname - if basestruct_cname == "PyTypeObject": - # User-defined subclasses of type are heap allocated. - basestruct_cname = "PyHeapTypeObject" - code.putln( - "%s%s %s;" % ( - ("struct ", "")[base_type.typedef_flag], - basestruct_cname, - Naming.obj_base_cname)) - else: - code.putln( - "PyObject_HEAD") - if type.vtabslot_cname and not (type.base_type and type.base_type.vtabslot_cname): - code.putln( - "struct %s *%s;" % ( - type.vtabstruct_cname, - type.vtabslot_cname)) - for attr in type.scope.var_entries: - if attr.is_declared_generic: - attr_type = py_object_type - else: - attr_type = attr.type - code.putln( - "%s;" % attr_type.declaration_code(attr.cname)) - code.putln(footer) - if type.objtypedef_cname is not None: - # Only for exposing public typedef name. - code.putln("typedef struct %s %s;" % (type.objstruct_cname, type.objtypedef_cname)) - - def generate_c_class_declarations(self, env, code, definition): - for entry in env.c_class_entries: - if definition or entry.defined_in_pxd: - code.putln("static PyTypeObject *%s = 0;" % ( - entry.type.typeptr_cname)) - - def generate_cvariable_declarations(self, env, code, definition): - if env.is_cython_builtin: - return - for entry in env.var_entries: - if (entry.in_cinclude or entry.in_closure or - (entry.visibility == 'private' and not (entry.defined_in_pxd or entry.used))): - continue - - storage_class = None - dll_linkage = None - init = None - - if entry.visibility == 'extern': - storage_class = Naming.extern_c_macro - dll_linkage = "DL_IMPORT" - elif entry.visibility == 'public': - storage_class = Naming.extern_c_macro - if definition: - dll_linkage = "DL_EXPORT" - else: - dll_linkage = "DL_IMPORT" - elif entry.visibility == 'private': - storage_class = "static" - dll_linkage = None - if entry.init is not None: - init = entry.type.literal_code(entry.init) - type = entry.type - cname = entry.cname - - if entry.defined_in_pxd and not definition: - storage_class = "static" - dll_linkage = None - type = CPtrType(type) - cname = env.mangle(Naming.varptr_prefix, entry.name) - init = 0 - - if storage_class: - code.put("%s " % storage_class) - code.put(type.declaration_code( - cname, dll_linkage=dll_linkage)) - if init is not None: - code.put_safe(" = %s" % init) - code.putln(";") - if entry.cname != cname: - code.putln("#define %s (*%s)" % (entry.cname, cname)) - - def generate_cfunction_declarations(self, env, code, definition): - for entry in env.cfunc_entries: - if entry.used or (entry.visibility == 'public' or entry.api): - generate_cfunction_declaration(entry, env, code, definition) - - def generate_variable_definitions(self, env, code): - for entry in env.var_entries: - if not entry.in_cinclude and entry.visibility == "public": - code.put(entry.type.declaration_code(entry.cname)) - if entry.init is not None: - init = entry.type.literal_code(entry.init) - code.put_safe(" = %s" % init) - code.putln(";") - - def generate_typeobj_definitions(self, env, code): - full_module_name = env.qualified_name - for entry in env.c_class_entries: - #print "generate_typeobj_definitions:", entry.name - #print "...visibility =", entry.visibility - if entry.visibility != 'extern': - type = entry.type - scope = type.scope - if scope: # could be None if there was an error - if not scope.directives['c_api_binop_methods']: - error(self.pos, - "The 'c_api_binop_methods' directive is only supported for forward compatibility" - " and must be True.") - self.generate_exttype_vtable(scope, code) - self.generate_new_function(scope, code, entry) - self.generate_dealloc_function(scope, code) - if scope.needs_gc(): - self.generate_traverse_function(scope, code, entry) - if scope.needs_tp_clear(): - self.generate_clear_function(scope, code, entry) - if scope.defines_any_special(["__getitem__"]): - self.generate_getitem_int_function(scope, code) - if scope.defines_any_special(["__setitem__", "__delitem__"]): - self.generate_ass_subscript_function(scope, code) - if scope.defines_any_special(["__getslice__", "__setslice__", "__delslice__"]): - warning(self.pos, - "__getslice__, __setslice__, and __delslice__ are not supported by Python 3, " - "use __getitem__, __setitem__, and __delitem__ instead", 1) - code.putln("#if PY_MAJOR_VERSION >= 3") - code.putln("#error __getslice__, __setslice__, and __delslice__ not supported in Python 3.") - code.putln("#endif") - if scope.defines_any_special(["__setslice__", "__delslice__"]): - self.generate_ass_slice_function(scope, code) - if scope.defines_any_special(["__getattr__", "__getattribute__"]): - self.generate_getattro_function(scope, code) - if scope.defines_any_special(["__setattr__", "__delattr__"]): - self.generate_setattro_function(scope, code) - if scope.defines_any_special(["__get__"]): - self.generate_descr_get_function(scope, code) - if scope.defines_any_special(["__set__", "__delete__"]): - self.generate_descr_set_function(scope, code) - if not scope.is_closure_class_scope and scope.defines_any(["__dict__"]): - self.generate_dict_getter_function(scope, code) - if scope.defines_any_special(TypeSlots.richcmp_special_methods): - self.generate_richcmp_function(scope, code) - self.generate_property_accessors(scope, code) - self.generate_method_table(scope, code) - self.generate_getset_table(scope, code) - self.generate_typeobj_definition(full_module_name, entry, code) - - def generate_exttype_vtable(self, scope, code): - # Generate the definition of an extension type's vtable. - type = scope.parent_type - if type.vtable_cname: - code.putln("static struct %s %s;" % ( - type.vtabstruct_cname, - type.vtable_cname)) - - def generate_self_cast(self, scope, code): - type = scope.parent_type - code.putln( - "%s = (%s)o;" % ( - type.declaration_code("p"), - type.empty_declaration_code())) - - def generate_new_function(self, scope, code, cclass_entry): - tp_slot = TypeSlots.ConstructorSlot("tp_new", '__new__') - slot_func = scope.mangle_internal("tp_new") - type = scope.parent_type - base_type = type.base_type - - have_entries, (py_attrs, py_buffers, memoryview_slices) = \ - scope.get_refcounted_entries() - is_final_type = scope.parent_type.is_final_type - if scope.is_internal: - # internal classes (should) never need None inits, normal zeroing will do - py_attrs = [] - cpp_class_attrs = [entry for entry in scope.var_entries - if entry.type.is_cpp_class] - - new_func_entry = scope.lookup_here("__new__") - if base_type or (new_func_entry and new_func_entry.is_special - and not new_func_entry.trivial_signature): - unused_marker = '' - else: - unused_marker = 'CYTHON_UNUSED ' - - if base_type: - freelist_size = 0 # not currently supported - else: - freelist_size = scope.directives.get('freelist', 0) - freelist_name = scope.mangle_internal(Naming.freelist_name) - freecount_name = scope.mangle_internal(Naming.freecount_name) - - decls = code.globalstate['decls'] - decls.putln("static PyObject *%s(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/" % - slot_func) - code.putln("") - if freelist_size: - code.putln("static %s[%d];" % ( - scope.parent_type.declaration_code(freelist_name), - freelist_size)) - code.putln("static int %s = 0;" % freecount_name) - code.putln("") - code.putln( - "static PyObject *%s(PyTypeObject *t, %sPyObject *a, %sPyObject *k) {" % ( - slot_func, unused_marker, unused_marker)) - - need_self_cast = (type.vtabslot_cname or - (py_buffers or memoryview_slices or py_attrs) or - cpp_class_attrs) - if need_self_cast: - code.putln("%s;" % scope.parent_type.declaration_code("p")) - if base_type: - tp_new = TypeSlots.get_base_slot_function(scope, tp_slot) - if tp_new is None: - tp_new = "%s->tp_new" % base_type.typeptr_cname - code.putln("PyObject *o = %s(t, a, k);" % tp_new) - else: - code.putln("PyObject *o;") - if freelist_size: - code.globalstate.use_utility_code( - UtilityCode.load_cached("IncludeStringH", "StringTools.c")) - if is_final_type: - type_safety_check = '' - else: - type_safety_check = ' & ((t->tp_flags & (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE)) == 0)' - obj_struct = type.declaration_code("", deref=True) - code.putln( - "if (CYTHON_COMPILING_IN_CPYTHON && likely((%s > 0) & (t->tp_basicsize == sizeof(%s))%s)) {" % ( - freecount_name, obj_struct, type_safety_check)) - code.putln("o = (PyObject*)%s[--%s];" % ( - freelist_name, freecount_name)) - code.putln("memset(o, 0, sizeof(%s));" % obj_struct) - code.putln("(void) PyObject_INIT(o, t);") - if scope.needs_gc(): - code.putln("PyObject_GC_Track(o);") - code.putln("} else {") - if not is_final_type: - code.putln("if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) {") - code.putln("o = (*t->tp_alloc)(t, 0);") - if not is_final_type: - code.putln("} else {") - code.putln("o = (PyObject *) PyBaseObject_Type.tp_new(t, %s, 0);" % Naming.empty_tuple) - code.putln("}") - code.putln("if (unlikely(!o)) return 0;") - if freelist_size and not base_type: - code.putln('}') - if need_self_cast: - code.putln("p = %s;" % type.cast_code("o")) - #if need_self_cast: - # self.generate_self_cast(scope, code) - - # from this point on, ensure DECREF(o) on failure - needs_error_cleanup = False - - if type.vtabslot_cname: - vtab_base_type = type - while vtab_base_type.base_type and vtab_base_type.base_type.vtabstruct_cname: - vtab_base_type = vtab_base_type.base_type - if vtab_base_type is not type: - struct_type_cast = "(struct %s*)" % vtab_base_type.vtabstruct_cname - else: - struct_type_cast = "" - code.putln("p->%s = %s%s;" % ( - type.vtabslot_cname, - struct_type_cast, type.vtabptr_cname)) - - for entry in cpp_class_attrs: - code.putln("new((void*)&(p->%s)) %s();" % ( - entry.cname, entry.type.empty_declaration_code())) - - for entry in py_attrs: - if entry.name == "__dict__": - needs_error_cleanup = True - code.put("p->%s = PyDict_New(); if (unlikely(!p->%s)) goto bad;" % ( - entry.cname, entry.cname)) - else: - code.put_init_var_to_py_none(entry, "p->%s", nanny=False) - - for entry in memoryview_slices: - code.putln("p->%s.data = NULL;" % entry.cname) - code.putln("p->%s.memview = NULL;" % entry.cname) - - for entry in py_buffers: - code.putln("p->%s.obj = NULL;" % entry.cname) - - if cclass_entry.cname == '__pyx_memoryviewslice': - code.putln("p->from_slice.memview = NULL;") - - if new_func_entry and new_func_entry.is_special: - if new_func_entry.trivial_signature: - cinit_args = "o, %s, NULL" % Naming.empty_tuple - else: - cinit_args = "o, a, k" - needs_error_cleanup = True - code.putln("if (unlikely(%s(%s) < 0)) goto bad;" % ( - new_func_entry.func_cname, cinit_args)) - - code.putln( - "return o;") - if needs_error_cleanup: - code.putln("bad:") - code.put_decref_clear("o", py_object_type, nanny=False) - code.putln("return NULL;") - code.putln( - "}") - - def generate_dealloc_function(self, scope, code): - tp_slot = TypeSlots.ConstructorSlot("tp_dealloc", '__dealloc__') - slot_func = scope.mangle_internal("tp_dealloc") - base_type = scope.parent_type.base_type - if tp_slot.slot_code(scope) != slot_func: - return # never used - - slot_func_cname = scope.mangle_internal("tp_dealloc") - code.putln("") - code.putln( - "static void %s(PyObject *o) {" % slot_func_cname) - - is_final_type = scope.parent_type.is_final_type - needs_gc = scope.needs_gc() - - weakref_slot = scope.lookup_here("__weakref__") if not scope.is_closure_class_scope else None - if weakref_slot not in scope.var_entries: - weakref_slot = None - - dict_slot = scope.lookup_here("__dict__") if not scope.is_closure_class_scope else None - if dict_slot not in scope.var_entries: - dict_slot = None - - _, (py_attrs, _, memoryview_slices) = scope.get_refcounted_entries() - cpp_class_attrs = [entry for entry in scope.var_entries - if entry.type.is_cpp_class] - - if py_attrs or cpp_class_attrs or memoryview_slices or weakref_slot or dict_slot: - self.generate_self_cast(scope, code) - - if not is_final_type: - # in Py3.4+, call tp_finalize() as early as possible - code.putln("#if CYTHON_USE_TP_FINALIZE") - if needs_gc: - finalised_check = '!_PyGC_FINALIZED(o)' - else: - finalised_check = ( - '(!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))') - code.putln( - "if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)" - " && Py_TYPE(o)->tp_finalize) && %s) {" % finalised_check) - # if instance was resurrected by finaliser, return - code.putln("if (PyObject_CallFinalizerFromDealloc(o)) return;") - code.putln("}") - code.putln("#endif") - - if needs_gc: - # We must mark this object as (gc) untracked while tearing - # it down, lest the garbage collection is invoked while - # running this destructor. - code.putln("PyObject_GC_UnTrack(o);") - - # call the user's __dealloc__ - self.generate_usr_dealloc_call(scope, code) - - if weakref_slot: - code.putln("if (p->__weakref__) PyObject_ClearWeakRefs(o);") - - if dict_slot: - code.putln("if (p->__dict__) PyDict_Clear(p->__dict__);") - - for entry in cpp_class_attrs: - code.putln("__Pyx_call_destructor(p->%s);" % entry.cname) - - for entry in py_attrs: - code.put_xdecref_clear("p->%s" % entry.cname, entry.type, nanny=False, - clear_before_decref=True) - - for entry in memoryview_slices: - code.put_xdecref_memoryviewslice("p->%s" % entry.cname, - have_gil=True) - - if base_type: - if needs_gc: - # The base class deallocator probably expects this to be tracked, - # so undo the untracking above. - if base_type.scope and base_type.scope.needs_gc(): - code.putln("PyObject_GC_Track(o);") - else: - code.putln("#if CYTHON_USE_TYPE_SLOTS") - code.putln("if (PyType_IS_GC(Py_TYPE(o)->tp_base))") - code.putln("#endif") - code.putln("PyObject_GC_Track(o);") - - tp_dealloc = TypeSlots.get_base_slot_function(scope, tp_slot) - if tp_dealloc is not None: - code.putln("%s(o);" % tp_dealloc) - elif base_type.is_builtin_type: - code.putln("%s->tp_dealloc(o);" % base_type.typeptr_cname) - else: - # This is an externally defined type. Calling through the - # cimported base type pointer directly interacts badly with - # the module cleanup, which may already have cleared it. - # In that case, fall back to traversing the type hierarchy. - base_cname = base_type.typeptr_cname - code.putln("if (likely(%s)) %s->tp_dealloc(o); " - "else __Pyx_call_next_tp_dealloc(o, %s);" % ( - base_cname, base_cname, slot_func_cname)) - code.globalstate.use_utility_code( - UtilityCode.load_cached("CallNextTpDealloc", "ExtensionTypes.c")) - else: - freelist_size = scope.directives.get('freelist', 0) - if freelist_size: - freelist_name = scope.mangle_internal(Naming.freelist_name) - freecount_name = scope.mangle_internal(Naming.freecount_name) - - if is_final_type: - type_safety_check = '' - else: - type_safety_check = ( - ' & ((Py_TYPE(o)->tp_flags & (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE)) == 0)') - - type = scope.parent_type - code.putln( - "if (CYTHON_COMPILING_IN_CPYTHON && ((%s < %d) & (Py_TYPE(o)->tp_basicsize == sizeof(%s))%s)) {" % ( - freecount_name, - freelist_size, - type.declaration_code("", deref=True), - type_safety_check)) - code.putln("%s[%s++] = %s;" % ( - freelist_name, freecount_name, type.cast_code("o"))) - code.putln("} else {") - code.putln("(*Py_TYPE(o)->tp_free)(o);") - if freelist_size: - code.putln("}") - code.putln( - "}") - - def generate_usr_dealloc_call(self, scope, code): - entry = scope.lookup_here("__dealloc__") - if not entry: - return - - code.putln("{") - code.putln("PyObject *etype, *eval, *etb;") - code.putln("PyErr_Fetch(&etype, &eval, &etb);") - # increase the refcount while we are calling into user code - # to prevent recursive deallocation - code.putln("__Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1);") - code.putln("%s(o);" % entry.func_cname) - code.putln("__Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1);") - code.putln("PyErr_Restore(etype, eval, etb);") - code.putln("}") - - def generate_traverse_function(self, scope, code, cclass_entry): - tp_slot = TypeSlots.GCDependentSlot("tp_traverse") - slot_func = scope.mangle_internal("tp_traverse") - base_type = scope.parent_type.base_type - if tp_slot.slot_code(scope) != slot_func: - return # never used - code.putln("") - code.putln( - "static int %s(PyObject *o, visitproc v, void *a) {" % slot_func) - - have_entries, (py_attrs, py_buffers, memoryview_slices) = ( - scope.get_refcounted_entries(include_gc_simple=False)) - - if base_type or py_attrs: - code.putln("int e;") - - if py_attrs or py_buffers: - self.generate_self_cast(scope, code) - - if base_type: - # want to call it explicitly if possible so inlining can be performed - static_call = TypeSlots.get_base_slot_function(scope, tp_slot) - if static_call: - code.putln("e = %s(o, v, a); if (e) return e;" % static_call) - elif base_type.is_builtin_type: - base_cname = base_type.typeptr_cname - code.putln("if (!%s->tp_traverse); else { e = %s->tp_traverse(o,v,a); if (e) return e; }" % ( - base_cname, base_cname)) - else: - # This is an externally defined type. Calling through the - # cimported base type pointer directly interacts badly with - # the module cleanup, which may already have cleared it. - # In that case, fall back to traversing the type hierarchy. - base_cname = base_type.typeptr_cname - code.putln( - "e = ((likely(%s)) ? ((%s->tp_traverse) ? %s->tp_traverse(o, v, a) : 0) : " - "__Pyx_call_next_tp_traverse(o, v, a, %s)); if (e) return e;" % ( - base_cname, base_cname, base_cname, slot_func)) - code.globalstate.use_utility_code( - UtilityCode.load_cached("CallNextTpTraverse", "ExtensionTypes.c")) - - for entry in py_attrs: - var_code = "p->%s" % entry.cname - var_as_pyobject = PyrexTypes.typecast(py_object_type, entry.type, var_code) - code.putln("if (%s) {" % var_code) - code.putln("e = (*v)(%s, a); if (e) return e;" % var_as_pyobject) - code.putln("}") - - # Traverse buffer exporting objects. - # Note: not traversing memoryview attributes of memoryview slices! - # When triggered by the GC, it would cause multiple visits (gc_refs - # subtractions which is not matched by its reference count!) - for entry in py_buffers: - cname = entry.cname + ".obj" - code.putln("if (p->%s) {" % cname) - code.putln("e = (*v)(p->%s, a); if (e) return e;" % cname) - code.putln("}") - - code.putln("return 0;") - code.putln("}") - - def generate_clear_function(self, scope, code, cclass_entry): - tp_slot = TypeSlots.get_slot_by_name("tp_clear") - slot_func = scope.mangle_internal("tp_clear") - base_type = scope.parent_type.base_type - if tp_slot.slot_code(scope) != slot_func: - return # never used - - have_entries, (py_attrs, py_buffers, memoryview_slices) = ( - scope.get_refcounted_entries(include_gc_simple=False)) - - if py_attrs or py_buffers or base_type: - unused = '' - else: - unused = 'CYTHON_UNUSED ' - - code.putln("") - code.putln("static int %s(%sPyObject *o) {" % (slot_func, unused)) - - if py_attrs and Options.clear_to_none: - code.putln("PyObject* tmp;") - - if py_attrs or py_buffers: - self.generate_self_cast(scope, code) - - if base_type: - # want to call it explicitly if possible so inlining can be performed - static_call = TypeSlots.get_base_slot_function(scope, tp_slot) - if static_call: - code.putln("%s(o);" % static_call) - elif base_type.is_builtin_type: - base_cname = base_type.typeptr_cname - code.putln("if (!%s->tp_clear); else %s->tp_clear(o);" % ( - base_cname, base_cname)) - else: - # This is an externally defined type. Calling through the - # cimported base type pointer directly interacts badly with - # the module cleanup, which may already have cleared it. - # In that case, fall back to traversing the type hierarchy. - base_cname = base_type.typeptr_cname - code.putln( - "if (likely(%s)) { if (%s->tp_clear) %s->tp_clear(o); } else __Pyx_call_next_tp_clear(o, %s);" % ( - base_cname, base_cname, base_cname, slot_func)) - code.globalstate.use_utility_code( - UtilityCode.load_cached("CallNextTpClear", "ExtensionTypes.c")) - - if Options.clear_to_none: - for entry in py_attrs: - name = "p->%s" % entry.cname - code.putln("tmp = ((PyObject*)%s);" % name) - if entry.is_declared_generic: - code.put_init_to_py_none(name, py_object_type, nanny=False) - else: - code.put_init_to_py_none(name, entry.type, nanny=False) - code.putln("Py_XDECREF(tmp);") - else: - for entry in py_attrs: - code.putln("Py_CLEAR(p->%s);" % entry.cname) - - for entry in py_buffers: - # Note: shouldn't this call __Pyx_ReleaseBuffer ?? - code.putln("Py_CLEAR(p->%s.obj);" % entry.cname) - - if cclass_entry.cname == '__pyx_memoryviewslice': - code.putln("__PYX_XDEC_MEMVIEW(&p->from_slice, 1);") - - code.putln("return 0;") - code.putln("}") - - def generate_getitem_int_function(self, scope, code): - # This function is put into the sq_item slot when - # a __getitem__ method is present. It converts its - # argument to a Python integer and calls mp_subscript. - code.putln( - "static PyObject *%s(PyObject *o, Py_ssize_t i) {" % ( - scope.mangle_internal("sq_item"))) - code.putln( - "PyObject *r;") - code.putln( - "PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0;") - code.putln( - "r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);") - code.putln( - "Py_DECREF(x);") - code.putln( - "return r;") - code.putln( - "}") - - def generate_ass_subscript_function(self, scope, code): - # Setting and deleting an item are both done through - # the ass_subscript method, so we dispatch to user's __setitem__ - # or __delitem__, or raise an exception. - base_type = scope.parent_type.base_type - set_entry = scope.lookup_here("__setitem__") - del_entry = scope.lookup_here("__delitem__") - code.putln("") - code.putln( - "static int %s(PyObject *o, PyObject *i, PyObject *v) {" % ( - scope.mangle_internal("mp_ass_subscript"))) - code.putln( - "if (v) {") - if set_entry: - code.putln("return %s(o, i, v);" % set_entry.func_cname) - else: - self.generate_guarded_basetype_call( - base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code) - code.putln( - "PyErr_Format(PyExc_NotImplementedError,") - code.putln( - ' "Subscript assignment not supported by %.200s", Py_TYPE(o)->tp_name);') - code.putln( - "return -1;") - code.putln( - "}") - code.putln( - "else {") - if del_entry: - code.putln( - "return %s(o, i);" % ( - del_entry.func_cname)) - else: - self.generate_guarded_basetype_call( - base_type, "tp_as_mapping", "mp_ass_subscript", "o, i, v", code) - code.putln( - "PyErr_Format(PyExc_NotImplementedError,") - code.putln( - ' "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name);') - code.putln( - "return -1;") - code.putln( - "}") - code.putln( - "}") - - def generate_guarded_basetype_call( - self, base_type, substructure, slot, args, code): - if base_type: - base_tpname = base_type.typeptr_cname - if substructure: - code.putln( - "if (%s->%s && %s->%s->%s)" % ( - base_tpname, substructure, base_tpname, substructure, slot)) - code.putln( - " return %s->%s->%s(%s);" % ( - base_tpname, substructure, slot, args)) - else: - code.putln( - "if (%s->%s)" % ( - base_tpname, slot)) - code.putln( - " return %s->%s(%s);" % ( - base_tpname, slot, args)) - - def generate_ass_slice_function(self, scope, code): - # Setting and deleting a slice are both done through - # the ass_slice method, so we dispatch to user's __setslice__ - # or __delslice__, or raise an exception. - base_type = scope.parent_type.base_type - set_entry = scope.lookup_here("__setslice__") - del_entry = scope.lookup_here("__delslice__") - code.putln("") - code.putln( - "static int %s(PyObject *o, Py_ssize_t i, Py_ssize_t j, PyObject *v) {" % ( - scope.mangle_internal("sq_ass_slice"))) - code.putln( - "if (v) {") - if set_entry: - code.putln( - "return %s(o, i, j, v);" % ( - set_entry.func_cname)) - else: - self.generate_guarded_basetype_call( - base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code) - code.putln( - "PyErr_Format(PyExc_NotImplementedError,") - code.putln( - ' "2-element slice assignment not supported by %.200s", Py_TYPE(o)->tp_name);') - code.putln( - "return -1;") - code.putln( - "}") - code.putln( - "else {") - if del_entry: - code.putln( - "return %s(o, i, j);" % ( - del_entry.func_cname)) - else: - self.generate_guarded_basetype_call( - base_type, "tp_as_sequence", "sq_ass_slice", "o, i, j, v", code) - code.putln( - "PyErr_Format(PyExc_NotImplementedError,") - code.putln( - ' "2-element slice deletion not supported by %.200s", Py_TYPE(o)->tp_name);') - code.putln( - "return -1;") - code.putln( - "}") - code.putln( - "}") - - def generate_richcmp_function(self, scope, code): - if scope.lookup_here("__richcmp__"): - # user implemented, nothing to do - return - # otherwise, we have to generate it from the Python special methods - richcmp_cfunc = scope.mangle_internal("tp_richcompare") - code.putln("") - code.putln("static PyObject *%s(PyObject *o1, PyObject *o2, int op) {" % richcmp_cfunc) - code.putln("switch (op) {") - - class_scopes = [] - cls = scope.parent_type - while cls is not None and not cls.entry.visibility == 'extern': - class_scopes.append(cls.scope) - cls = cls.scope.parent_type.base_type - assert scope in class_scopes - - extern_parent = None - if cls and cls.entry.visibility == 'extern': - # need to call up into base classes as we may not know all implemented comparison methods - extern_parent = cls if cls.typeptr_cname else scope.parent_type.base_type - - eq_entry = None - has_ne = False - for cmp_method in TypeSlots.richcmp_special_methods: - for class_scope in class_scopes: - entry = class_scope.lookup_here(cmp_method) - if entry is not None: - break - else: - continue - - cmp_type = cmp_method.strip('_').upper() # e.g. "__eq__" -> EQ - code.putln("case Py_%s: {" % cmp_type) - if cmp_method == '__eq__': - eq_entry = entry - # Python itself does not do this optimisation, it seems... - #code.putln("if (o1 == o2) return __Pyx_NewRef(Py_True);") - elif cmp_method == '__ne__': - has_ne = True - # Python itself does not do this optimisation, it seems... - #code.putln("if (o1 == o2) return __Pyx_NewRef(Py_False);") - code.putln("return %s(o1, o2);" % entry.func_cname) - code.putln("}") - - if eq_entry and not has_ne and not extern_parent: - code.putln("case Py_NE: {") - code.putln("PyObject *ret;") - # Python itself does not do this optimisation, it seems... - #code.putln("if (o1 == o2) return __Pyx_NewRef(Py_False);") - code.putln("ret = %s(o1, o2);" % eq_entry.func_cname) - code.putln("if (likely(ret && ret != Py_NotImplemented)) {") - code.putln("int b = __Pyx_PyObject_IsTrue(ret); Py_DECREF(ret);") - code.putln("if (unlikely(b < 0)) return NULL;") - code.putln("ret = (b) ? Py_False : Py_True;") - code.putln("Py_INCREF(ret);") - code.putln("}") - code.putln("return ret;") - code.putln("}") - - code.putln("default: {") - if extern_parent and extern_parent.typeptr_cname: - code.putln("if (likely(%s->tp_richcompare)) return %s->tp_richcompare(o1, o2, op);" % ( - extern_parent.typeptr_cname, extern_parent.typeptr_cname)) - code.putln("return __Pyx_NewRef(Py_NotImplemented);") - code.putln("}") - - code.putln("}") # switch - code.putln("}") - - def generate_getattro_function(self, scope, code): - # First try to get the attribute using __getattribute__, if defined, or - # PyObject_GenericGetAttr. - # - # If that raises an AttributeError, call the __getattr__ if defined. - # - # In both cases, defined can be in this class, or any base class. - def lookup_here_or_base(n, tp=None, extern_return=None): - # Recursive lookup - if tp is None: - tp = scope.parent_type - r = tp.scope.lookup_here(n) - if r is None: - if tp.is_external and extern_return is not None: - return extern_return - if tp.base_type is not None: - return lookup_here_or_base(n, tp.base_type) - return r - - has_instance_dict = lookup_here_or_base("__dict__", extern_return="extern") - getattr_entry = lookup_here_or_base("__getattr__") - getattribute_entry = lookup_here_or_base("__getattribute__") - code.putln("") - code.putln( - "static PyObject *%s(PyObject *o, PyObject *n) {" % ( - scope.mangle_internal("tp_getattro"))) - if getattribute_entry is not None: - code.putln( - "PyObject *v = %s(o, n);" % ( - getattribute_entry.func_cname)) - else: - if not has_instance_dict and scope.parent_type.is_final_type: - # Final with no dict => use faster type attribute lookup. - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyObject_GenericGetAttrNoDict", "ObjectHandling.c")) - generic_getattr_cfunc = "__Pyx_PyObject_GenericGetAttrNoDict" - elif not has_instance_dict or has_instance_dict == "extern": - # No dict in the known ancestors, but don't know about extern ancestors or subtypes. - code.globalstate.use_utility_code( - UtilityCode.load_cached("PyObject_GenericGetAttr", "ObjectHandling.c")) - generic_getattr_cfunc = "__Pyx_PyObject_GenericGetAttr" - else: - generic_getattr_cfunc = "PyObject_GenericGetAttr" - code.putln( - "PyObject *v = %s(o, n);" % generic_getattr_cfunc) - if getattr_entry is not None: - code.putln( - "if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) {") - code.putln( - "PyErr_Clear();") - code.putln( - "v = %s(o, n);" % ( - getattr_entry.func_cname)) - code.putln( - "}") - code.putln( - "return v;") - code.putln( - "}") - - def generate_setattro_function(self, scope, code): - # Setting and deleting an attribute are both done through - # the setattro method, so we dispatch to user's __setattr__ - # or __delattr__ or fall back on PyObject_GenericSetAttr. - base_type = scope.parent_type.base_type - set_entry = scope.lookup_here("__setattr__") - del_entry = scope.lookup_here("__delattr__") - code.putln("") - code.putln( - "static int %s(PyObject *o, PyObject *n, PyObject *v) {" % ( - scope.mangle_internal("tp_setattro"))) - code.putln( - "if (v) {") - if set_entry: - code.putln( - "return %s(o, n, v);" % ( - set_entry.func_cname)) - else: - self.generate_guarded_basetype_call( - base_type, None, "tp_setattro", "o, n, v", code) - code.putln( - "return PyObject_GenericSetAttr(o, n, v);") - code.putln( - "}") - code.putln( - "else {") - if del_entry: - code.putln( - "return %s(o, n);" % ( - del_entry.func_cname)) - else: - self.generate_guarded_basetype_call( - base_type, None, "tp_setattro", "o, n, v", code) - code.putln( - "return PyObject_GenericSetAttr(o, n, 0);") - code.putln( - "}") - code.putln( - "}") - - def generate_descr_get_function(self, scope, code): - # The __get__ function of a descriptor object can be - # called with NULL for the second or third arguments - # under some circumstances, so we replace them with - # None in that case. - user_get_entry = scope.lookup_here("__get__") - code.putln("") - code.putln( - "static PyObject *%s(PyObject *o, PyObject *i, PyObject *c) {" % ( - scope.mangle_internal("tp_descr_get"))) - code.putln( - "PyObject *r = 0;") - code.putln( - "if (!i) i = Py_None;") - code.putln( - "if (!c) c = Py_None;") - #code.put_incref("i", py_object_type) - #code.put_incref("c", py_object_type) - code.putln( - "r = %s(o, i, c);" % ( - user_get_entry.func_cname)) - #code.put_decref("i", py_object_type) - #code.put_decref("c", py_object_type) - code.putln( - "return r;") - code.putln( - "}") - - def generate_descr_set_function(self, scope, code): - # Setting and deleting are both done through the __set__ - # method of a descriptor, so we dispatch to user's __set__ - # or __delete__ or raise an exception. - base_type = scope.parent_type.base_type - user_set_entry = scope.lookup_here("__set__") - user_del_entry = scope.lookup_here("__delete__") - code.putln("") - code.putln( - "static int %s(PyObject *o, PyObject *i, PyObject *v) {" % ( - scope.mangle_internal("tp_descr_set"))) - code.putln( - "if (v) {") - if user_set_entry: - code.putln( - "return %s(o, i, v);" % ( - user_set_entry.func_cname)) - else: - self.generate_guarded_basetype_call( - base_type, None, "tp_descr_set", "o, i, v", code) - code.putln( - 'PyErr_SetString(PyExc_NotImplementedError, "__set__");') - code.putln( - "return -1;") - code.putln( - "}") - code.putln( - "else {") - if user_del_entry: - code.putln( - "return %s(o, i);" % ( - user_del_entry.func_cname)) - else: - self.generate_guarded_basetype_call( - base_type, None, "tp_descr_set", "o, i, v", code) - code.putln( - 'PyErr_SetString(PyExc_NotImplementedError, "__delete__");') - code.putln( - "return -1;") - code.putln( - "}") - code.putln( - "}") - - def generate_property_accessors(self, cclass_scope, code): - for entry in cclass_scope.property_entries: - property_scope = entry.scope - if property_scope.defines_any(["__get__"]): - self.generate_property_get_function(entry, code) - if property_scope.defines_any(["__set__", "__del__"]): - self.generate_property_set_function(entry, code) - - def generate_property_get_function(self, property_entry, code): - property_scope = property_entry.scope - property_entry.getter_cname = property_scope.parent_scope.mangle( - Naming.prop_get_prefix, property_entry.name) - get_entry = property_scope.lookup_here("__get__") - code.putln("") - code.putln( - "static PyObject *%s(PyObject *o, CYTHON_UNUSED void *x) {" % ( - property_entry.getter_cname)) - code.putln( - "return %s(o);" % ( - get_entry.func_cname)) - code.putln( - "}") - - def generate_property_set_function(self, property_entry, code): - property_scope = property_entry.scope - property_entry.setter_cname = property_scope.parent_scope.mangle( - Naming.prop_set_prefix, property_entry.name) - set_entry = property_scope.lookup_here("__set__") - del_entry = property_scope.lookup_here("__del__") - code.putln("") - code.putln( - "static int %s(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) {" % ( - property_entry.setter_cname)) - code.putln( - "if (v) {") - if set_entry: - code.putln( - "return %s(o, v);" % ( - set_entry.func_cname)) - else: - code.putln( - 'PyErr_SetString(PyExc_NotImplementedError, "__set__");') - code.putln( - "return -1;") - code.putln( - "}") - code.putln( - "else {") - if del_entry: - code.putln( - "return %s(o);" % ( - del_entry.func_cname)) - else: - code.putln( - 'PyErr_SetString(PyExc_NotImplementedError, "__del__");') - code.putln( - "return -1;") - code.putln( - "}") - code.putln( - "}") - - def generate_typeobj_definition(self, modname, entry, code): - type = entry.type - scope = type.scope - for suite in TypeSlots.substructures: - suite.generate_substructure(scope, code) - code.putln("") - if entry.visibility == 'public': - header = "DL_EXPORT(PyTypeObject) %s = {" - else: - header = "static PyTypeObject %s = {" - #code.putln(header % scope.parent_type.typeobj_cname) - code.putln(header % type.typeobj_cname) - code.putln( - "PyVarObject_HEAD_INIT(0, 0)") - code.putln( - '"%s.%s", /*tp_name*/' % ( - self.full_module_name, scope.class_name)) - if type.typedef_flag: - objstruct = type.objstruct_cname - else: - objstruct = "struct %s" % type.objstruct_cname - code.putln( - "sizeof(%s), /*tp_basicsize*/" % objstruct) - code.putln( - "0, /*tp_itemsize*/") - for slot in TypeSlots.slot_table: - slot.generate(scope, code) - code.putln( - "};") - - def generate_method_table(self, env, code): - if env.is_c_class_scope and not env.pyfunc_entries: - return - binding = env.directives['binding'] - - code.putln("") - wrapper_code_writer = code.insertion_point() - - code.putln( - "static PyMethodDef %s[] = {" % ( - env.method_table_cname)) - for entry in env.pyfunc_entries: - if not entry.fused_cfunction and not (binding and entry.is_overridable): - code.put_pymethoddef(entry, ",", wrapper_code_writer=wrapper_code_writer) - code.putln( - "{0, 0, 0, 0}") - code.putln( - "};") - - if wrapper_code_writer.getvalue(): - wrapper_code_writer.putln("") - - def generate_dict_getter_function(self, scope, code): - dict_attr = scope.lookup_here("__dict__") - if not dict_attr or not dict_attr.is_variable: - return - func_name = scope.mangle_internal("__dict__getter") - dict_name = dict_attr.cname - code.putln("") - code.putln("static PyObject *%s(PyObject *o, CYTHON_UNUSED void *x) {" % func_name) - self.generate_self_cast(scope, code) - code.putln("if (unlikely(!p->%s)){" % dict_name) - code.putln("p->%s = PyDict_New();" % dict_name) - code.putln("}") - code.putln("Py_XINCREF(p->%s);" % dict_name) - code.putln("return p->%s;" % dict_name) - code.putln("}") - - def generate_getset_table(self, env, code): - if env.property_entries: - code.putln("") - code.putln( - "static struct PyGetSetDef %s[] = {" % - env.getset_table_cname) - for entry in env.property_entries: - doc = entry.doc - if doc: - if doc.is_unicode: - doc = doc.as_utf8_string() - doc_code = doc.as_c_string_literal() - else: - doc_code = "0" - code.putln( - '{(char *)"%s", %s, %s, (char *)%s, 0},' % ( - entry.name, - entry.getter_cname or "0", - entry.setter_cname or "0", - doc_code)) - code.putln( - "{0, 0, 0, 0, 0}") - code.putln( - "};") - - def create_import_star_conversion_utility_code(self, env): - # Create all conversion helpers that are needed for "import *" assignments. - # Must be done before code generation to support CythonUtilityCode. - for name, entry in sorted(env.entries.items()): - if entry.is_cglobal and entry.used: - if not entry.type.is_pyobject: - entry.type.create_from_py_utility_code(env) - - def generate_import_star(self, env, code): - env.use_utility_code(UtilityCode.load_cached("CStringEquals", "StringTools.c")) - code.putln() - code.enter_cfunc_scope() # as we need labels - code.putln("static int %s(PyObject *o, PyObject* py_name, char *name) {" % Naming.import_star_set) - - code.putln("static const char* internal_type_names[] = {") - for name, entry in sorted(env.entries.items()): - if entry.is_type: - code.putln('"%s",' % name) - code.putln("0") - code.putln("};") - - code.putln("const char** type_name = internal_type_names;") - code.putln("while (*type_name) {") - code.putln("if (__Pyx_StrEq(name, *type_name)) {") - code.putln('PyErr_Format(PyExc_TypeError, "Cannot overwrite C type %s", name);') - code.putln('goto bad;') - code.putln("}") - code.putln("type_name++;") - code.putln("}") - - old_error_label = code.new_error_label() - code.putln("if (0);") # so the first one can be "else if" - msvc_count = 0 - for name, entry in sorted(env.entries.items()): - if entry.is_cglobal and entry.used and not entry.type.is_const: - msvc_count += 1 - if msvc_count % 100 == 0: - code.putln("#ifdef _MSC_VER") - code.putln("if (0); /* Workaround for MSVC C1061. */") - code.putln("#endif") - code.putln('else if (__Pyx_StrEq(name, "%s")) {' % name) - if entry.type.is_pyobject: - if entry.type.is_extension_type or entry.type.is_builtin_type: - code.putln("if (!(%s)) %s;" % ( - entry.type.type_test_code("o"), - code.error_goto(entry.pos))) - code.putln("Py_INCREF(o);") - code.put_decref(entry.cname, entry.type, nanny=False) - code.putln("%s = %s;" % ( - entry.cname, - PyrexTypes.typecast(entry.type, py_object_type, "o"))) - elif entry.type.create_from_py_utility_code(env): - # if available, utility code was already created in self.prepare_utility_code() - code.putln(entry.type.from_py_call_code( - 'o', entry.cname, entry.pos, code)) - else: - code.putln('PyErr_Format(PyExc_TypeError, "Cannot convert Python object %s to %s");' % ( - name, entry.type)) - code.putln(code.error_goto(entry.pos)) - code.putln("}") - code.putln("else {") - code.putln("if (PyObject_SetAttr(%s, py_name, o) < 0) goto bad;" % Naming.module_cname) - code.putln("}") - code.putln("return 0;") - if code.label_used(code.error_label): - code.put_label(code.error_label) - # This helps locate the offending name. - code.put_add_traceback(self.full_module_name) - code.error_label = old_error_label - code.putln("bad:") - code.putln("return -1;") - code.putln("}") - code.putln("") - code.putln(UtilityCode.load_as_string("ImportStar", "ImportExport.c")[1]) - code.exit_cfunc_scope() # done with labels - - def generate_module_init_func(self, imported_modules, env, code): - subfunction = self.mod_init_subfunction(self.pos, self.scope, code) - - code.enter_cfunc_scope(self.scope) - code.putln("") - code.putln(UtilityCode.load_as_string("PyModInitFuncType", "ModuleSetupCode.c")[0]) - header2 = "__Pyx_PyMODINIT_FUNC init%s(void)" % env.module_name - header3 = "__Pyx_PyMODINIT_FUNC %s(void)" % self.mod_init_func_cname('PyInit', env) - code.putln("#if PY_MAJOR_VERSION < 3") - # Optimise for small code size as the module init function is only executed once. - code.putln("%s CYTHON_SMALL_CODE; /*proto*/" % header2) - code.putln(header2) - code.putln("#else") - code.putln("%s CYTHON_SMALL_CODE; /*proto*/" % header3) - code.putln(header3) - - # CPython 3.5+ supports multi-phase module initialisation (gives access to __spec__, __file__, etc.) - code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT") - code.putln("{") - code.putln("return PyModuleDef_Init(&%s);" % Naming.pymoduledef_cname) - code.putln("}") - - mod_create_func = UtilityCode.load_as_string("ModuleCreationPEP489", "ModuleSetupCode.c")[1] - code.put(mod_create_func) - - code.putln("") - # main module init code lives in Py_mod_exec function, not in PyInit function - code.putln("static CYTHON_SMALL_CODE int %s(PyObject *%s)" % ( - self.mod_init_func_cname(Naming.pymodule_exec_func_cname, env), - Naming.pymodinit_module_arg)) - code.putln("#endif") # PEP489 - - code.putln("#endif") # Py3 - - # start of module init/exec function (pre/post PEP 489) - code.putln("{") - - tempdecl_code = code.insertion_point() - - profile = code.globalstate.directives['profile'] - linetrace = code.globalstate.directives['linetrace'] - if profile or linetrace: - code.globalstate.use_utility_code(UtilityCode.load_cached("Profile", "Profile.c")) - - code.put_declare_refcount_context() - code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT") - # Most extension modules simply can't deal with it, and Cython isn't ready either. - # See issues listed here: https://docs.python.org/3/c-api/init.html#sub-interpreter-support - code.putln("if (%s) {" % Naming.module_cname) - # Hack: enforce single initialisation. - code.putln("if (%s == %s) return 0;" % ( - Naming.module_cname, - Naming.pymodinit_module_arg, - )) - code.putln('PyErr_SetString(PyExc_RuntimeError,' - ' "Module \'%s\' has already been imported. Re-initialisation is not supported.");' % - env.module_name) - code.putln("return -1;") - code.putln("}") - code.putln("#elif PY_MAJOR_VERSION >= 3") - # Hack: enforce single initialisation also on reimports under different names on Python 3 (with PEP 3121/489). - code.putln("if (%s) return __Pyx_NewRef(%s);" % ( - Naming.module_cname, - Naming.module_cname, - )) - code.putln("#endif") - - if profile or linetrace: - tempdecl_code.put_trace_declarations() - code.put_trace_frame_init() - - refnanny_import_code = UtilityCode.load_as_string("ImportRefnannyAPI", "ModuleSetupCode.c")[1] - code.putln(refnanny_import_code.rstrip()) - code.put_setup_refcount_context(header3) - - env.use_utility_code(UtilityCode.load("CheckBinaryVersion", "ModuleSetupCode.c")) - code.put_error_if_neg(self.pos, "__Pyx_check_binary_version()") - - code.putln("#ifdef __Pxy_PyFrame_Initialize_Offsets") - code.putln("__Pxy_PyFrame_Initialize_Offsets();") - code.putln("#endif") - code.putln("%s = PyTuple_New(0); %s" % ( - Naming.empty_tuple, code.error_goto_if_null(Naming.empty_tuple, self.pos))) - code.putln("%s = PyBytes_FromStringAndSize(\"\", 0); %s" % ( - Naming.empty_bytes, code.error_goto_if_null(Naming.empty_bytes, self.pos))) - code.putln("%s = PyUnicode_FromStringAndSize(\"\", 0); %s" % ( - Naming.empty_unicode, code.error_goto_if_null(Naming.empty_unicode, self.pos))) - - for ext_type in ('CyFunction', 'FusedFunction', 'Coroutine', 'Generator', 'AsyncGen', 'StopAsyncIteration'): - code.putln("#ifdef __Pyx_%s_USED" % ext_type) - code.put_error_if_neg(self.pos, "__pyx_%s_init()" % ext_type) - code.putln("#endif") - - code.putln("/*--- Library function declarations ---*/") - if env.directives['np_pythran']: - code.put_error_if_neg(self.pos, "_import_array()") - - code.putln("/*--- Threads initialization code ---*/") - code.putln("#if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 " - "&& defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS") - code.putln("PyEval_InitThreads();") - code.putln("#endif") - - code.putln("/*--- Module creation code ---*/") - self.generate_module_creation_code(env, code) - - code.putln("/*--- Initialize various global constants etc. ---*/") - code.put_error_if_neg(self.pos, "__Pyx_InitGlobals()") - - code.putln("#if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || " - "__PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)") - code.put_error_if_neg(self.pos, "__Pyx_init_sys_getdefaultencoding_params()") - code.putln("#endif") - - code.putln("if (%s%s) {" % (Naming.module_is_main, self.full_module_name.replace('.', '__'))) - code.put_error_if_neg(self.pos, 'PyObject_SetAttr(%s, %s, %s)' % ( - env.module_cname, - code.intern_identifier(EncodedString("__name__")), - code.intern_identifier(EncodedString("__main__")))) - code.putln("}") - - # set up __file__ and __path__, then add the module to sys.modules - self.generate_module_import_setup(env, code) - - if Options.cache_builtins: - code.putln("/*--- Builtin init code ---*/") - code.put_error_if_neg(self.pos, "__Pyx_InitCachedBuiltins()") - - code.putln("/*--- Constants init code ---*/") - code.put_error_if_neg(self.pos, "__Pyx_InitCachedConstants()") - - code.putln("/*--- Global type/function init code ---*/") - - with subfunction("Global init code") as inner_code: - self.generate_global_init_code(env, inner_code) - - with subfunction("Variable export code") as inner_code: - self.generate_c_variable_export_code(env, inner_code) - - with subfunction("Function export code") as inner_code: - self.generate_c_function_export_code(env, inner_code) - - with subfunction("Type init code") as inner_code: - self.generate_type_init_code(env, inner_code) - - with subfunction("Type import code") as inner_code: - for module in imported_modules: - self.generate_type_import_code_for_module(module, env, inner_code) - - with subfunction("Variable import code") as inner_code: - for module in imported_modules: - self.generate_c_variable_import_code_for_module(module, env, inner_code) - - with subfunction("Function import code") as inner_code: - for module in imported_modules: - self.specialize_fused_types(module) - self.generate_c_function_import_code_for_module(module, env, inner_code) - - code.putln("/*--- Execution code ---*/") - code.mark_pos(None) - - code.putln("#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)") - code.put_error_if_neg(self.pos, "__Pyx_patch_abc()") - code.putln("#endif") - - if profile or linetrace: - code.put_trace_call(header3, self.pos, nogil=not code.funcstate.gil_owned) - code.funcstate.can_trace = True - - self.body.generate_execution_code(code) - - if profile or linetrace: - code.funcstate.can_trace = False - code.put_trace_return("Py_None", nogil=not code.funcstate.gil_owned) - - code.putln() - code.putln("/*--- Wrapped vars code ---*/") - self.generate_wrapped_entries_code(env, code) - code.putln() - - if Options.generate_cleanup_code: - code.globalstate.use_utility_code( - UtilityCode.load_cached("RegisterModuleCleanup", "ModuleSetupCode.c")) - code.putln("if (__Pyx_RegisterCleanup()) %s;" % code.error_goto(self.pos)) - - code.put_goto(code.return_label) - code.put_label(code.error_label) - for cname, type in code.funcstate.all_managed_temps(): - code.put_xdecref(cname, type) - code.putln('if (%s) {' % env.module_cname) - code.putln('if (%s) {' % env.module_dict_cname) - code.put_add_traceback("init %s" % env.qualified_name) - code.globalstate.use_utility_code(Nodes.traceback_utility_code) - # Module reference and module dict are in global variables which might still be needed - # for cleanup, atexit code, etc., so leaking is better than crashing. - # At least clearing the module dict here might be a good idea, but could still break - # user code in atexit or other global registries. - ##code.put_decref_clear(env.module_dict_cname, py_object_type, nanny=False) - code.putln('}') - code.put_decref_clear(env.module_cname, py_object_type, nanny=False, clear_before_decref=True) - code.putln('} else if (!PyErr_Occurred()) {') - code.putln('PyErr_SetString(PyExc_ImportError, "init %s");' % env.qualified_name) - code.putln('}') - code.put_label(code.return_label) - - code.put_finish_refcount_context() - - code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT") - code.putln("return (%s != NULL) ? 0 : -1;" % env.module_cname) - code.putln("#elif PY_MAJOR_VERSION >= 3") - code.putln("return %s;" % env.module_cname) - code.putln("#else") - code.putln("return;") - code.putln("#endif") - code.putln('}') - - tempdecl_code.put_temp_declarations(code.funcstate) - - code.exit_cfunc_scope() - - def mod_init_subfunction(self, pos, scope, orig_code): - """ - Return a context manager that allows deviating the module init code generation - into a separate function and instead inserts a call to it. - - Can be reused sequentially to create multiple functions. - The functions get inserted at the point where the context manager was created. - The call gets inserted where the context manager is used (on entry). - """ - prototypes = orig_code.insertion_point() - prototypes.putln("") - function_code = orig_code.insertion_point() - function_code.putln("") - - class ModInitSubfunction(object): - def __init__(self, code_type): - cname = '_'.join(code_type.lower().split()) - assert re.match("^[a-z0-9_]+$", cname) - self.cfunc_name = "__Pyx_modinit_%s" % cname - self.description = code_type - self.tempdecl_code = None - self.call_code = None - - def __enter__(self): - self.call_code = orig_code.insertion_point() - code = function_code - code.enter_cfunc_scope(scope) - prototypes.putln("static CYTHON_SMALL_CODE int %s(void); /*proto*/" % self.cfunc_name) - code.putln("static int %s(void) {" % self.cfunc_name) - code.put_declare_refcount_context() - self.tempdecl_code = code.insertion_point() - code.put_setup_refcount_context(self.cfunc_name) - # Leave a grepable marker that makes it easy to find the generator source. - code.putln("/*--- %s ---*/" % self.description) - return code - - def __exit__(self, *args): - code = function_code - code.put_finish_refcount_context() - code.putln("return 0;") - - self.tempdecl_code.put_temp_declarations(code.funcstate) - self.tempdecl_code = None - - needs_error_handling = code.label_used(code.error_label) - if needs_error_handling: - code.put_label(code.error_label) - for cname, type in code.funcstate.all_managed_temps(): - code.put_xdecref(cname, type) - code.put_finish_refcount_context() - code.putln("return -1;") - code.putln("}") - code.exit_cfunc_scope() - code.putln("") - - if needs_error_handling: - self.call_code.putln( - self.call_code.error_goto_if_neg("%s()" % self.cfunc_name, pos)) - else: - self.call_code.putln("(void)%s();" % self.cfunc_name) - self.call_code = None - - return ModInitSubfunction - - def generate_module_import_setup(self, env, code): - module_path = env.directives['set_initial_path'] - if module_path == 'SOURCEFILE': - module_path = self.pos[0].filename - - if module_path: - code.putln('if (!CYTHON_PEP489_MULTI_PHASE_INIT) {') - code.putln('if (PyObject_SetAttrString(%s, "__file__", %s) < 0) %s;' % ( - env.module_cname, - code.globalstate.get_py_string_const( - EncodedString(decode_filename(module_path))).cname, - code.error_goto(self.pos))) - code.putln("}") - - if env.is_package: - # set __path__ to mark the module as package - code.putln('if (!CYTHON_PEP489_MULTI_PHASE_INIT) {') - temp = code.funcstate.allocate_temp(py_object_type, True) - code.putln('%s = Py_BuildValue("[O]", %s); %s' % ( - temp, - code.globalstate.get_py_string_const( - EncodedString(decode_filename( - os.path.dirname(module_path)))).cname, - code.error_goto_if_null(temp, self.pos))) - code.put_gotref(temp) - code.putln( - 'if (PyObject_SetAttrString(%s, "__path__", %s) < 0) %s;' % ( - env.module_cname, temp, code.error_goto(self.pos))) - code.put_decref_clear(temp, py_object_type) - code.funcstate.release_temp(temp) - code.putln("}") - - elif env.is_package: - # packages require __path__, so all we can do is try to figure - # out the module path at runtime by rerunning the import lookup - code.putln("if (!CYTHON_PEP489_MULTI_PHASE_INIT) {") - package_name, _ = self.full_module_name.rsplit('.', 1) - if '.' in package_name: - parent_name = '"%s"' % (package_name.rsplit('.', 1)[0],) - else: - parent_name = 'NULL' - code.globalstate.use_utility_code(UtilityCode.load( - "SetPackagePathFromImportLib", "ImportExport.c")) - code.putln(code.error_goto_if_neg( - '__Pyx_SetPackagePathFromImportLib(%s, %s)' % ( - parent_name, - code.globalstate.get_py_string_const( - EncodedString(env.module_name)).cname), - self.pos)) - code.putln("}") - - # CPython may not have put us into sys.modules yet, but relative imports and reimports require it - fq_module_name = self.full_module_name - if fq_module_name.endswith('.__init__'): - fq_module_name = fq_module_name[:-len('.__init__')] - code.putln("#if PY_MAJOR_VERSION >= 3") - code.putln("{") - code.putln("PyObject *modules = PyImport_GetModuleDict(); %s" % - code.error_goto_if_null("modules", self.pos)) - code.putln('if (!PyDict_GetItemString(modules, "%s")) {' % fq_module_name) - code.putln(code.error_goto_if_neg('PyDict_SetItemString(modules, "%s", %s)' % ( - fq_module_name, env.module_cname), self.pos)) - code.putln("}") - code.putln("}") - code.putln("#endif") - - def generate_module_cleanup_func(self, env, code): - if not Options.generate_cleanup_code: - return - - code.putln('static void %s(CYTHON_UNUSED PyObject *self) {' % - Naming.cleanup_cname) - code.enter_cfunc_scope(env) - - if Options.generate_cleanup_code >= 2: - code.putln("/*--- Global cleanup code ---*/") - rev_entries = list(env.var_entries) - rev_entries.reverse() - for entry in rev_entries: - if entry.visibility != 'extern': - if entry.type.is_pyobject and entry.used: - code.put_xdecref_clear( - entry.cname, entry.type, - clear_before_decref=True, - nanny=False) - code.putln("__Pyx_CleanupGlobals();") - if Options.generate_cleanup_code >= 3: - code.putln("/*--- Type import cleanup code ---*/") - for ext_type in sorted(env.types_imported, key=operator.attrgetter('typeptr_cname')): - code.put_xdecref_clear( - ext_type.typeptr_cname, ext_type, - clear_before_decref=True, - nanny=False) - if Options.cache_builtins: - code.putln("/*--- Builtin cleanup code ---*/") - for entry in env.cached_builtins: - code.put_xdecref_clear( - entry.cname, PyrexTypes.py_object_type, - clear_before_decref=True, - nanny=False) - code.putln("/*--- Intern cleanup code ---*/") - code.put_decref_clear(Naming.empty_tuple, - PyrexTypes.py_object_type, - clear_before_decref=True, - nanny=False) - for entry in env.c_class_entries: - cclass_type = entry.type - if cclass_type.is_external or cclass_type.base_type: - continue - if cclass_type.scope.directives.get('freelist', 0): - scope = cclass_type.scope - freelist_name = scope.mangle_internal(Naming.freelist_name) - freecount_name = scope.mangle_internal(Naming.freecount_name) - code.putln("while (%s > 0) {" % freecount_name) - code.putln("PyObject* o = (PyObject*)%s[--%s];" % ( - freelist_name, freecount_name)) - code.putln("(*Py_TYPE(o)->tp_free)(o);") - code.putln("}") -# for entry in env.pynum_entries: -# code.put_decref_clear(entry.cname, -# PyrexTypes.py_object_type, -# nanny=False) -# for entry in env.all_pystring_entries: -# if entry.is_interned: -# code.put_decref_clear(entry.pystring_cname, -# PyrexTypes.py_object_type, -# nanny=False) -# for entry in env.default_entries: -# if entry.type.is_pyobject and entry.used: -# code.putln("Py_DECREF(%s); %s = 0;" % ( -# code.entry_as_pyobject(entry), entry.cname)) - if Options.pre_import is not None: - code.put_decref_clear(Naming.preimport_cname, py_object_type, - nanny=False, clear_before_decref=True) - for cname in [env.module_dict_cname, Naming.cython_runtime_cname, Naming.builtins_cname]: - code.put_decref_clear(cname, py_object_type, nanny=False, clear_before_decref=True) - - def generate_main_method(self, env, code): - module_is_main = "%s%s" % (Naming.module_is_main, self.full_module_name.replace('.', '__')) - if Options.embed == "main": - wmain = "wmain" - else: - wmain = Options.embed - main_method = UtilityCode.load_cached("MainFunction", "Embed.c") - code.globalstate.use_utility_code( - main_method.specialize( - module_name=env.module_name, - module_is_main=module_is_main, - main_method=Options.embed, - wmain_method=wmain)) - - def mod_init_func_cname(self, prefix, env): - return '%s_%s' % (prefix, env.module_name) - - def generate_pymoduledef_struct(self, env, code): - if env.doc: - doc = "%s" % code.get_string_const(env.doc) - else: - doc = "0" - if Options.generate_cleanup_code: - cleanup_func = "(freefunc)%s" % Naming.cleanup_cname - else: - cleanup_func = 'NULL' - - code.putln("") - code.putln("#if PY_MAJOR_VERSION >= 3") - code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT") - exec_func_cname = self.mod_init_func_cname(Naming.pymodule_exec_func_cname, env) - code.putln("static PyObject* %s(PyObject *spec, PyModuleDef *def); /*proto*/" % - Naming.pymodule_create_func_cname) - code.putln("static int %s(PyObject* module); /*proto*/" % exec_func_cname) - - code.putln("static PyModuleDef_Slot %s[] = {" % Naming.pymoduledef_slots_cname) - code.putln("{Py_mod_create, (void*)%s}," % Naming.pymodule_create_func_cname) - code.putln("{Py_mod_exec, (void*)%s}," % exec_func_cname) - code.putln("{0, NULL}") - code.putln("};") - code.putln("#endif") - - code.putln("") - code.putln("static struct PyModuleDef %s = {" % Naming.pymoduledef_cname) - code.putln(" PyModuleDef_HEAD_INIT,") - code.putln(' "%s",' % env.module_name) - code.putln(" %s, /* m_doc */" % doc) - code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT") - code.putln(" 0, /* m_size */") - code.putln("#else") - code.putln(" -1, /* m_size */") - code.putln("#endif") - code.putln(" %s /* m_methods */," % env.method_table_cname) - code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT") - code.putln(" %s, /* m_slots */" % Naming.pymoduledef_slots_cname) - code.putln("#else") - code.putln(" NULL, /* m_reload */") - code.putln("#endif") - code.putln(" NULL, /* m_traverse */") - code.putln(" NULL, /* m_clear */") - code.putln(" %s /* m_free */" % cleanup_func) - code.putln("};") - code.putln("#endif") - - def generate_module_creation_code(self, env, code): - # Generate code to create the module object and - # install the builtins. - if env.doc: - doc = "%s" % code.get_string_const(env.doc) - else: - doc = "0" - - code.putln("#if CYTHON_PEP489_MULTI_PHASE_INIT") - code.putln("%s = %s;" % ( - env.module_cname, - Naming.pymodinit_module_arg)) - code.put_incref(env.module_cname, py_object_type, nanny=False) - code.putln("#else") - code.putln("#if PY_MAJOR_VERSION < 3") - code.putln( - '%s = Py_InitModule4("%s", %s, %s, 0, PYTHON_API_VERSION); Py_XINCREF(%s);' % ( - env.module_cname, - env.module_name, - env.method_table_cname, - doc, - env.module_cname)) - code.putln("#else") - code.putln( - "%s = PyModule_Create(&%s);" % ( - env.module_cname, - Naming.pymoduledef_cname)) - code.putln("#endif") - code.putln(code.error_goto_if_null(env.module_cname, self.pos)) - code.putln("#endif") # CYTHON_PEP489_MULTI_PHASE_INIT - - code.putln( - "%s = PyModule_GetDict(%s); %s" % ( - env.module_dict_cname, env.module_cname, - code.error_goto_if_null(env.module_dict_cname, self.pos))) - code.put_incref(env.module_dict_cname, py_object_type, nanny=False) - - code.putln( - '%s = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); %s' % ( - Naming.builtins_cname, - code.error_goto_if_null(Naming.builtins_cname, self.pos))) - code.put_incref(Naming.builtins_cname, py_object_type, nanny=False) - code.putln( - '%s = PyImport_AddModule((char *) "cython_runtime"); %s' % ( - Naming.cython_runtime_cname, - code.error_goto_if_null(Naming.cython_runtime_cname, self.pos))) - code.put_incref(Naming.cython_runtime_cname, py_object_type, nanny=False) - code.putln( - 'if (PyObject_SetAttrString(%s, "__builtins__", %s) < 0) %s;' % ( - env.module_cname, - Naming.builtins_cname, - code.error_goto(self.pos))) - if Options.pre_import is not None: - code.putln( - '%s = PyImport_AddModule("%s"); %s' % ( - Naming.preimport_cname, - Options.pre_import, - code.error_goto_if_null(Naming.preimport_cname, self.pos))) - code.put_incref(Naming.preimport_cname, py_object_type, nanny=False) - - def generate_global_init_code(self, env, code): - # Generate code to initialise global PyObject * - # variables to None. - for entry in env.var_entries: - if entry.visibility != 'extern': - if entry.used: - entry.type.global_init_code(entry, code) - - def generate_wrapped_entries_code(self, env, code): - for name, entry in sorted(env.entries.items()): - if (entry.create_wrapper - and not entry.is_type - and entry.scope is env): - if not entry.type.create_to_py_utility_code(env): - error(entry.pos, "Cannot convert '%s' to Python object" % entry.type) - code.putln("{") - code.putln("PyObject* wrapped = %s(%s);" % ( - entry.type.to_py_function, - entry.cname)) - code.putln(code.error_goto_if_null("wrapped", entry.pos)) - code.putln( - 'if (PyObject_SetAttrString(%s, "%s", wrapped) < 0) %s;' % ( - env.module_cname, - name, - code.error_goto(entry.pos))) - code.putln("}") - - def generate_c_variable_export_code(self, env, code): - # Generate code to create PyCFunction wrappers for exported C functions. - entries = [] - for entry in env.var_entries: - if (entry.api - or entry.defined_in_pxd - or (Options.cimport_from_pyx and not entry.visibility == 'extern')): - entries.append(entry) - if entries: - env.use_utility_code(UtilityCode.load_cached("VoidPtrExport", "ImportExport.c")) - for entry in entries: - signature = entry.type.empty_declaration_code() - name = code.intern_identifier(entry.name) - code.putln('if (__Pyx_ExportVoidPtr(%s, (void *)&%s, "%s") < 0) %s' % ( - name, entry.cname, signature, - code.error_goto(self.pos))) - - def generate_c_function_export_code(self, env, code): - # Generate code to create PyCFunction wrappers for exported C functions. - entries = [] - for entry in env.cfunc_entries: - if (entry.api - or entry.defined_in_pxd - or (Options.cimport_from_pyx and not entry.visibility == 'extern')): - entries.append(entry) - if entries: - env.use_utility_code( - UtilityCode.load_cached("FunctionExport", "ImportExport.c")) - # Note: while this looks like it could be more cheaply stored and read from a struct array, - # investigation shows that the resulting binary is smaller with repeated functions calls. - for entry in entries: - signature = entry.type.signature_string() - code.putln('if (__Pyx_ExportFunction("%s", (void (*)(void))%s, "%s") < 0) %s' % ( - entry.name, - entry.cname, - signature, - code.error_goto(self.pos))) - - def generate_type_import_code_for_module(self, module, env, code): - # Generate type import code for all exported extension types in - # an imported module. - #if module.c_class_entries: - with ModuleImportGenerator(code) as import_generator: - for entry in module.c_class_entries: - if entry.defined_in_pxd: - self.generate_type_import_code(env, entry.type, entry.pos, code, import_generator) - - def specialize_fused_types(self, pxd_env): - """ - If fused c(p)def functions are defined in an imported pxd, but not - used in this implementation file, we still have fused entries and - not specialized ones. This method replaces any fused entries with their - specialized ones. - """ - for entry in pxd_env.cfunc_entries[:]: - if entry.type.is_fused: - # This call modifies the cfunc_entries in-place - entry.type.get_all_specialized_function_types() - - def generate_c_variable_import_code_for_module(self, module, env, code): - # Generate import code for all exported C functions in a cimported module. - entries = [] - for entry in module.var_entries: - if entry.defined_in_pxd: - entries.append(entry) - if entries: - env.use_utility_code( - UtilityCode.load_cached("VoidPtrImport", "ImportExport.c")) - temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True) - code.putln( - '%s = PyImport_ImportModule("%s"); if (!%s) %s' % ( - temp, - module.qualified_name, - temp, - code.error_goto(self.pos))) - code.put_gotref(temp) - for entry in entries: - if env is module: - cname = entry.cname - else: - cname = module.mangle(Naming.varptr_prefix, entry.name) - signature = entry.type.empty_declaration_code() - code.putln( - 'if (__Pyx_ImportVoidPtr(%s, "%s", (void **)&%s, "%s") < 0) %s' % ( - temp, entry.name, cname, signature, - code.error_goto(self.pos))) - code.put_decref_clear(temp, py_object_type) - code.funcstate.release_temp(temp) - - def generate_c_function_import_code_for_module(self, module, env, code): - # Generate import code for all exported C functions in a cimported module. - entries = [] - for entry in module.cfunc_entries: - if entry.defined_in_pxd and entry.used: - entries.append(entry) - if entries: - env.use_utility_code( - UtilityCode.load_cached("FunctionImport", "ImportExport.c")) - temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True) - code.putln( - '%s = PyImport_ImportModule("%s"); if (!%s) %s' % ( - temp, - module.qualified_name, - temp, - code.error_goto(self.pos))) - code.put_gotref(temp) - for entry in entries: - code.putln( - 'if (__Pyx_ImportFunction(%s, "%s", (void (**)(void))&%s, "%s") < 0) %s' % ( - temp, - entry.name, - entry.cname, - entry.type.signature_string(), - code.error_goto(self.pos))) - code.put_decref_clear(temp, py_object_type) - code.funcstate.release_temp(temp) - - def generate_type_init_code(self, env, code): - # Generate type import code for extern extension types - # and type ready code for non-extern ones. - with ModuleImportGenerator(code) as import_generator: - for entry in env.c_class_entries: - if entry.visibility == 'extern' and not entry.utility_code_definition: - self.generate_type_import_code(env, entry.type, entry.pos, code, import_generator) - else: - self.generate_base_type_import_code(env, entry, code, import_generator) - self.generate_exttype_vtable_init_code(entry, code) - if entry.type.early_init: - self.generate_type_ready_code(entry, code) - - def generate_base_type_import_code(self, env, entry, code, import_generator): - base_type = entry.type.base_type - if (base_type and base_type.module_name != env.qualified_name and not - base_type.is_builtin_type and not entry.utility_code_definition): - self.generate_type_import_code(env, base_type, self.pos, code, import_generator) - - def generate_type_import_code(self, env, type, pos, code, import_generator): - # If not already done, generate code to import the typeobject of an - # extension type defined in another module, and extract its C method - # table pointer if any. - if type in env.types_imported: - return - if type.name not in Code.ctypedef_builtins_map: - # see corresponding condition in generate_type_import_call() below! - code.globalstate.use_utility_code( - UtilityCode.load_cached("TypeImport", "ImportExport.c")) - self.generate_type_import_call(type, code, import_generator, error_pos=pos) - if type.vtabptr_cname: - code.globalstate.use_utility_code( - UtilityCode.load_cached('GetVTable', 'ImportExport.c')) - code.putln("%s = (struct %s*)__Pyx_GetVtable(%s->tp_dict); %s" % ( - type.vtabptr_cname, - type.vtabstruct_cname, - type.typeptr_cname, - code.error_goto_if_null(type.vtabptr_cname, pos))) - env.types_imported.add(type) - - def generate_type_import_call(self, type, code, import_generator, error_code=None, error_pos=None): - if type.typedef_flag: - objstruct = type.objstruct_cname - else: - objstruct = "struct %s" % type.objstruct_cname - sizeof_objstruct = objstruct - module_name = type.module_name - condition = replacement = None - if module_name not in ('__builtin__', 'builtins'): - module_name = '"%s"' % module_name - elif type.name in Code.ctypedef_builtins_map: - # Fast path for special builtins, don't actually import - ctypename = Code.ctypedef_builtins_map[type.name] - code.putln('%s = %s;' % (type.typeptr_cname, ctypename)) - return - else: - module_name = '__Pyx_BUILTIN_MODULE_NAME' - if type.name in Code.non_portable_builtins_map: - condition, replacement = Code.non_portable_builtins_map[type.name] - if objstruct in Code.basicsize_builtins_map: - # Some builtin types have a tp_basicsize which differs from sizeof(...): - sizeof_objstruct = Code.basicsize_builtins_map[objstruct] - - if not error_code: - assert error_pos is not None - error_code = code.error_goto(error_pos) - - module = import_generator.imported_module(module_name, error_code) - code.put('%s = __Pyx_ImportType(%s, %s,' % ( - type.typeptr_cname, - module, - module_name)) - - if condition and replacement: - code.putln("") # start in new line - code.putln("#if %s" % condition) - code.putln('"%s",' % replacement) - code.putln("#else") - code.putln('"%s",' % type.name) - code.putln("#endif") - else: - code.put(' "%s", ' % type.name) - - if sizeof_objstruct != objstruct: - if not condition: - code.putln("") # start in new line - code.putln("#if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000") - code.putln('sizeof(%s),' % objstruct) - code.putln("#else") - code.putln('sizeof(%s),' % sizeof_objstruct) - code.putln("#endif") - else: - code.put('sizeof(%s), ' % objstruct) - - # check_size - if type.check_size and type.check_size in ('error', 'warn', 'ignore'): - check_size = type.check_size - elif not type.is_external or type.is_subclassed: - check_size = 'error' - else: - raise RuntimeError("invalid value for check_size '%s' when compiling %s.%s" % ( - type.check_size, module_name, type.name)) - code.putln('__Pyx_ImportType_CheckSize_%s);' % check_size.title()) - - code.putln(' if (!%s) %s' % (type.typeptr_cname, error_code)) - - def generate_type_ready_code(self, entry, code): - Nodes.CClassDefNode.generate_type_ready_code(entry, code) - - def generate_exttype_vtable_init_code(self, entry, code): - # Generate code to initialise the C method table of an - # extension type. - type = entry.type - if type.vtable_cname: - code.putln( - "%s = &%s;" % ( - type.vtabptr_cname, - type.vtable_cname)) - if type.base_type and type.base_type.vtabptr_cname: - code.putln( - "%s.%s = *%s;" % ( - type.vtable_cname, - Naming.obj_base_cname, - type.base_type.vtabptr_cname)) - - c_method_entries = [ - entry for entry in type.scope.cfunc_entries - if entry.func_cname] - if c_method_entries: - for meth_entry in c_method_entries: - cast = meth_entry.type.signature_cast_string() - code.putln( - "%s.%s = %s%s;" % ( - type.vtable_cname, - meth_entry.cname, - cast, - meth_entry.func_cname)) - - -class ModuleImportGenerator(object): - """ - Helper to generate module import while importing external types. - This is used to avoid excessive re-imports of external modules when multiple types are looked up. - """ - def __init__(self, code, imported_modules=None): - self.code = code - self.imported = {} - if imported_modules: - for name, cname in imported_modules.items(): - self.imported['"%s"' % name] = cname - self.temps = [] # remember original import order for freeing - - def imported_module(self, module_name_string, error_code): - if module_name_string in self.imported: - return self.imported[module_name_string] - - code = self.code - temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True) - self.temps.append(temp) - code.putln('%s = PyImport_ImportModule(%s); if (unlikely(!%s)) %s' % ( - temp, module_name_string, temp, error_code)) - code.put_gotref(temp) - self.imported[module_name_string] = temp - return temp - - def __enter__(self): - return self - - def __exit__(self, *exc): - code = self.code - for temp in self.temps: - code.put_decref_clear(temp, py_object_type) - code.funcstate.release_temp(temp) - - -def generate_cfunction_declaration(entry, env, code, definition): - from_cy_utility = entry.used and entry.utility_code_definition - if entry.used and entry.inline_func_in_pxd or (not entry.in_cinclude and ( - definition or entry.defined_in_pxd or entry.visibility == 'extern' or from_cy_utility)): - if entry.visibility == 'extern': - storage_class = Naming.extern_c_macro - dll_linkage = "DL_IMPORT" - elif entry.visibility == 'public': - storage_class = Naming.extern_c_macro - dll_linkage = None - elif entry.visibility == 'private': - storage_class = "static" - dll_linkage = None - else: - storage_class = "static" - dll_linkage = None - type = entry.type - - if entry.defined_in_pxd and not definition: - storage_class = "static" - dll_linkage = None - type = CPtrType(type) - - header = type.declaration_code( - entry.cname, dll_linkage=dll_linkage) - modifiers = code.build_function_modifiers(entry.func_modifiers) - code.putln("%s %s%s; /*proto*/" % ( - storage_class, - modifiers, - header)) - -#------------------------------------------------------------------------------------ -# -# Runtime support code -# -#------------------------------------------------------------------------------------ - -refnanny_utility_code = UtilityCode.load("Refnanny", "ModuleSetupCode.c") - -packed_struct_utility_code = UtilityCode(proto=""" -#if defined(__GNUC__) -#define __Pyx_PACKED __attribute__((__packed__)) -#else -#define __Pyx_PACKED -#endif -""", impl="", proto_block='utility_code_proto_before_types') - -capsule_utility_code = UtilityCode.load("Capsule") diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/absl/flags/argparse_flags.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/absl/flags/argparse_flags.py deleted file mode 100644 index dd8b505f7ddd470ba4c4e9fd5a533f5f63306a9b..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/absl/flags/argparse_flags.py +++ /dev/null @@ -1,388 +0,0 @@ -# Copyright 2018 The Abseil Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This module provides argparse integration with absl.flags. - -``argparse_flags.ArgumentParser`` is a drop-in replacement for -:class:`argparse.ArgumentParser`. It takes care of collecting and defining absl -flags in :mod:`argparse`. - -Here is a simple example:: - - # Assume the following absl.flags is defined in another module: - # - # from absl import flags - # flags.DEFINE_string('echo', None, 'The echo message.') - # - parser = argparse_flags.ArgumentParser( - description='A demo of absl.flags and argparse integration.') - parser.add_argument('--header', help='Header message to print.') - - # The parser will also accept the absl flag `--echo`. - # The `header` value is available as `args.header` just like a regular - # argparse flag. The absl flag `--echo` continues to be available via - # `absl.flags.FLAGS` if you want to access it. - args = parser.parse_args() - - # Example usages: - # ./program --echo='A message.' --header='A header' - # ./program --header 'A header' --echo 'A message.' - - -Here is another example demonstrates subparsers:: - - parser = argparse_flags.ArgumentParser(description='A subcommands demo.') - parser.add_argument('--header', help='The header message to print.') - - subparsers = parser.add_subparsers(help='The command to execute.') - - roll_dice_parser = subparsers.add_parser( - 'roll_dice', help='Roll a dice.', - # By default, absl flags can also be specified after the sub-command. - # To only allow them before sub-command, pass - # `inherited_absl_flags=None`. - inherited_absl_flags=None) - roll_dice_parser.add_argument('--num_faces', type=int, default=6) - roll_dice_parser.set_defaults(command=roll_dice) - - shuffle_parser = subparsers.add_parser('shuffle', help='Shuffle inputs.') - shuffle_parser.add_argument( - 'inputs', metavar='I', nargs='+', help='Inputs to shuffle.') - shuffle_parser.set_defaults(command=shuffle) - - args = parser.parse_args(argv[1:]) - args.command(args) - - # Example usages: - # ./program --echo='A message.' roll_dice --num_faces=6 - # ./program shuffle --echo='A message.' 1 2 3 4 - - -There are several differences between :mod:`absl.flags` and -:mod:`~absl.flags.argparse_flags`: - -1. Flags defined with absl.flags are parsed differently when using the - argparse parser. Notably: - - 1) absl.flags allows both single-dash and double-dash for any flag, and - doesn't distinguish them; argparse_flags only allows double-dash for - flag's regular name, and single-dash for flag's ``short_name``. - 2) Boolean flags in absl.flags can be specified with ``--bool``, - ``--nobool``, as well as ``--bool=true/false`` (though not recommended); - in argparse_flags, it only allows ``--bool``, ``--nobool``. - -2. Help related flag differences: - - 1) absl.flags does not define help flags, absl.app does that; argparse_flags - defines help flags unless passed with ``add_help=False``. - 2) absl.app supports ``--helpxml``; argparse_flags does not. - 3) argparse_flags supports ``-h``; absl.app does not. -""" - -import argparse -import sys - -from absl import flags - - -_BUILT_IN_FLAGS = frozenset({ - 'help', - 'helpshort', - 'helpfull', - 'helpxml', - 'flagfile', - 'undefok', -}) - - -class ArgumentParser(argparse.ArgumentParser): - """Custom ArgumentParser class to support special absl flags.""" - - def __init__(self, **kwargs): - """Initializes ArgumentParser. - - Args: - **kwargs: same as argparse.ArgumentParser, except: - 1. It also accepts `inherited_absl_flags`: the absl flags to inherit. - The default is the global absl.flags.FLAGS instance. Pass None to - ignore absl flags. - 2. The `prefix_chars` argument must be the default value '-'. - - Raises: - ValueError: Raised when prefix_chars is not '-'. - """ - prefix_chars = kwargs.get('prefix_chars', '-') - if prefix_chars != '-': - raise ValueError( - 'argparse_flags.ArgumentParser only supports "-" as the prefix ' - 'character, found "{}".'.format(prefix_chars)) - - # Remove inherited_absl_flags before calling super. - self._inherited_absl_flags = kwargs.pop('inherited_absl_flags', flags.FLAGS) - # Now call super to initialize argparse.ArgumentParser before calling - # add_argument in _define_absl_flags. - super(ArgumentParser, self).__init__(**kwargs) - - if self.add_help: - # -h and --help are defined in super. - # Also add the --helpshort and --helpfull flags. - self.add_argument( - # Action 'help' defines a similar flag to -h/--help. - '--helpshort', action='help', - default=argparse.SUPPRESS, help=argparse.SUPPRESS) - self.add_argument( - '--helpfull', action=_HelpFullAction, - default=argparse.SUPPRESS, help='show full help message and exit') - - if self._inherited_absl_flags: - self.add_argument( - '--undefok', default=argparse.SUPPRESS, help=argparse.SUPPRESS) - self._define_absl_flags(self._inherited_absl_flags) - - def parse_known_args(self, args=None, namespace=None): - if args is None: - args = sys.argv[1:] - if self._inherited_absl_flags: - # Handle --flagfile. - # Explicitly specify force_gnu=True, since argparse behaves like - # gnu_getopt: flags can be specified after positional arguments. - args = self._inherited_absl_flags.read_flags_from_files( - args, force_gnu=True) - - undefok_missing = object() - undefok = getattr(namespace, 'undefok', undefok_missing) - - namespace, args = super(ArgumentParser, self).parse_known_args( - args, namespace) - - # For Python <= 2.7.8: https://bugs.python.org/issue9351, a bug where - # sub-parsers don't preserve existing namespace attributes. - # Restore the undefok attribute if a sub-parser dropped it. - if undefok is not undefok_missing: - namespace.undefok = undefok - - if self._inherited_absl_flags: - # Handle --undefok. At this point, `args` only contains unknown flags, - # so it won't strip defined flags that are also specified with --undefok. - # For Python <= 2.7.8: https://bugs.python.org/issue9351, a bug where - # sub-parsers don't preserve existing namespace attributes. The undefok - # attribute might not exist because a subparser dropped it. - if hasattr(namespace, 'undefok'): - args = _strip_undefok_args(namespace.undefok, args) - # absl flags are not exposed in the Namespace object. See Namespace: - # https://docs.python.org/3/library/argparse.html#argparse.Namespace. - del namespace.undefok - self._inherited_absl_flags.mark_as_parsed() - try: - self._inherited_absl_flags.validate_all_flags() - except flags.IllegalFlagValueError as e: - self.error(str(e)) - - return namespace, args - - def _define_absl_flags(self, absl_flags): - """Defines flags from absl_flags.""" - key_flags = set(absl_flags.get_key_flags_for_module(sys.argv[0])) - for name in absl_flags: - if name in _BUILT_IN_FLAGS: - # Do not inherit built-in flags. - continue - flag_instance = absl_flags[name] - # Each flags with short_name appears in FLAGS twice, so only define - # when the dictionary key is equal to the regular name. - if name == flag_instance.name: - # Suppress the flag in the help short message if it's not a main - # module's key flag. - suppress = flag_instance not in key_flags - self._define_absl_flag(flag_instance, suppress) - - def _define_absl_flag(self, flag_instance, suppress): - """Defines a flag from the flag_instance.""" - flag_name = flag_instance.name - short_name = flag_instance.short_name - argument_names = ['--' + flag_name] - if short_name: - argument_names.insert(0, '-' + short_name) - if suppress: - helptext = argparse.SUPPRESS - else: - # argparse help string uses %-formatting. Escape the literal %'s. - helptext = flag_instance.help.replace('%', '%%') - if flag_instance.boolean: - # Only add the `no` form to the long name. - argument_names.append('--no' + flag_name) - self.add_argument( - *argument_names, action=_BooleanFlagAction, help=helptext, - metavar=flag_instance.name.upper(), - flag_instance=flag_instance) - else: - self.add_argument( - *argument_names, action=_FlagAction, help=helptext, - metavar=flag_instance.name.upper(), - flag_instance=flag_instance) - - -class _FlagAction(argparse.Action): - """Action class for Abseil non-boolean flags.""" - - def __init__( - self, - option_strings, - dest, - help, # pylint: disable=redefined-builtin - metavar, - flag_instance, - default=argparse.SUPPRESS): - """Initializes _FlagAction. - - Args: - option_strings: See argparse.Action. - dest: Ignored. The flag is always defined with dest=argparse.SUPPRESS. - help: See argparse.Action. - metavar: See argparse.Action. - flag_instance: absl.flags.Flag, the absl flag instance. - default: Ignored. The flag always uses dest=argparse.SUPPRESS so it - doesn't affect the parsing result. - """ - del dest - self._flag_instance = flag_instance - super(_FlagAction, self).__init__( - option_strings=option_strings, - dest=argparse.SUPPRESS, - help=help, - metavar=metavar) - - def __call__(self, parser, namespace, values, option_string=None): - """See https://docs.python.org/3/library/argparse.html#action-classes.""" - self._flag_instance.parse(values) - self._flag_instance.using_default_value = False - - -class _BooleanFlagAction(argparse.Action): - """Action class for Abseil boolean flags.""" - - def __init__( - self, - option_strings, - dest, - help, # pylint: disable=redefined-builtin - metavar, - flag_instance, - default=argparse.SUPPRESS): - """Initializes _BooleanFlagAction. - - Args: - option_strings: See argparse.Action. - dest: Ignored. The flag is always defined with dest=argparse.SUPPRESS. - help: See argparse.Action. - metavar: See argparse.Action. - flag_instance: absl.flags.Flag, the absl flag instance. - default: Ignored. The flag always uses dest=argparse.SUPPRESS so it - doesn't affect the parsing result. - """ - del dest, default - self._flag_instance = flag_instance - flag_names = [self._flag_instance.name] - if self._flag_instance.short_name: - flag_names.append(self._flag_instance.short_name) - self._flag_names = frozenset(flag_names) - super(_BooleanFlagAction, self).__init__( - option_strings=option_strings, - dest=argparse.SUPPRESS, - nargs=0, # Does not accept values, only `--bool` or `--nobool`. - help=help, - metavar=metavar) - - def __call__(self, parser, namespace, values, option_string=None): - """See https://docs.python.org/3/library/argparse.html#action-classes.""" - if not isinstance(values, list) or values: - raise ValueError('values must be an empty list.') - if option_string.startswith('--'): - option = option_string[2:] - else: - option = option_string[1:] - if option in self._flag_names: - self._flag_instance.parse('true') - else: - if not option.startswith('no') or option[2:] not in self._flag_names: - raise ValueError('invalid option_string: ' + option_string) - self._flag_instance.parse('false') - self._flag_instance.using_default_value = False - - -class _HelpFullAction(argparse.Action): - """Action class for --helpfull flag.""" - - def __init__(self, option_strings, dest, default, help): # pylint: disable=redefined-builtin - """Initializes _HelpFullAction. - - Args: - option_strings: See argparse.Action. - dest: Ignored. The flag is always defined with dest=argparse.SUPPRESS. - default: Ignored. - help: See argparse.Action. - """ - del dest, default - super(_HelpFullAction, self).__init__( - option_strings=option_strings, - dest=argparse.SUPPRESS, - default=argparse.SUPPRESS, - nargs=0, - help=help) - - def __call__(self, parser, namespace, values, option_string=None): - """See https://docs.python.org/3/library/argparse.html#action-classes.""" - # This only prints flags when help is not argparse.SUPPRESS. - # It includes user defined argparse flags, as well as main module's - # key absl flags. Other absl flags use argparse.SUPPRESS, so they aren't - # printed here. - parser.print_help() - - absl_flags = parser._inherited_absl_flags # pylint: disable=protected-access - if absl_flags: - modules = sorted(absl_flags.flags_by_module_dict()) - main_module = sys.argv[0] - if main_module in modules: - # The main module flags are already printed in parser.print_help(). - modules.remove(main_module) - print(absl_flags._get_help_for_modules( # pylint: disable=protected-access - modules, prefix='', include_special_flags=True)) - parser.exit() - - -def _strip_undefok_args(undefok, args): - """Returns a new list of args after removing flags in --undefok.""" - if undefok: - undefok_names = set(name.strip() for name in undefok.split(',')) - undefok_names |= set('no' + name for name in undefok_names) - # Remove undefok flags. - args = [arg for arg in args if not _is_undefok(arg, undefok_names)] - return args - - -def _is_undefok(arg, undefok_names): - """Returns whether we can ignore arg based on a set of undefok flag names.""" - if not arg.startswith('-'): - return False - if arg.startswith('--'): - arg_without_dash = arg[2:] - else: - arg_without_dash = arg[1:] - if '=' in arg_without_dash: - name, _ = arg_without_dash.split('=', 1) - else: - name = arg_without_dash - if name in undefok_names: - return True - return False diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/distributed/utils.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/distributed/utils.py deleted file mode 100644 index 2c52f76aa7d60250101cdaee9a80ed3c9d58a4fa..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/fairseq/distributed/utils.py +++ /dev/null @@ -1,808 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import io -import logging -import os -import pickle -import random -import socket -import struct -import subprocess -import warnings -from argparse import Namespace -from collections import OrderedDict -from dataclasses import dataclass -from typing import Any, Dict, List, Mapping, Optional - -import torch -import torch.distributed as dist -from fairseq.dataclass.configs import DistributedTrainingConfig, FairseqConfig -from omegaconf import open_dict - -try: - import torch_xla.core.xla_model as xm -except ImportError: - xm = None - - -# Flag to indicate if we're using Megatron -# NOTE: this is a temporary hack until we move away from Megatron's model parallel init -_USE_MEGATRON = False - -# Whether to use XLA ops (e.g., on TPUs) instead of CUDA ops. -_USE_XLA = False - - -logger = logging.getLogger(__name__) - - -def is_master(cfg: DistributedTrainingConfig): - return cfg.distributed_rank == 0 - - -def infer_init_method(cfg: DistributedTrainingConfig, force_distributed=False): - if cfg.distributed_init_method is not None or cfg.tpu: - return - - num_pipelines_per_node = None - if cfg.pipeline_model_parallel: - num_pipeline_devices, num_pipelines_per_node = _pipeline_parallel_pre_init(cfg) - - if all( - key in os.environ - for key in ["MASTER_ADDR", "MASTER_PORT", "WORLD_SIZE", "RANK"] - ): - # support torch.distributed.launch - _infer_torch_distributed_launch_init(cfg) - elif cfg.distributed_port > 0: - # we can determine the init method automatically for Slurm - _infer_slurm_init(cfg, num_pipelines_per_node) - elif cfg.distributed_world_size > 1 or force_distributed: - # fallback for single node with multiple GPUs - _infer_single_node_init(cfg) - - if cfg.pipeline_model_parallel: - _pipeline_parallel_post_init(cfg, num_pipeline_devices, num_pipelines_per_node) - elif not cfg.distributed_no_spawn: - with open_dict(cfg): - cfg.distributed_num_procs = min( - torch.cuda.device_count(), cfg.distributed_world_size - ) - - -def _infer_torch_distributed_launch_init(cfg: DistributedTrainingConfig): - cfg.distributed_init_method = "env://" - cfg.distributed_world_size = int(os.environ["WORLD_SIZE"]) - cfg.distributed_rank = int(os.environ["RANK"]) - # processes are created by torch.distributed.launch - cfg.distributed_no_spawn = True - - -def _infer_slurm_init(cfg: DistributedTrainingConfig, num_pipelines_per_node): - node_list = os.environ.get("SLURM_STEP_NODELIST") - if node_list is None: - node_list = os.environ.get("SLURM_JOB_NODELIST") - if node_list is not None: - try: - hostnames = subprocess.check_output( - ["scontrol", "show", "hostnames", node_list] - ) - cfg.distributed_init_method = "tcp://{host}:{port}".format( - host=hostnames.split()[0].decode("utf-8"), - port=cfg.distributed_port, - ) - nnodes = int(os.environ.get("SLURM_NNODES")) - ntasks_per_node = os.environ.get("SLURM_NTASKS_PER_NODE") - if ntasks_per_node is not None: - ntasks_per_node = int(ntasks_per_node) - else: - ntasks = int(os.environ.get("SLURM_NTASKS")) - nnodes = int(os.environ.get("SLURM_NNODES")) - assert ntasks % nnodes == 0 - ntasks_per_node = int(ntasks / nnodes) - if ntasks_per_node == 1: - gpus_per_node = torch.cuda.device_count() - node_id = int(os.environ.get("SLURM_NODEID")) - cfg.distributed_rank = node_id * gpus_per_node - cfg.distributed_world_size = nnodes * gpus_per_node - elif cfg.pipeline_model_parallel: - assert ntasks_per_node == num_pipelines_per_node, ( - "SLURM --ntasks-per-node must match number of pipelines per " - "node (={})".format(num_pipelines_per_node) - ) - cfg.distributed_no_spawn = True - # For 4-way MP on nodes with 8 GPUs, ranks will be [0, 1] on - # the first node, [1, 2] on the second node, etc. This - # matches torch.distributed.launch. - node_id = int(os.environ.get("SLURM_NODEID")) - local_id = int(os.environ.get("SLURM_LOCALID")) - cfg.distributed_rank = node_id * num_pipelines_per_node + local_id - # In the above example, device_id will always be in [0, 1], - # which also matches torch.distributed.launch. - cfg.device_id = local_id - # We also want to set distributed_world_size to be the total - # number of pipelines across all nodes. - cfg.distributed_world_size = nnodes * num_pipelines_per_node - else: - assert ntasks_per_node == cfg.distributed_world_size // nnodes - cfg.distributed_no_spawn = True - cfg.distributed_rank = int(os.environ.get("SLURM_PROCID")) - cfg.device_id = int(os.environ.get("SLURM_LOCALID")) - except subprocess.CalledProcessError as e: # scontrol failed - raise e - except FileNotFoundError: # Slurm is not installed - pass - - -def _infer_single_node_init(cfg: DistributedTrainingConfig): - assert ( - cfg.distributed_world_size <= torch.cuda.device_count() - ), f"world size is {cfg.distributed_world_size} but have {torch.cuda.device_count()} available devices" - port = random.randint(10000, 20000) - cfg.distributed_init_method = "tcp://localhost:{port}".format(port=port) - - -def _pipeline_parallel_pre_init(cfg: DistributedTrainingConfig): - from fairseq import utils - - balance_exists = ( - cfg.pipeline_balance is not None - or cfg.pipeline_encoder_balance is not None - or cfg.pipeline_decoder_balance is not None - ) - devices_exist = ( - cfg.pipeline_devices is not None - or cfg.pipeline_encoder_devices is not None - or cfg.pipeline_decoder_devices is not None - ) - if not balance_exists: - raise ValueError( - "--pipeline-balance is currently required for pipeline model parallelism" - ) - if not devices_exist: - raise ValueError( - "--pipeline-devices is currently required for pipeline model parallelism" - ) - - cfg.pipeline_balance = utils.eval_str_list(cfg.pipeline_balance, type=int) - if cfg.pipeline_devices is not None: - cfg.pipeline_devices = utils.eval_str_list(cfg.pipeline_devices, type=int) - num_pipeline_devices = len(set(cfg.pipeline_devices)) - else: - cfg.pipeline_encoder_devices = utils.eval_str_list( - cfg.pipeline_encoder_devices, type=int - ) - cfg.pipeline_decoder_devices = utils.eval_str_list( - cfg.pipeline_decoder_devices, type=int - ) - num_pipeline_devices = len( - set(cfg.pipeline_encoder_devices + cfg.pipeline_decoder_devices) - ) - gpus_per_node = torch.cuda.device_count() - assert ( - gpus_per_node >= num_pipeline_devices - and gpus_per_node % num_pipeline_devices == 0 - ), ( - "the number of unique device IDs in --pipeline-devices must evenly divide " - "the number of GPUs per node (multi-node pipelining is not yet supported)" - ) - num_pipelines_per_node = gpus_per_node // num_pipeline_devices - return num_pipeline_devices, num_pipelines_per_node - - -def _pipeline_parallel_post_init( - cfg: DistributedTrainingConfig, num_pipeline_devices, num_pipelines_per_node -): - if not cfg.distributed_no_spawn: - # When distributed_no_spawn is False, we expect distributed_rank and - # distributed_world_size to be based on the total number of GPUs, so - # we need to correct them to be based on the number of pipelines. - assert cfg.distributed_world_size % num_pipeline_devices == 0 - cfg.distributed_world_size = cfg.distributed_world_size // num_pipeline_devices - # In the case of 4-way MP on nodes with 8 GPUs, we want - # distributed_rank to be the starting GPU index for each pipeline - # i.e., 0, 2, ... - gpus_per_node = torch.cuda.device_count() - assert cfg.distributed_rank % gpus_per_node == 0 - assert cfg.distributed_rank % num_pipeline_devices == 0 - - with open_dict(cfg): - cfg.distributed_rank = cfg.distributed_rank // num_pipeline_devices - # launch one process per pipeline - cfg.distributed_num_procs = num_pipelines_per_node - - # if we have 4-way MP on a node with 8 GPUs, we want device_ids to be 0 - # and 4, indicating the starting device IDs for each pipeline - cfg.device_id *= num_pipeline_devices - - if cfg.device_id > 0: - # if there's multiple pipelines on a node (e.g., 4-way MP on an 8 - # GPU node), we need to adjust pipeline_devices accordingly - logger.debug( - "setting CUDA device={} on rank {}".format( - cfg.device_id, cfg.distributed_rank - ) - ) - torch.cuda.set_device(cfg.device_id) - with open_dict(cfg): - cfg.pipeline_devices = [cfg.device_id + d for d in cfg.pipeline_devices] - logger.info( - "setting pipeline_devices={} on rank {}".format( - cfg.pipeline_devices, cfg.distributed_rank - ) - ) - - -def distributed_init(cfg: FairseqConfig): - if isinstance(cfg, Namespace): - from fairseq.dataclass.utils import convert_namespace_to_omegaconf - - cfg = convert_namespace_to_omegaconf(cfg) - - if not cfg.common.tpu: - if torch.distributed.is_available() and torch.distributed.is_initialized(): - warnings.warn( - "Distributed is already initialized, cannot initialize twice!" - ) - else: - logger.info( - "distributed init (rank {}): {}".format( - cfg.distributed_training.distributed_rank, - cfg.distributed_training.distributed_init_method, - ) - ) - dist.init_process_group( - backend=cfg.distributed_training.distributed_backend, - init_method=cfg.distributed_training.distributed_init_method, - world_size=cfg.distributed_training.distributed_world_size, - rank=cfg.distributed_training.distributed_rank, - ) - logger.info( - "initialized host {} as rank {}".format( - socket.gethostname(), - cfg.distributed_training.distributed_rank, - ) - ) - - # perform a dummy all-reduce to initialize the NCCL communicator - if torch.cuda.is_available(): - dist.all_reduce(torch.zeros(1).cuda()) - - cfg.distributed_training.distributed_rank = torch.distributed.get_rank() - else: - assert xm.xrt_world_size() == cfg.distributed_training.distributed_world_size - global _USE_XLA - _USE_XLA = True - cfg.distributed_training.device_id = xm.get_local_ordinal() - cfg.distributed_training.distributed_rank = xm.get_ordinal() - xm.rendezvous("distributed_init") # wait for all workers - - if is_master(cfg.distributed_training): - logging.getLogger().setLevel(logging.INFO) - else: - logging.getLogger().setLevel(logging.WARNING) - - if cfg.common.model_parallel_size > 1: - try: - from fairseq.model_parallel.megatron.mpu import ( - initialize_model_parallel, - model_parallel_cuda_manual_seed, - ) - except ImportError: - raise ImportError( - "\n\nPlease install the megatron submodule:" - "\n\n git submodule update --init " - "fairseq/model_parallel/megatron" - ) - global _USE_MEGATRON - _USE_MEGATRON = True - initialize_model_parallel(cfg.common.model_parallel_size) - model_parallel_cuda_manual_seed(cfg.common.seed) - model_part_number = get_model_parallel_rank() - cfg.checkpoint.checkpoint_suffix += "-model_part-{0}".format(model_part_number) - - if hasattr(cfg, "model") and getattr(cfg.model, "base_layers", 0) > 0: - cfg.checkpoint.checkpoint_suffix = ( - f"-rank-{cfg.distributed_training.distributed_rank}" - ) - - return cfg.distributed_training.distributed_rank - - -def distributed_main(i, main, cfg: FairseqConfig, kwargs): - cfg.distributed_training.device_id = i - if torch.cuda.is_available() and not cfg.common.cpu and not cfg.common.tpu: - torch.cuda.set_device(cfg.distributed_training.device_id) - if cfg.distributed_training.distributed_rank is None: # torch.multiprocessing.spawn - cfg.distributed_training.distributed_rank = kwargs.pop("start_rank", 0) + i - - cfg.distributed_training.distributed_rank = distributed_init(cfg) - - after_distributed_init_fn = kwargs.pop("after_distributed_init_fn", None) - if after_distributed_init_fn: - cfg = after_distributed_init_fn(cfg) - - main(cfg, **kwargs) - - if torch.distributed.is_initialized(): - torch.distributed.barrier(get_global_group()) - - -def call_main(cfg: FairseqConfig, main, **kwargs): - if cfg.distributed_training.distributed_init_method is None: - infer_init_method(cfg.distributed_training) - - if cfg.distributed_training.distributed_init_method is not None: - # distributed training - if not cfg.distributed_training.distributed_no_spawn: - start_rank = cfg.distributed_training.distributed_rank - cfg.distributed_training.distributed_rank = None # assign automatically - kwargs["start_rank"] = start_rank - torch.multiprocessing.spawn( - fn=distributed_main, - args=(main, cfg, kwargs), - nprocs=min( - torch.cuda.device_count(), - cfg.distributed_training.distributed_world_size, - ), - join=True, - ) - else: - distributed_main(cfg.distributed_training.device_id, main, cfg, kwargs) - elif cfg.common.tpu and cfg.distributed_training.distributed_world_size > 1: - import torch_xla.distributed.xla_multiprocessing as xmp - - torch.multiprocessing.set_sharing_strategy("file_system") - xmp.spawn( - fn=distributed_main, - args=(main, cfg, kwargs), - # tpu-comment: - # 8 devices in one TPU VM, is the max processes to be spawned. - # The rest is driven by xm.distributed.xla_dist - nprocs=min(cfg.distributed_training.distributed_world_size, 8), - ) - else: - # single GPU main - main(cfg, **kwargs) - - -def use_xla(): - global _USE_XLA - return _USE_XLA - - -def new_groups(grouped_ranks: List[List[int]]): - if use_xla(): - return ("tpu", grouped_ranks) - else: - groups = [dist.new_group(g) for g in grouped_ranks] - my_group_idx = _find_my_group_index(grouped_ranks) - return groups[my_group_idx] - - -def _find_my_group_index(grouped_ranks): - my_rank = get_global_rank() - for i, group in enumerate(grouped_ranks): - if my_rank in group: - return i - raise RuntimeError - - -def _find_my_group(grouped_ranks): - index = _find_my_group_index(grouped_ranks) - return grouped_ranks[index] - - -def get_rank(group): - if use_xla(): - assert group[0] == "tpu" - my_group = _find_my_group(group[1]) - return my_group.index(get_global_rank()) - else: - return dist.get_rank(group=group) - - -def get_world_size(group): - if use_xla(): - assert group[0] == "tpu" - my_group = _find_my_group(group[1]) - return len(my_group) - elif torch.distributed.is_initialized(): - return dist.get_world_size(group=group) - else: - return 1 - - -def get_global_group(): - if use_xla(): - return new_groups([list(range(get_global_world_size()))]) - elif torch.distributed.is_initialized(): - if not hasattr(get_global_group, "_global_group"): - # ideally we could use torch.distributed.group.WORLD, but it seems - # to cause random NCCL hangs in some cases - get_global_group._global_group = dist.new_group() - return get_global_group._global_group - else: - return None - - -def get_global_rank(): - if use_xla(): - return xm.get_ordinal() - elif torch.distributed.is_initialized(): - return torch.distributed.get_rank() - else: - return 0 - - -def get_global_world_size(): - if use_xla(): - return xm.xrt_world_size() - elif torch.distributed.is_initialized(): - return torch.distributed.get_world_size() - else: - return 1 - - -def get_data_parallel_group(): - """Get the data parallel group the caller rank belongs to.""" - global _USE_MEGATRON - if _USE_MEGATRON: - from fairseq.model_parallel.megatron import mpu - - return mpu.get_data_parallel_group() - else: - return get_global_group() - - -def get_data_parallel_rank(): - """Return my rank for the data parallel group.""" - return get_rank(get_data_parallel_group()) - - -def get_data_parallel_world_size(): - """Return world size for the data parallel group.""" - return get_world_size(get_data_parallel_group()) - - -def get_model_parallel_group(): - global _USE_MEGATRON - if _USE_MEGATRON: - from fairseq.model_parallel.megatron import mpu - - return mpu.get_model_parallel_group() - else: - return None - - -def get_model_parallel_rank(): - """Return my rank for the model parallel group.""" - return get_rank(get_model_parallel_group()) - - -def get_model_parallel_world_size(): - """Return world size for the model parallel group.""" - return get_world_size(get_model_parallel_group()) - - -def all_reduce(tensor, group, op="sum"): - if use_xla(): - assert isinstance(group, tuple) and group[0] == "tpu" - tensor = [tensor] # wrap in a list to make xm.all_reduce in-place - return xm.all_reduce(op, tensor, groups=group[1])[0] - else: - if op == "sum": - op = dist.ReduceOp.SUM - elif op == "max": - op = dist.ReduceOp.MAX - else: - raise NotImplementedError - dist.all_reduce(tensor, op=op, group=group) - return tensor - - -def broadcast(tensor, src, group): - if use_xla(): - # XLA doesn't support broadcast, hack it with all_reduce - if get_rank(group) != src: - tensor.zero_() - all_reduce(tensor, group) - else: - dist.broadcast(tensor, src=src, group=group) - - -def all_to_all(tensor, group): - """Perform an all-to-all operation on a 1D Tensor.""" - assert tensor.dim() == 1 - split_count = get_world_size(group=group) - assert tensor.numel() % split_count == 0 - if use_xla(): - assert isinstance(group, tuple) and group[0] == "tpu" - return xm.all_to_all( - tensor, - split_dimension=0, - concat_dimension=0, - split_count=split_count, - groups=group[1], - ) - else: - output = torch.zeros_like(tensor) - dist.all_to_all_single(output, tensor, group=group) - return output - - -def all_gather(tensor, group, return_tensor=False): - """Perform an all-gather operation.""" - if use_xla(): - result = xm.all_gather(tensor, groups=group[1]) - world_size = get_world_size(group=group) - result = result.view(world_size, *tensor.size()) - if return_tensor: - return result - else: - return [result[i] for i in range(world_size)] - else: - world_size = get_world_size(group=group) - rank = get_rank(group=group) - tensor_list = [ - tensor if i == rank else torch.empty_like(tensor) for i in range(world_size) - ] - dist.all_gather(tensor_list, tensor, group=group) - if return_tensor: - return torch.stack(tensor_list, dim=0) - else: - return tensor_list - - -def all_gather_list(data, group=None, max_size=16384): - """Gathers arbitrary data from all nodes into a list. - - Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python - data. Note that *data* must be picklable and any CUDA tensors will be moved - to CPU and returned on CPU as well. - - Args: - data (Any): data from the local worker to be gathered on other workers - group: group of the collective - max_size (int, optional): maximum size of the data to be gathered - across workers - """ - from fairseq import utils - - if group is None: - group = get_global_group() - rank = get_rank(group=group) - world_size = get_world_size(group=group) - - buffer_size = max_size * world_size - if ( - not hasattr(all_gather_list, "_buffer") - or all_gather_list._buffer.numel() < buffer_size - ): - all_gather_list._buffer = torch.cuda.ByteTensor(buffer_size) - all_gather_list._cpu_buffer = torch.ByteTensor(max_size).pin_memory() - buffer = all_gather_list._buffer - buffer.zero_() - cpu_buffer = all_gather_list._cpu_buffer - - data = utils.move_to_cpu(data) - enc = pickle.dumps(data) - enc_size = len(enc) - header_size = 4 # size of header that contains the length of the encoded data - size = header_size + enc_size - if size > max_size: - raise ValueError( - "encoded data size ({}) exceeds max_size ({})".format(size, max_size) - ) - - header = struct.pack(">I", enc_size) - cpu_buffer[:size] = torch.ByteTensor(list(header + enc)) - start = rank * max_size - buffer[start : start + size].copy_(cpu_buffer[:size]) - - all_reduce(buffer, group=group) - - buffer = buffer.cpu() - try: - result = [] - for i in range(world_size): - out_buffer = buffer[i * max_size : (i + 1) * max_size] - (enc_size,) = struct.unpack(">I", bytes(out_buffer[:header_size].tolist())) - if enc_size > 0: - result.append( - pickle.loads( - bytes(out_buffer[header_size : header_size + enc_size].tolist()) - ) - ) - return result - except pickle.UnpicklingError: - raise Exception( - "Unable to unpickle data from other workers. all_gather_list requires all " - "workers to enter the function together, so this error usually indicates " - "that the workers have fallen out of sync somehow. Workers can fall out of " - "sync if one of them runs out of memory, or if there are other conditions " - "in your training script that can cause one worker to finish an epoch " - "while other workers are still iterating over their portions of the data. " - "Try rerunning with --ddp-backend=legacy_ddp and see if that helps." - ) - - -def all_reduce_dict(data: Mapping[str, Any], device, group) -> Dict[str, Any]: - """ - AllReduce a dictionary of values across workers. We separately - reduce items that are already on the device and items on CPU for - better performance. - - Args: - data (Mapping[str, Any]): dictionary of data to all-reduce, but - cannot be a nested dictionary - device (torch.device): device for the reduction - group: group of the collective - """ - data_keys = list(data.keys()) - - # We want to separately reduce items that are already on the - # device and items on CPU for performance reasons. - cpu_data = OrderedDict() - device_data = OrderedDict() - for k in data_keys: - t = data[k] - if not torch.is_tensor(t): - cpu_data[k] = torch.tensor(t, dtype=torch.double) - elif t.device.type != device.type: - cpu_data[k] = t.to(dtype=torch.double) - else: - device_data[k] = t.to(dtype=torch.double) - - def _all_reduce_dict(data: OrderedDict): - if len(data) == 0: - return data - buf = torch.cat([t.view(-1) for t in data.values()]).to(device=device) - all_reduce(buf, group=group) - split_buf = torch.split(buf.clone(), [t.numel() for t in data.values()]) - reduced_data = [t.view_as(orig) for t, orig in zip(split_buf, data.values())] - return OrderedDict(zip(data.keys(), reduced_data)) - - cpu_data = _all_reduce_dict(cpu_data) - device_data = _all_reduce_dict(device_data) - - def get_from_stack(key): - if key in cpu_data: - return cpu_data[key] - elif key in device_data: - return device_data[key] - raise KeyError - - return OrderedDict([(key, get_from_stack(key)) for key in data_keys]) - - -def broadcast_tensors( - tensors: Optional[List[torch.Tensor]], - src_rank: int, - group: object, - dist_device: Optional[torch.device] = None, -) -> List[torch.Tensor]: - """ - Broadcasts a list of tensors without other (non-src) ranks needing to know - the dtypes/shapes of the tensors. - """ - if dist_device is None: - if torch.distributed.get_backend(group) == "nccl": - dist_device = torch.device("cuda") - else: - dist_device = torch.device("cpu") - - # share metadata first to simplify transfer - is_src_rank = get_rank(group) == src_rank - if is_src_rank: - metadata = [ - {"size": t.size(), "dtype": t.dtype, "device": t.device} for t in tensors - ] - metadata = _broadcast_object_slow(metadata, src_rank, group, dist_device) - else: - metadata = _broadcast_object_slow(None, src_rank, group, dist_device) - - out_tensors = [] - for i, meta in enumerate(metadata): - if is_src_rank: - tensor = tensors[i] - broadcast(tensors[i].to(dist_device), src=src_rank, group=group) - else: - tensor = torch.zeros( - [meta["size"].numel()], dtype=meta["dtype"], device=dist_device - ) - broadcast(tensor, src=src_rank, group=group) - tensor = tensor.view(meta["size"]).to(meta["device"]) - out_tensors.append(tensor) - return out_tensors - - -def broadcast_object( - obj: Any, - src_rank: int, - group: object, - dist_device: Optional[torch.device] = None, -) -> Any: - """Broadcast an arbitrary Python object to other workers.""" - if dist_device is None: - if torch.distributed.get_backend(group) == "nccl": - dist_device = torch.device("cuda") - else: - dist_device = torch.device("cpu") - - if get_rank(group) == src_rank: - # split the tensors from the non-tensors so we can broadcast them - # directly, avoiding unnecessary serialization/deserialization - tensors = [] - obj = _split_tensors_from_obj(obj, tensors) - obj = _broadcast_object_slow(obj, src_rank, group, dist_device) - tensors = broadcast_tensors(tensors, src_rank, group, dist_device) - else: - obj = _broadcast_object_slow(None, src_rank, group, dist_device) - tensors = broadcast_tensors(None, src_rank, group, dist_device) - return _put_tensors_in_obj(obj, tensors) - - -def _broadcast_object_slow( - obj: Any, - src_rank: int, - group: object, - dist_device: torch.device, -) -> Any: - if get_rank(group) == src_rank: - # Emit data - buffer = io.BytesIO() - torch.save(obj, buffer) - buffer = torch.ByteTensor(buffer.getbuffer()).to(dist_device) - length = torch.LongTensor([len(buffer)]).to(dist_device) - broadcast(length, src=src_rank, group=group) - broadcast(buffer, src=src_rank, group=group) - else: - # Fetch from the source - length = torch.LongTensor([0]).to(dist_device) - broadcast(length, src=src_rank, group=group) - buffer = torch.ByteTensor(int(length.item())).to(dist_device) - broadcast(buffer, src=src_rank, group=group) - buffer = io.BytesIO(buffer.cpu().numpy()) - obj = torch.load(buffer, map_location="cpu") - return obj - - -@dataclass(frozen=True) -class _TensorPlaceholder: - index: int - - -def _split_tensors_from_obj(obj: Any, tensors: List[torch.Tensor]) -> Any: - if torch.is_tensor(obj): - placeholder = _TensorPlaceholder(index=len(tensors)) - tensors.append(obj) - return placeholder - elif isinstance(obj, dict): - return {k: _split_tensors_from_obj(v, tensors) for k, v in obj.items()} - elif isinstance(obj, list): - return [_split_tensors_from_obj(v, tensors) for v in obj] - elif isinstance(obj, tuple): - return tuple(_split_tensors_from_obj(v, tensors) for v in obj) - elif isinstance(obj, set): - return {_split_tensors_from_obj(v, tensors) for v in obj} - else: - return obj - - -def _put_tensors_in_obj(obj: Any, tensors: List[torch.Tensor]) -> Any: - if isinstance(obj, _TensorPlaceholder): - return tensors[obj.index] - elif isinstance(obj, dict): - return {k: _put_tensors_in_obj(v, tensors) for k, v in obj.items()} - elif isinstance(obj, list): - return [_put_tensors_in_obj(v, tensors) for v in obj] - elif isinstance(obj, tuple): - return tuple(_put_tensors_in_obj(v, tensors) for v in obj) - elif isinstance(obj, set): - return {_put_tensors_in_obj(v, tensors) for v in obj} - else: - return obj diff --git a/spaces/asbeabi/PoCs/index.html b/spaces/asbeabi/PoCs/index.html deleted file mode 100644 index 8b72ed6e93fb1317c1954a40fb637d8ba80ae9bf..0000000000000000000000000000000000000000 --- a/spaces/asbeabi/PoCs/index.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - My static Space - - - ewqe - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

-
- - diff --git a/spaces/asciicorp/hotel-chat/greeting.py b/spaces/asciicorp/hotel-chat/greeting.py deleted file mode 100644 index fb4e861e98d6451868257d805d99df642bb2e4f5..0000000000000000000000000000000000000000 --- a/spaces/asciicorp/hotel-chat/greeting.py +++ /dev/null @@ -1,18 +0,0 @@ -from langchain import OpenAI, LLMChain, PromptTemplate -from langchain.memory import ReadOnlySharedMemory -from memory import memory -import config -import os -os.environ["OPENAI_API_KEY"] = "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" - -temperature = config.DEFAULT_TEMPERATURE - -readonlymemory = ReadOnlySharedMemory(memory=memory) -llm=OpenAI(temperature=temperature) - - -template = config.GREET_TEMPLATE - -greet_prompt = PromptTemplate(template=template, input_variables=["question", "chat_history"]) - -greet_llm = LLMChain(prompt=greet_prompt, llm=llm, memory=readonlymemory, verbose=True) \ No newline at end of file diff --git a/spaces/ashercn97/AsherTesting/extensions/multimodal/multimodal_embedder.py b/spaces/ashercn97/AsherTesting/extensions/multimodal/multimodal_embedder.py deleted file mode 100644 index 626077cb80987d66af90f390e31aa2f2def76fec..0000000000000000000000000000000000000000 --- a/spaces/ashercn97/AsherTesting/extensions/multimodal/multimodal_embedder.py +++ /dev/null @@ -1,178 +0,0 @@ -import base64 -import re -from dataclasses import dataclass -from io import BytesIO -from typing import Any, List, Optional - -import torch -from PIL import Image - -from extensions.multimodal.pipeline_loader import load_pipeline -from modules import shared -from modules.logging_colors import logger -from modules.text_generation import encode, get_max_prompt_length - - -@dataclass -class PromptPart: - text: str - image: Optional[Image.Image] = None - is_image: bool = False - input_ids: Optional[torch.Tensor] = None - embedding: Optional[torch.Tensor] = None - - -class MultimodalEmbedder: - def __init__(self, params: dict): - pipeline, source = load_pipeline(params) - self.pipeline = pipeline - logger.info(f'Multimodal: loaded pipeline {self.pipeline.name()} from pipelines/{source} ({self.pipeline.__class__.__name__})') - - def _split_prompt(self, prompt: str, load_images: bool = False) -> List[PromptPart]: - """Splits a prompt into a list of `PromptParts` to separate image data from text. - It will also append `image_start` and `image_end` before and after the image, and optionally parse and load the images, - if `load_images` is `True`. - """ - parts: List[PromptPart] = [] - curr = 0 - while True: - match = re.search(r'', prompt[curr:]) - if match is None: - # no more image tokens, append the rest of the prompt - if curr > 0: - # add image end token after last image - parts.append(PromptPart(text=self.pipeline.image_end() + prompt[curr:])) - else: - parts.append(PromptPart(text=prompt)) - break - # found an image, append image start token to the text - if match.start() > 0: - parts.append(PromptPart(text=prompt[curr:curr + match.start()] + self.pipeline.image_start())) - else: - parts.append(PromptPart(text=self.pipeline.image_start())) - # append the image - parts.append(PromptPart( - text=match.group(0), - image=Image.open(BytesIO(base64.b64decode(match.group(1)))) if load_images else None, - is_image=True - )) - curr += match.end() - return parts - - def _len_in_tokens_prompt_parts(self, parts: List[PromptPart]) -> int: - """Total length in tokens of all `parts`""" - tokens = 0 - for part in parts: - if part.is_image: - tokens += self.pipeline.num_image_embeds() - elif part.input_ids is not None: - tokens += len(part.input_ids) - else: - tokens += len(encode(part.text)[0]) - return tokens - - def len_in_tokens(self, prompt: str) -> int: - """Total length in tokens for a given text `prompt`""" - parts = self._split_prompt(prompt, False) - return self._len_in_tokens_prompt_parts(parts) - - def _encode_single_text(self, part: PromptPart, add_bos_token: bool) -> PromptPart: - """Encode a single prompt `part` to `input_ids`. Returns a `PromptPart`""" - if part.is_image: - placeholders = torch.ones((self.pipeline.num_image_embeds())) * self.pipeline.placeholder_token_id() - part.input_ids = placeholders.to(shared.model.device, dtype=torch.int64) - else: - part.input_ids = encode(part.text, add_bos_token=add_bos_token)[0].to(shared.model.device, dtype=torch.int64) - return part - - @staticmethod - def _num_images(parts: List[PromptPart]) -> int: - count = 0 - for part in parts: - if part.is_image: - count += 1 - return count - - def _encode_text(self, state, parts: List[PromptPart]) -> List[PromptPart]: - """Encode text to token_ids, also truncate the prompt, if necessary. - - The chat/instruct mode should make prompts that fit in get_max_prompt_length, but if max_new_tokens are set - such that the context + min_rows don't fit, we can get a prompt which is too long. - We can't truncate image embeddings, as it leads to broken generation, so remove the images instead and warn the user - """ - encoded: List[PromptPart] = [] - for i, part in enumerate(parts): - encoded.append(self._encode_single_text(part, i == 0 and state['add_bos_token'])) - - # truncation: - max_len = get_max_prompt_length(state) - removed_images = 0 - - # 1. remove entire text/image blocks - while self._len_in_tokens_prompt_parts(encoded[1:]) > max_len: - if encoded[0].is_image: - removed_images += 1 - encoded = encoded[1:] - - # 2. check if the last prompt part doesn't need to get truncated - if self._len_in_tokens_prompt_parts(encoded) > max_len: - if encoded[0].is_image: - # don't truncate image embeddings, just remove the image, otherwise generation will be broken - removed_images += 1 - encoded = encoded[1:] - elif len(encoded) > 1 and encoded[0].text.endswith(self.pipeline.image_start()): - # see if we can keep image_start token - len_image_start = len(encode(self.pipeline.image_start(), add_bos_token=state['add_bos_token'])[0]) - if self._len_in_tokens_prompt_parts(encoded[1:]) + len_image_start > max_len: - # we can't -> remove this text, and the image - encoded = encoded[2:] - removed_images += 1 - else: - # we can -> just truncate the text - trunc_len = self._len_in_tokens_prompt_parts(encoded) - max_len - encoded[0].input_ids = encoded[0].input_ids[trunc_len:] - elif len(encoded) > 0: - # only one text left, truncate it normally - trunc_len = self._len_in_tokens_prompt_parts(encoded) - max_len - encoded[0].input_ids = encoded[0].input_ids[trunc_len:] - - # notify user if we truncated an image - if removed_images > 0: - logger.warning(f"Multimodal: removed {removed_images} image(s) from prompt. Try decreasing max_new_tokens if generation is broken") - - return encoded - - def _embed(self, parts: List[PromptPart]) -> List[PromptPart]: - # batch images - image_indicies = [i for i, part in enumerate(parts) if part.is_image] - embedded = self.pipeline.embed_images([parts[i].image for i in image_indicies]) - for i, embeds in zip(image_indicies, embedded): - parts[i].embedding = embeds - # embed text - for (i, part) in enumerate(parts): - if not part.is_image: - parts[i].embedding = self.pipeline.embed_tokens(part.input_ids) - return parts - - def _remove_old_images(self, parts: List[PromptPart], params: dict) -> List[PromptPart]: - if params['add_all_images_to_prompt']: - return parts - already_added = False - for i, part in reversed(list(enumerate(parts))): - if part.is_image: - if already_added: - parts[i].embedding = self.pipeline.placeholder_embeddings() - else: - already_added = True - return parts - - def forward(self, prompt: str, state: Any, params: dict): - prompt_parts = self._split_prompt(prompt, True) - prompt_parts = self._encode_text(state, prompt_parts) - prompt_parts = self._embed(prompt_parts) - prompt_parts = self._remove_old_images(prompt_parts, params) - embeds = tuple(part.embedding for part in prompt_parts) - ids = tuple(part.input_ids for part in prompt_parts) - input_embeds = torch.cat(embeds, dim=0) - input_ids = torch.cat(ids, dim=0) - return prompt, input_ids, input_embeds, self._num_images(prompt_parts) diff --git a/spaces/awacke1/CardGameActivity-GraphViz/app.py b/spaces/awacke1/CardGameActivity-GraphViz/app.py deleted file mode 100644 index a4188b9ce85ecf34ca387489632c404edd6fd5df..0000000000000000000000000000000000000000 --- a/spaces/awacke1/CardGameActivity-GraphViz/app.py +++ /dev/null @@ -1,53 +0,0 @@ - -import time -import re -import pandas as pd -import numpy as np -import graphviz as graphviz -import streamlit as st -from st_click_detector import click_detector - - - -dot = graphviz.Digraph() - -dot.node('ActionMechanics', 'Action Mechanics 💪') -dot.node('AuctionMechanics', 'Auction Mechanics 💰') -dot.node('AreaControlMechanics', 'Area Control Mechanics 🗺️') -dot.node('CardMechanics', 'Card Mechanics 🃏') -dot.node('CooperativeMechanics', 'Cooperative and Semi-Cooperative Mechanics 🤝') -dot.node('DiceMechanics', 'Dice Mechanics 🎲') -dot.node('MovementMechanics', 'Movement Mechanics 🏃') -dot.node('ResourceMechanics', 'Resource Mechanics 📈') -dot.node('TurnOrderMechanics', 'Turn Order Mechanics ⏳') -dot.node('SocialInteractionMechanics', 'Social Interaction Mechanics 💬') -dot.node('MemoryMechanics', 'Memory Mechanics 🧠') -dot.node('DexterityMechanics', 'Dexterity Mechanics 🤹') -dot.node('ResourceManagementMechanics', 'Resource Management Mechanics 💼') -dot.node('NarrativeMechanics', 'Narrative Mechanics 📖') -dot.node('StrategyMechanics', 'Strategy Mechanics 🎯') -dot.node('ChanceMechanics', 'Chance Mechanics 🎲') -dot.node('TimeMechanics', 'Time Mechanics ⏰') -dot.node('OtherMechanics', 'Other Mechanics 🆕') - -dot.edge('ActionMechanics', 'AuctionMechanics') -dot.edge('ActionMechanics', 'AreaControlMechanics') -dot.edge('ActionMechanics', 'CardMechanics') -dot.edge('ActionMechanics', 'CooperativeMechanics') -dot.edge('ActionMechanics', 'DiceMechanics') -dot.edge('ActionMechanics', 'MovementMechanics') -dot.edge('ActionMechanics', 'ResourceMechanics') -dot.edge('ActionMechanics', 'TurnOrderMechanics') -dot.edge('ActionMechanics', 'SocialInteractionMechanics') -dot.edge('AuctionMechanics', 'ResourceMechanics') -dot.edge('AreaControlMechanics', 'MovementMechanics') -dot.edge('CardMechanics', 'ResourceManagementMechanics') -dot.edge('CooperativeMechanics', 'ResourceMechanics') -dot.edge('DiceMechanics', 'ChanceMechanics') -dot.edge('MovementMechanics', 'ResourceManagementMechanics') -dot.edge('ResourceMechanics', 'StrategyMechanics') -dot.edge('TurnOrderMechanics', 'TimeMechanics') -dot.edge('OtherMechanics', 'ActionMechanics') - -# Draw the graph using Streamlit's graphviz_chart function -st.graphviz_chart(dot.source) diff --git a/spaces/awacke1/VizLib-TopLargeHospitalsNewJersey-03-09-2023/README.md b/spaces/awacke1/VizLib-TopLargeHospitalsNewJersey-03-09-2023/README.md deleted file mode 100644 index 243e4d688b4a0c80de3b6640d0c9efdd5df8872a..0000000000000000000000000000000000000000 --- a/spaces/awacke1/VizLib-TopLargeHospitalsNewJersey-03-09-2023/README.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: 🌎VizLib Hospital Map New Jersey 🌍 -emoji: 📣🌎🌍🔍 -colorFrom: yellow -colorTo: red -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false -license: mit ---- - -🎉 Today, we are excited to announce the launch of a new AI-powered map designed to track bird migration patterns in real-time. 🎉 - -🐦 The AI map is a product of our ongoing efforts to use AI for the greater good. - -It is designed to be user-friendly and accessible to everyone, regardless of their technical expertise. 🤓 \ No newline at end of file diff --git a/spaces/badayvedat/LLaVA/llava/model/language_model/mpt/flash_attn_triton.py b/spaces/badayvedat/LLaVA/llava/model/language_model/mpt/flash_attn_triton.py deleted file mode 100644 index c0a42186d982283add95b63d99fc118e845bcf9d..0000000000000000000000000000000000000000 --- a/spaces/badayvedat/LLaVA/llava/model/language_model/mpt/flash_attn_triton.py +++ /dev/null @@ -1,484 +0,0 @@ -""" -Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py -update imports to use 'triton_pre_mlir' - -*Experimental* implementation of FlashAttention in Triton. -Tested with triton==2.0.0.dev20221202. -Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions -other than 64: -https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207 -We'll update this implementation with the new Triton backend once this is fixed. - -We use the FlashAttention implementation from Phil Tillet a starting point. -https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py - -Changes: -- Implement both causal and non-causal attention. -- Implement both self-attention and cross-attention. -- Support arbitrary seqlens (not just multiples of 128), for both forward and backward. -- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward. -- Support attention bias. -- Speed up the forward pass a bit, and only store the LSE instead of m and l. -- Make the backward for d=128 much faster by reducing register spilling. -- Optionally parallelize the backward pass across seqlen_k, to deal with the case of -small batch size * nheads. - -Caution: -- This is an *experimental* implementation. The forward pass should be quite robust but -I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler). -- This implementation has only been tested on A100. -- If you plan to use headdim other than 64 and 128, you should test for race conditions -(due to the Triton compiler), as done in tests/test_flash_attn.py -"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions -for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident -that there are none left for other head dimensions. - -Differences between this Triton version and the CUDA version: -- Triton version doesn't support dropout. -- Triton forward is generally faster than CUDA forward, while Triton backward is -generally slower than CUDA backward. Overall Triton forward + backward is slightly slower -than CUDA forward + backward. -- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor). -- Triton version supports attention bias, while CUDA version doesn't. -""" -import math -import torch -import triton_pre_mlir as triton -import triton_pre_mlir.language as tl - -@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']}) -@triton.jit -def _fwd_kernel(Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_ob, stride_oh, stride_om, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr): - start_m = tl.program_id(0) - off_hb = tl.program_id(1) - off_b = off_hb // nheads - off_h = off_hb % nheads - offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) - offs_n = tl.arange(0, BLOCK_N) - offs_d = tl.arange(0, BLOCK_HEADDIM) - q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :]) - k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :]) - v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :]) - if BIAS_TYPE == 'vector': - b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n - elif BIAS_TYPE == 'matrix': - b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :]) - t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m - lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf') - m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf') - acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32) - if EVEN_M & EVEN_N: - if EVEN_HEADDIM: - q = tl.load(q_ptrs) - else: - q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0) - elif EVEN_HEADDIM: - q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0) - else: - q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0) - end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k) - for start_n in range(0, end_n, BLOCK_N): - start_n = tl.multiple_of(start_n, BLOCK_N) - if EVEN_N & EVEN_M: - if EVEN_HEADDIM: - k = tl.load(k_ptrs + start_n * stride_kn) - else: - k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0) - elif EVEN_HEADDIM: - k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0) - else: - k = tl.load(k_ptrs + start_n * stride_kn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0) - qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) - qk += tl.dot(q, k, trans_b=True) - if not EVEN_N: - qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float('-inf')) - if IS_CAUSAL: - qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float('-inf')) - if BIAS_TYPE != 'none': - if BIAS_TYPE == 'vector': - if EVEN_N: - bias = tl.load(b_ptrs + start_n).to(tl.float32) - else: - bias = tl.load(b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0).to(tl.float32) - bias = bias[None, :] - elif BIAS_TYPE == 'matrix': - if EVEN_M & EVEN_N: - bias = tl.load(b_ptrs + start_n).to(tl.float32) - else: - bias = tl.load(b_ptrs + start_n, mask=(offs_m[:, None] < seqlen_q) & ((start_n + offs_n)[None, :] < seqlen_k), other=0.0).to(tl.float32) - qk = qk * softmax_scale + bias - m_ij = tl.maximum(tl.max(qk, 1), lse_i) - p = tl.exp(qk - m_ij[:, None]) - else: - m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i) - p = tl.exp(qk * softmax_scale - m_ij[:, None]) - l_ij = tl.sum(p, 1) - acc_o_scale = tl.exp(m_i - m_ij) - tl.store(t_ptrs, acc_o_scale) - acc_o_scale = tl.load(t_ptrs) - acc_o = acc_o * acc_o_scale[:, None] - if EVEN_N & EVEN_M: - if EVEN_HEADDIM: - v = tl.load(v_ptrs + start_n * stride_vn) - else: - v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0) - elif EVEN_HEADDIM: - v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0) - else: - v = tl.load(v_ptrs + start_n * stride_vn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0) - p = p.to(v.dtype) - acc_o += tl.dot(p, v) - m_i = m_ij - l_i_new = tl.exp(lse_i - m_ij) + l_ij - lse_i = m_ij + tl.log(l_i_new) - o_scale = tl.exp(m_i - lse_i) - tl.store(t_ptrs, o_scale) - o_scale = tl.load(t_ptrs) - acc_o = acc_o * o_scale[:, None] - start_m = tl.program_id(0) - offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) - lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m - tl.store(lse_ptrs, lse_i) - offs_d = tl.arange(0, BLOCK_HEADDIM) - out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :]) - if EVEN_M: - if EVEN_HEADDIM: - tl.store(out_ptrs, acc_o) - else: - tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim) - elif EVEN_HEADDIM: - tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q) - else: - tl.store(out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim)) - -@triton.jit -def _bwd_preprocess_do_o_dot(Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr): - start_m = tl.program_id(0) - off_hb = tl.program_id(1) - off_b = off_hb // nheads - off_h = off_hb % nheads - offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) - offs_d = tl.arange(0, BLOCK_HEADDIM) - o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32) - do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32) - delta = tl.sum(o * do, axis=1) - tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta) - -@triton.jit -def _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr): - if EVEN_N & EVEN_M: - if EVEN_HEADDIM: - tl.store(dv_ptrs, dv) - tl.store(dk_ptrs, dk) - else: - tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim) - tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim) - elif EVEN_HEADDIM: - tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k) - tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k) - else: - tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)) - tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)) - -@triton.jit -def _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD: tl.constexpr, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr): - begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M - offs_qm = begin_m + tl.arange(0, BLOCK_M) - offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N) - offs_m = tl.arange(0, BLOCK_M) - offs_d = tl.arange(0, BLOCK_HEADDIM) - q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :]) - k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :]) - v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :]) - do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :]) - dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :]) - if BIAS_TYPE == 'vector': - b_ptrs = Bias + offs_n - elif BIAS_TYPE == 'matrix': - b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :]) - dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32) - dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32) - if begin_m >= seqlen_q: - dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :]) - dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :]) - _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM) - return - if EVEN_N & EVEN_M: - if EVEN_HEADDIM: - k = tl.load(k_ptrs) - v = tl.load(v_ptrs) - else: - k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0) - v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0) - elif EVEN_HEADDIM: - k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0) - v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0) - else: - k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0) - v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0) - num_block_m = tl.cdiv(seqlen_q, BLOCK_M) - for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M): - start_m = tl.multiple_of(start_m, BLOCK_M) - offs_m_curr = start_m + offs_m - if EVEN_M & EVEN_HEADDIM: - q = tl.load(q_ptrs) - elif EVEN_HEADDIM: - q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0) - else: - q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0) - qk = tl.dot(q, k, trans_b=True) - if not EVEN_N: - qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf')) - if IS_CAUSAL: - qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float('-inf')) - if BIAS_TYPE != 'none': - tl.debug_barrier() - if BIAS_TYPE == 'vector': - if EVEN_N: - bias = tl.load(b_ptrs).to(tl.float32) - else: - bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32) - bias = bias[None, :] - elif BIAS_TYPE == 'matrix': - if EVEN_M & EVEN_N: - bias = tl.load(b_ptrs).to(tl.float32) - else: - bias = tl.load(b_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), other=0.0).to(tl.float32) - qk = qk * softmax_scale + bias - if not EVEN_M & EVEN_HEADDIM: - tl.debug_barrier() - lse_i = tl.load(LSE + offs_m_curr) - if BIAS_TYPE == 'none': - p = tl.exp(qk * softmax_scale - lse_i[:, None]) - else: - p = tl.exp(qk - lse_i[:, None]) - if EVEN_M & EVEN_HEADDIM: - do = tl.load(do_ptrs) - else: - do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0) - dv += tl.dot(p.to(do.dtype), do, trans_a=True) - if not EVEN_M & EVEN_HEADDIM: - tl.debug_barrier() - dp = tl.dot(do, v, trans_b=True) - if not EVEN_HEADDIM: - tl.debug_barrier() - Di = tl.load(D + offs_m_curr) - ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype) - dk += tl.dot(ds, q, trans_a=True) - if not EVEN_M & EVEN_HEADDIM: - tl.debug_barrier() - if not ATOMIC_ADD: - if EVEN_M & EVEN_HEADDIM: - dq = tl.load(dq_ptrs, eviction_policy='evict_last') - dq += tl.dot(ds, k) - tl.store(dq_ptrs, dq, eviction_policy='evict_last') - elif EVEN_HEADDIM: - dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0, eviction_policy='evict_last') - dq += tl.dot(ds, k) - tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q, eviction_policy='evict_last') - else: - dq = tl.load(dq_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0, eviction_policy='evict_last') - dq += tl.dot(ds, k) - tl.store(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), eviction_policy='evict_last') - else: - dq = tl.dot(ds, k) - if EVEN_M & EVEN_HEADDIM: - tl.atomic_add(dq_ptrs, dq) - elif EVEN_HEADDIM: - tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q) - else: - tl.atomic_add(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim)) - dq_ptrs += BLOCK_M * stride_dqm - q_ptrs += BLOCK_M * stride_qm - do_ptrs += BLOCK_M * stride_dom - if BIAS_TYPE == 'matrix': - b_ptrs += BLOCK_M * stride_bm - dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :]) - dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :]) - _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM) - -def init_to_zero(name): - return lambda nargs: nargs[name].zero_() - -@triton.autotune(configs=[triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ'))], key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM']) -@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']}) -@triton.jit -def _bwd_kernel(Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_dob, stride_doh, stride_dom, stride_dqb, stride_dqh, stride_dqm, stride_dkb, stride_dkh, stride_dkn, stride_dvb, stride_dvh, stride_dvn, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, SEQUENCE_PARALLEL: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr): - off_hb = tl.program_id(1) - off_b = off_hb // nheads - off_h = off_hb % nheads - Q += off_b * stride_qb + off_h * stride_qh - K += off_b * stride_kb + off_h * stride_kh - V += off_b * stride_vb + off_h * stride_vh - DO += off_b * stride_dob + off_h * stride_doh - DQ += off_b * stride_dqb + off_h * stride_dqh - DK += off_b * stride_dkb + off_h * stride_dkh - DV += off_b * stride_dvb + off_h * stride_dvh - if BIAS_TYPE != 'none': - Bias += off_b * stride_bb + off_h * stride_bh - D += off_hb * seqlen_q_rounded - LSE += off_hb * seqlen_q_rounded - if not SEQUENCE_PARALLEL: - num_block_n = tl.cdiv(seqlen_k, BLOCK_N) - for start_n in range(0, num_block_n): - _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=False, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N) - else: - start_n = tl.program_id(0) - _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=True, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N) - -def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None): - (batch, seqlen_q, nheads, d) = q.shape - (_, seqlen_k, _, _) = k.shape - assert k.shape == (batch, seqlen_k, nheads, d) - assert v.shape == (batch, seqlen_k, nheads, d) - assert d <= 128, 'FlashAttention only support head dimensions up to 128' - assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type' - assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16' - assert q.is_cuda and k.is_cuda and v.is_cuda - softmax_scale = softmax_scale or 1.0 / math.sqrt(d) - has_bias = bias is not None - bias_type = 'none' - if has_bias: - assert bias.dtype in [q.dtype, torch.float] - assert bias.is_cuda - assert bias.dim() == 4 - if bias.stride(-1) != 1: - bias = bias.contiguous() - if bias.shape[2:] == (1, seqlen_k): - bias_type = 'vector' - elif bias.shape[2:] == (seqlen_q, seqlen_k): - bias_type = 'matrix' - else: - raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)') - bias = bias.expand(batch, nheads, seqlen_q, seqlen_k) - bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0) - seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128 - lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32) - tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32) - o = torch.empty_like(q) - BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16) - BLOCK = 128 - num_warps = 4 if d <= 64 else 8 - grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads) - _fwd_kernel[grid](q, k, v, bias, o, lse, tmp, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, o.stride(0), o.stride(2), o.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM, BLOCK_M=BLOCK, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1) - return (o, lse, softmax_scale) - -def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None): - if do.stride(-1) != 1: - do = do.contiguous() - (batch, seqlen_q, nheads, d) = q.shape - (_, seqlen_k, _, _) = k.shape - assert d <= 128 - seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128 - assert lse.shape == (batch, nheads, seqlen_q_rounded) - assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1 - assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1 - softmax_scale = softmax_scale or 1.0 / math.sqrt(d) - dq_accum = torch.empty_like(q, dtype=torch.float32) - delta = torch.empty_like(lse) - BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16) - grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads) - _bwd_preprocess_do_o_dot[grid](o, do, delta, o.stride(0), o.stride(2), o.stride(1), do.stride(0), do.stride(2), do.stride(1), nheads, seqlen_q, seqlen_q_rounded, d, BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM) - has_bias = bias is not None - bias_type = 'none' - if has_bias: - assert bias.dtype in [q.dtype, torch.float] - assert bias.is_cuda - assert bias.dim() == 4 - assert bias.stride(-1) == 1 - if bias.shape[2:] == (1, seqlen_k): - bias_type = 'vector' - elif bias.shape[2:] == (seqlen_q, seqlen_k): - bias_type = 'matrix' - else: - raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)') - bias = bias.expand(batch, nheads, seqlen_q, seqlen_k) - bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0) - grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N']) if META['SEQUENCE_PARALLEL'] else 1, batch * nheads) - _bwd_kernel[grid](q, k, v, bias, do, dq_accum, dk, dv, lse, delta, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, do.stride(0), do.stride(2), do.stride(1), dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1), dk.stride(0), dk.stride(2), dk.stride(1), dv.stride(0), dv.stride(2), dv.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM) - dq.copy_(dq_accum) - -class FlashAttnQKVPackedFunc(torch.autograd.Function): - - @staticmethod - def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None): - """ - qkv: (batch, seqlen, 3, nheads, headdim) - bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen). - For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen). - ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen) - """ - if qkv.stride(-1) != 1: - qkv = qkv.contiguous() - (o, lse, ctx.softmax_scale) = _flash_attn_forward(qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal, softmax_scale=softmax_scale) - ctx.save_for_backward(qkv, o, lse, bias) - ctx.causal = causal - return o - - @staticmethod - def backward(ctx, do): - (qkv, o, lse, bias) = ctx.saved_tensors - assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet' - with torch.inference_mode(): - dqkv = torch.empty_like(qkv) - _flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse, dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale) - return (dqkv, None, None, None) -flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply - -class FlashAttnKVPackedFunc(torch.autograd.Function): - - @staticmethod - def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None): - """ - q: (batch, seqlen_q, nheads, headdim) - kv: (batch, seqlen_k, 2, nheads, headdim) - bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k). - For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k). - ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k) - """ - (q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]] - (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale) - ctx.save_for_backward(q, kv, o, lse, bias) - ctx.causal = causal - return o - - @staticmethod - def backward(ctx, do): - (q, kv, o, lse, bias) = ctx.saved_tensors - if len(ctx.needs_input_grad) >= 3: - assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet' - with torch.inference_mode(): - dq = torch.empty_like(q) - dkv = torch.empty_like(kv) - _flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse, dq, dkv[:, :, 0], dkv[:, :, 1], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale) - return (dq, dkv, None, None, None) -flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply - -class FlashAttnFunc(torch.autograd.Function): - - @staticmethod - def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None): - """ - q: (batch_size, seqlen_q, nheads, headdim) - k, v: (batch_size, seqlen_k, nheads, headdim) - bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k). - For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k). - ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k) - """ - (q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]] - (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale) - ctx.save_for_backward(q, k, v, o, lse, bias) - ctx.causal = causal - return o - - @staticmethod - def backward(ctx, do): - (q, k, v, o, lse, bias) = ctx.saved_tensors - assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet' - with torch.inference_mode(): - dq = torch.empty_like(q) - dk = torch.empty_like(k) - dv = torch.empty_like(v) - _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale) - return (dq, dk, dv, None, None, None) -flash_attn_func = FlashAttnFunc.apply \ No newline at end of file diff --git a/spaces/basit123796/basit/app.py b/spaces/basit123796/basit/app.py deleted file mode 100644 index f1e7d807a887a1fb7b88fb7c6d10717ad13399eb..0000000000000000000000000000000000000000 --- a/spaces/basit123796/basit/app.py +++ /dev/null @@ -1,24 +0,0 @@ -import openai -import gradio as gi - - -openai.api_key = "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" - -messages = [{"role": "system", "content": "you are chatGPT"}] - - - - -def CustomChatGPT(user_input): - messages.append({"role": "user", "content": user_input}) - response = openai.ChatCompletion.create( - model = "gpt-3.5-turbo", - messages = messages - ) - ChatGPT_reply = response["choices"][0]["message"]["content"] - messages.append({"role": "assistant", "content": ChatGPT_reply}) - return ChatGPT_reply - -iface = gi.Interface(fn=CustomChatGPT, inputs = "text", outputs = "text", title = "basitGPT") -iface.launch() - diff --git a/spaces/beihai/GFPGAN-V1.3-whole-image/.history/app_20220327011459.py b/spaces/beihai/GFPGAN-V1.3-whole-image/.history/app_20220327011459.py deleted file mode 100644 index f5b1195110153fc1057059ac04749712a932992f..0000000000000000000000000000000000000000 --- a/spaces/beihai/GFPGAN-V1.3-whole-image/.history/app_20220327011459.py +++ /dev/null @@ -1,66 +0,0 @@ -import os -#os.system("pip install gfpgan") - -#os.system("pip freeze") -#os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth -P .") -import random -import gradio as gr -from PIL import Image -import torch -# torch.hub.download_url_to_file('https://upload.wikimedia.org/wikipedia/commons/thumb/a/ab/Abraham_Lincoln_O-77_matte_collodion_print.jpg/1024px-Abraham_Lincoln_O-77_matte_collodion_print.jpg', 'lincoln.jpg') -# torch.hub.download_url_to_file('https://upload.wikimedia.org/wikipedia/commons/5/50/Albert_Einstein_%28Nobel%29.png', 'einstein.png') -# torch.hub.download_url_to_file('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9d/Thomas_Edison2.jpg/1024px-Thomas_Edison2.jpg', 'edison.jpg') -# torch.hub.download_url_to_file('https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Henry_Ford_1888.jpg/1024px-Henry_Ford_1888.jpg', 'Henry.jpg') -# torch.hub.download_url_to_file('https://upload.wikimedia.org/wikipedia/commons/thumb/0/06/Frida_Kahlo%2C_by_Guillermo_Kahlo.jpg/800px-Frida_Kahlo%2C_by_Guillermo_Kahlo.jpg', 'Frida.jpg') - - -import cv2 -import glob -import numpy as np -from basicsr.utils import imwrite -from gfpgan import GFPGANer - -import warnings -warnings.warn('The unoptimized RealESRGAN is very slow on CPU. We do not use it. ' - 'If you really want to use it, please modify the corresponding codes.') -bg_upsampler = None - - - -# set up GFPGAN restorer -restorer = GFPGANer( - model_path='experiments/pretrained_models/GFPGANv1.3.pth', - upscale=2, - arch='clean', - channel_multiplier=2, - bg_upsampler=bg_upsampler) - - -def inference(img): - input_img = cv2.imread(img, cv2.IMREAD_COLOR) - cropped_faces, restored_faces, restored_img = restorer.enhance( - input_img, has_aligned=False, only_center_face=False, paste_back=True) - - #return Image.fromarray(restored_faces[0][:,:,::-1]) - return Image.fromarray(restored_img) - -title = "GFP-GAN" -description = "Gradio demo for GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below. Please click submit only once" -article = "

Towards Real-World Blind Face Restoration with Generative Facial Prior | Github Repo

visitor badge
" -gr.Interface( - inference, - [gr.inputs.Image(type="filepath", label="Input")], - gr.outputs.Image(type="pil", label="Output"), - title=title, - description=description, - article=article, - examples=[ - ['lincoln.jpg'], - ['einstein.png'], - ['edison.jpg'], - ['Henry.jpg'], - ['Frida.jpg'] - ] - ).launch(enable_queue=True,cache_examples=True) - - diff --git a/spaces/beihai/GFPGAN-V1.3-whole-image/basicsr/models/__init__.py b/spaces/beihai/GFPGAN-V1.3-whole-image/basicsr/models/__init__.py deleted file mode 100644 index 285ce3ef90550f5cd6cb61467388f8ae4b73f14a..0000000000000000000000000000000000000000 --- a/spaces/beihai/GFPGAN-V1.3-whole-image/basicsr/models/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -import importlib -from copy import deepcopy -from os import path as osp - -from basicsr.utils import get_root_logger, scandir -from basicsr.utils.registry import MODEL_REGISTRY - -__all__ = ['build_model'] - -# automatically scan and import model modules for registry -# scan all the files under the 'models' folder and collect files ending with -# '_model.py' -model_folder = osp.dirname(osp.abspath(__file__)) -model_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(model_folder) if v.endswith('_model.py')] -# import all the model modules -_model_modules = [importlib.import_module(f'basicsr.models.{file_name}') for file_name in model_filenames] - - -def build_model(opt): - """Build model from options. - - Args: - opt (dict): Configuration. It must contain: - model_type (str): Model type. - """ - opt = deepcopy(opt) - model = MODEL_REGISTRY.get(opt['model_type'])(opt) - logger = get_root_logger() - logger.info(f'Model [{model.__class__.__name__}] is created.') - return model diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/.github/CONTRIBUTING.md b/spaces/brjathu/HMR2.0/vendor/detectron2/.github/CONTRIBUTING.md deleted file mode 100644 index 9bab709cae689ba3b92dd52f7fbcc0c6926f4a38..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/.github/CONTRIBUTING.md +++ /dev/null @@ -1,68 +0,0 @@ -# Contributing to detectron2 - -## Issues -We use GitHub issues to track public bugs and questions. -Please make sure to follow one of the -[issue templates](https://github.com/facebookresearch/detectron2/issues/new/choose) -when reporting any issues. - -Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe -disclosure of security bugs. In those cases, please go through the process -outlined on that page and do not file a public issue. - -## Pull Requests -We actively welcome pull requests. - -However, if you're adding any significant features (e.g. > 50 lines), please -make sure to discuss with maintainers about your motivation and proposals in an issue -before sending a PR. This is to save your time so you don't spend time on a PR that we'll not accept. - -We do not always accept new features, and we take the following -factors into consideration: - -1. Whether the same feature can be achieved without modifying detectron2. - Detectron2 is designed so that you can implement many extensions from the outside, e.g. - those in [projects](https://github.com/facebookresearch/detectron2/tree/master/projects). - * If some part of detectron2 is not extensible enough, you can also bring up a more general issue to - improve it. Such feature request may be useful to more users. -2. Whether the feature is potentially useful to a large audience (e.g. an impactful detection paper, a popular dataset, - a significant speedup, a widely useful utility), - or only to a small portion of users (e.g., a less-known paper, an improvement not in the object - detection field, a trick that's not very popular in the community, code to handle a non-standard type of data) - * Adoption of additional models, datasets, new task are by default not added to detectron2 before they - receive significant popularity in the community. - We sometimes accept such features in `projects/`, or as a link in `projects/README.md`. -3. Whether the proposed solution has a good design / interface. This can be discussed in the issue prior to PRs, or - in the form of a draft PR. -4. Whether the proposed solution adds extra mental/practical overhead to users who don't - need such feature. -5. Whether the proposed solution breaks existing APIs. - -To add a feature to an existing function/class `Func`, there are always two approaches: -(1) add new arguments to `Func`; (2) write a new `Func_with_new_feature`. -To meet the above criteria, we often prefer approach (2), because: - -1. It does not involve modifying or potentially breaking existing code. -2. It does not add overhead to users who do not need the new feature. -3. Adding new arguments to a function/class is not scalable w.r.t. all the possible new research ideas in the future. - -When sending a PR, please do: - -1. If a PR contains multiple orthogonal changes, split it to several PRs. -2. If you've added code that should be tested, add tests. -3. For PRs that need experiments (e.g. adding a new model or new methods), - you don't need to update model zoo, but do provide experiment results in the description of the PR. -4. If APIs are changed, update the documentation. -5. We use the [Google style docstrings](https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html) in python. -6. Make sure your code lints with `./dev/linter.sh`. - - -## Contributor License Agreement ("CLA") -In order to accept your pull request, we need you to submit a CLA. You only need -to do this once to work on any of Facebook's open source projects. - -Complete your CLA here: - -## License -By contributing to detectron2, you agree that your contributions will be licensed -under the LICENSE file in the root directory of this source tree. diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/samplers/distributed_sampler.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/samplers/distributed_sampler.py deleted file mode 100644 index a098e6ac07c1b193fddcb69e6e54aced82e6081c..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/samplers/distributed_sampler.py +++ /dev/null @@ -1,278 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import itertools -import logging -import math -from collections import defaultdict -from typing import Optional -import torch -from torch.utils.data.sampler import Sampler - -from detectron2.utils import comm - -logger = logging.getLogger(__name__) - - -class TrainingSampler(Sampler): - """ - In training, we only care about the "infinite stream" of training data. - So this sampler produces an infinite stream of indices and - all workers cooperate to correctly shuffle the indices and sample different indices. - - The samplers in each worker effectively produces `indices[worker_id::num_workers]` - where `indices` is an infinite stream of indices consisting of - `shuffle(range(size)) + shuffle(range(size)) + ...` (if shuffle is True) - or `range(size) + range(size) + ...` (if shuffle is False) - - Note that this sampler does not shard based on pytorch DataLoader worker id. - A sampler passed to pytorch DataLoader is used only with map-style dataset - and will not be executed inside workers. - But if this sampler is used in a way that it gets execute inside a dataloader - worker, then extra work needs to be done to shard its outputs based on worker id. - This is required so that workers don't produce identical data. - :class:`ToIterableDataset` implements this logic. - This note is true for all samplers in detectron2. - """ - - def __init__(self, size: int, shuffle: bool = True, seed: Optional[int] = None): - """ - Args: - size (int): the total number of data of the underlying dataset to sample from - shuffle (bool): whether to shuffle the indices or not - seed (int): the initial seed of the shuffle. Must be the same - across all workers. If None, will use a random seed shared - among workers (require synchronization among all workers). - """ - if not isinstance(size, int): - raise TypeError(f"TrainingSampler(size=) expects an int. Got type {type(size)}.") - if size <= 0: - raise ValueError(f"TrainingSampler(size=) expects a positive int. Got {size}.") - self._size = size - self._shuffle = shuffle - if seed is None: - seed = comm.shared_random_seed() - self._seed = int(seed) - - self._rank = comm.get_rank() - self._world_size = comm.get_world_size() - - def __iter__(self): - start = self._rank - yield from itertools.islice(self._infinite_indices(), start, None, self._world_size) - - def _infinite_indices(self): - g = torch.Generator() - g.manual_seed(self._seed) - while True: - if self._shuffle: - yield from torch.randperm(self._size, generator=g).tolist() - else: - yield from torch.arange(self._size).tolist() - - -class RandomSubsetTrainingSampler(TrainingSampler): - """ - Similar to TrainingSampler, but only sample a random subset of indices. - This is useful when you want to estimate the accuracy vs data-number curves by - training the model with different subset_ratio. - """ - - def __init__( - self, - size: int, - subset_ratio: float, - shuffle: bool = True, - seed_shuffle: Optional[int] = None, - seed_subset: Optional[int] = None, - ): - """ - Args: - size (int): the total number of data of the underlying dataset to sample from - subset_ratio (float): the ratio of subset data to sample from the underlying dataset - shuffle (bool): whether to shuffle the indices or not - seed_shuffle (int): the initial seed of the shuffle. Must be the same - across all workers. If None, will use a random seed shared - among workers (require synchronization among all workers). - seed_subset (int): the seed to randomize the subset to be sampled. - Must be the same across all workers. If None, will use a random seed shared - among workers (require synchronization among all workers). - """ - super().__init__(size=size, shuffle=shuffle, seed=seed_shuffle) - - assert 0.0 < subset_ratio <= 1.0 - self._size_subset = int(size * subset_ratio) - assert self._size_subset > 0 - if seed_subset is None: - seed_subset = comm.shared_random_seed() - self._seed_subset = int(seed_subset) - - # randomly generate the subset indexes to be sampled from - g = torch.Generator() - g.manual_seed(self._seed_subset) - indexes_randperm = torch.randperm(self._size, generator=g) - self._indexes_subset = indexes_randperm[: self._size_subset] - - logger.info("Using RandomSubsetTrainingSampler......") - logger.info(f"Randomly sample {self._size_subset} data from the original {self._size} data") - - def _infinite_indices(self): - g = torch.Generator() - g.manual_seed(self._seed) # self._seed equals seed_shuffle from __init__() - while True: - if self._shuffle: - # generate a random permutation to shuffle self._indexes_subset - randperm = torch.randperm(self._size_subset, generator=g) - yield from self._indexes_subset[randperm].tolist() - else: - yield from self._indexes_subset.tolist() - - -class RepeatFactorTrainingSampler(Sampler): - """ - Similar to TrainingSampler, but a sample may appear more times than others based - on its "repeat factor". This is suitable for training on class imbalanced datasets like LVIS. - """ - - def __init__(self, repeat_factors, *, shuffle=True, seed=None): - """ - Args: - repeat_factors (Tensor): a float vector, the repeat factor for each indice. When it's - full of ones, it is equivalent to ``TrainingSampler(len(repeat_factors), ...)``. - shuffle (bool): whether to shuffle the indices or not - seed (int): the initial seed of the shuffle. Must be the same - across all workers. If None, will use a random seed shared - among workers (require synchronization among all workers). - """ - self._shuffle = shuffle - if seed is None: - seed = comm.shared_random_seed() - self._seed = int(seed) - - self._rank = comm.get_rank() - self._world_size = comm.get_world_size() - - # Split into whole number (_int_part) and fractional (_frac_part) parts. - self._int_part = torch.trunc(repeat_factors) - self._frac_part = repeat_factors - self._int_part - - @staticmethod - def repeat_factors_from_category_frequency(dataset_dicts, repeat_thresh): - """ - Compute (fractional) per-image repeat factors based on category frequency. - The repeat factor for an image is a function of the frequency of the rarest - category labeled in that image. The "frequency of category c" in [0, 1] is defined - as the fraction of images in the training set (without repeats) in which category c - appears. - See :paper:`lvis` (>= v2) Appendix B.2. - - Args: - dataset_dicts (list[dict]): annotations in Detectron2 dataset format. - repeat_thresh (float): frequency threshold below which data is repeated. - If the frequency is half of `repeat_thresh`, the image will be - repeated twice. - - Returns: - torch.Tensor: - the i-th element is the repeat factor for the dataset image at index i. - """ - # 1. For each category c, compute the fraction of images that contain it: f(c) - category_freq = defaultdict(int) - for dataset_dict in dataset_dicts: # For each image (without repeats) - cat_ids = {ann["category_id"] for ann in dataset_dict["annotations"]} - for cat_id in cat_ids: - category_freq[cat_id] += 1 - num_images = len(dataset_dicts) - for k, v in category_freq.items(): - category_freq[k] = v / num_images - - # 2. For each category c, compute the category-level repeat factor: - # r(c) = max(1, sqrt(t / f(c))) - category_rep = { - cat_id: max(1.0, math.sqrt(repeat_thresh / cat_freq)) - for cat_id, cat_freq in category_freq.items() - } - - # 3. For each image I, compute the image-level repeat factor: - # r(I) = max_{c in I} r(c) - rep_factors = [] - for dataset_dict in dataset_dicts: - cat_ids = {ann["category_id"] for ann in dataset_dict["annotations"]} - rep_factor = max({category_rep[cat_id] for cat_id in cat_ids}, default=1.0) - rep_factors.append(rep_factor) - - return torch.tensor(rep_factors, dtype=torch.float32) - - def _get_epoch_indices(self, generator): - """ - Create a list of dataset indices (with repeats) to use for one epoch. - - Args: - generator (torch.Generator): pseudo random number generator used for - stochastic rounding. - - Returns: - torch.Tensor: list of dataset indices to use in one epoch. Each index - is repeated based on its calculated repeat factor. - """ - # Since repeat factors are fractional, we use stochastic rounding so - # that the target repeat factor is achieved in expectation over the - # course of training - rands = torch.rand(len(self._frac_part), generator=generator) - rep_factors = self._int_part + (rands < self._frac_part).float() - # Construct a list of indices in which we repeat images as specified - indices = [] - for dataset_index, rep_factor in enumerate(rep_factors): - indices.extend([dataset_index] * int(rep_factor.item())) - return torch.tensor(indices, dtype=torch.int64) - - def __iter__(self): - start = self._rank - yield from itertools.islice(self._infinite_indices(), start, None, self._world_size) - - def _infinite_indices(self): - g = torch.Generator() - g.manual_seed(self._seed) - while True: - # Sample indices with repeats determined by stochastic rounding; each - # "epoch" may have a slightly different size due to the rounding. - indices = self._get_epoch_indices(g) - if self._shuffle: - randperm = torch.randperm(len(indices), generator=g) - yield from indices[randperm].tolist() - else: - yield from indices.tolist() - - -class InferenceSampler(Sampler): - """ - Produce indices for inference across all workers. - Inference needs to run on the __exact__ set of samples, - therefore when the total number of samples is not divisible by the number of workers, - this sampler produces different number of samples on different workers. - """ - - def __init__(self, size: int): - """ - Args: - size (int): the total number of data of the underlying dataset to sample from - """ - self._size = size - assert size > 0 - self._rank = comm.get_rank() - self._world_size = comm.get_world_size() - self._local_indices = self._get_local_indices(size, self._world_size, self._rank) - - @staticmethod - def _get_local_indices(total_size, world_size, rank): - shard_size = total_size // world_size - left = total_size % world_size - shard_sizes = [shard_size + int(r < left) for r in range(world_size)] - - begin = sum(shard_sizes[:rank]) - end = min(sum(shard_sizes[: rank + 1]), total_size) - return range(begin, end) - - def __iter__(self): - yield from self._local_indices - - def __len__(self): - return len(self._local_indices) diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/engine/train_loop.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/engine/train_loop.py deleted file mode 100644 index 2f6b96dc66af2d4c93028219a4b13ea16c719892..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/engine/train_loop.py +++ /dev/null @@ -1,528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) Facebook, Inc. and its affiliates. -import concurrent.futures -import logging -import numpy as np -import time -import weakref -from typing import List, Mapping, Optional -import torch -from torch.nn.parallel import DataParallel, DistributedDataParallel - -import detectron2.utils.comm as comm -from detectron2.utils.events import EventStorage, get_event_storage -from detectron2.utils.logger import _log_api_usage - -__all__ = ["HookBase", "TrainerBase", "SimpleTrainer", "AMPTrainer"] - - -class HookBase: - """ - Base class for hooks that can be registered with :class:`TrainerBase`. - - Each hook can implement 4 methods. The way they are called is demonstrated - in the following snippet: - :: - hook.before_train() - for iter in range(start_iter, max_iter): - hook.before_step() - trainer.run_step() - hook.after_step() - iter += 1 - hook.after_train() - - Notes: - 1. In the hook method, users can access ``self.trainer`` to access more - properties about the context (e.g., model, current iteration, or config - if using :class:`DefaultTrainer`). - - 2. A hook that does something in :meth:`before_step` can often be - implemented equivalently in :meth:`after_step`. - If the hook takes non-trivial time, it is strongly recommended to - implement the hook in :meth:`after_step` instead of :meth:`before_step`. - The convention is that :meth:`before_step` should only take negligible time. - - Following this convention will allow hooks that do care about the difference - between :meth:`before_step` and :meth:`after_step` (e.g., timer) to - function properly. - - """ - - trainer: "TrainerBase" = None - """ - A weak reference to the trainer object. Set by the trainer when the hook is registered. - """ - - def before_train(self): - """ - Called before the first iteration. - """ - pass - - def after_train(self): - """ - Called after the last iteration. - """ - pass - - def before_step(self): - """ - Called before each iteration. - """ - pass - - def after_backward(self): - """ - Called after the backward pass of each iteration. - """ - pass - - def after_step(self): - """ - Called after each iteration. - """ - pass - - def state_dict(self): - """ - Hooks are stateless by default, but can be made checkpointable by - implementing `state_dict` and `load_state_dict`. - """ - return {} - - -class TrainerBase: - """ - Base class for iterative trainer with hooks. - - The only assumption we made here is: the training runs in a loop. - A subclass can implement what the loop is. - We made no assumptions about the existence of dataloader, optimizer, model, etc. - - Attributes: - iter(int): the current iteration. - - start_iter(int): The iteration to start with. - By convention the minimum possible value is 0. - - max_iter(int): The iteration to end training. - - storage(EventStorage): An EventStorage that's opened during the course of training. - """ - - def __init__(self) -> None: - self._hooks: List[HookBase] = [] - self.iter: int = 0 - self.start_iter: int = 0 - self.max_iter: int - self.storage: EventStorage - _log_api_usage("trainer." + self.__class__.__name__) - - def register_hooks(self, hooks: List[Optional[HookBase]]) -> None: - """ - Register hooks to the trainer. The hooks are executed in the order - they are registered. - - Args: - hooks (list[Optional[HookBase]]): list of hooks - """ - hooks = [h for h in hooks if h is not None] - for h in hooks: - assert isinstance(h, HookBase) - # To avoid circular reference, hooks and trainer cannot own each other. - # This normally does not matter, but will cause memory leak if the - # involved objects contain __del__: - # See http://engineering.hearsaysocial.com/2013/06/16/circular-references-in-python/ - h.trainer = weakref.proxy(self) - self._hooks.extend(hooks) - - def train(self, start_iter: int, max_iter: int): - """ - Args: - start_iter, max_iter (int): See docs above - """ - logger = logging.getLogger(__name__) - logger.info("Starting training from iteration {}".format(start_iter)) - - self.iter = self.start_iter = start_iter - self.max_iter = max_iter - - with EventStorage(start_iter) as self.storage: - try: - self.before_train() - for self.iter in range(start_iter, max_iter): - self.before_step() - self.run_step() - self.after_step() - # self.iter == max_iter can be used by `after_train` to - # tell whether the training successfully finished or failed - # due to exceptions. - self.iter += 1 - except Exception: - logger.exception("Exception during training:") - raise - finally: - self.after_train() - - def before_train(self): - for h in self._hooks: - h.before_train() - - def after_train(self): - self.storage.iter = self.iter - for h in self._hooks: - h.after_train() - - def before_step(self): - # Maintain the invariant that storage.iter == trainer.iter - # for the entire execution of each step - self.storage.iter = self.iter - - for h in self._hooks: - h.before_step() - - def after_backward(self): - for h in self._hooks: - h.after_backward() - - def after_step(self): - for h in self._hooks: - h.after_step() - - def run_step(self): - raise NotImplementedError - - def state_dict(self): - ret = {"iteration": self.iter} - hooks_state = {} - for h in self._hooks: - sd = h.state_dict() - if sd: - name = type(h).__qualname__ - if name in hooks_state: - # TODO handle repetitive stateful hooks - continue - hooks_state[name] = sd - if hooks_state: - ret["hooks"] = hooks_state - return ret - - def load_state_dict(self, state_dict): - logger = logging.getLogger(__name__) - self.iter = state_dict["iteration"] - for key, value in state_dict.get("hooks", {}).items(): - for h in self._hooks: - try: - name = type(h).__qualname__ - except AttributeError: - continue - if name == key: - h.load_state_dict(value) - break - else: - logger.warning(f"Cannot find the hook '{key}', its state_dict is ignored.") - - -class SimpleTrainer(TrainerBase): - """ - A simple trainer for the most common type of task: - single-cost single-optimizer single-data-source iterative optimization, - optionally using data-parallelism. - It assumes that every step, you: - - 1. Compute the loss with a data from the data_loader. - 2. Compute the gradients with the above loss. - 3. Update the model with the optimizer. - - All other tasks during training (checkpointing, logging, evaluation, LR schedule) - are maintained by hooks, which can be registered by :meth:`TrainerBase.register_hooks`. - - If you want to do anything fancier than this, - either subclass TrainerBase and implement your own `run_step`, - or write your own training loop. - """ - - def __init__( - self, - model, - data_loader, - optimizer, - gather_metric_period=1, - zero_grad_before_forward=False, - async_write_metrics=False, - ): - """ - Args: - model: a torch Module. Takes a data from data_loader and returns a - dict of losses. - data_loader: an iterable. Contains data to be used to call model. - optimizer: a torch optimizer. - gather_metric_period: an int. Every gather_metric_period iterations - the metrics are gathered from all the ranks to rank 0 and logged. - zero_grad_before_forward: whether to zero the gradients before the forward. - async_write_metrics: bool. If True, then write metrics asynchronously to improve - training speed - """ - super().__init__() - - """ - We set the model to training mode in the trainer. - However it's valid to train a model that's in eval mode. - If you want your model (or a submodule of it) to behave - like evaluation during training, you can overwrite its train() method. - """ - model.train() - - self.model = model - self.data_loader = data_loader - # to access the data loader iterator, call `self._data_loader_iter` - self._data_loader_iter_obj = None - self.optimizer = optimizer - self.gather_metric_period = gather_metric_period - self.zero_grad_before_forward = zero_grad_before_forward - self.async_write_metrics = async_write_metrics - # create a thread pool that can execute non critical logic in run_step asynchronically - # use only 1 worker so tasks will be executred in order of submitting. - self.concurrent_executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) - - def run_step(self): - """ - Implement the standard training logic described above. - """ - assert self.model.training, "[SimpleTrainer] model was changed to eval mode!" - start = time.perf_counter() - """ - If you want to do something with the data, you can wrap the dataloader. - """ - data = next(self._data_loader_iter) - data_time = time.perf_counter() - start - - if self.zero_grad_before_forward: - """ - If you need to accumulate gradients or do something similar, you can - wrap the optimizer with your custom `zero_grad()` method. - """ - self.optimizer.zero_grad() - - """ - If you want to do something with the losses, you can wrap the model. - """ - loss_dict = self.model(data) - if isinstance(loss_dict, torch.Tensor): - losses = loss_dict - loss_dict = {"total_loss": loss_dict} - else: - losses = sum(loss_dict.values()) - if not self.zero_grad_before_forward: - """ - If you need to accumulate gradients or do something similar, you can - wrap the optimizer with your custom `zero_grad()` method. - """ - self.optimizer.zero_grad() - losses.backward() - - self.after_backward() - - if self.async_write_metrics: - # write metrics asynchronically - self.concurrent_executor.submit( - self._write_metrics, loss_dict, data_time, iter=self.iter - ) - else: - self._write_metrics(loss_dict, data_time) - - """ - If you need gradient clipping/scaling or other processing, you can - wrap the optimizer with your custom `step()` method. But it is - suboptimal as explained in https://arxiv.org/abs/2006.15704 Sec 3.2.4 - """ - self.optimizer.step() - - @property - def _data_loader_iter(self): - # only create the data loader iterator when it is used - if self._data_loader_iter_obj is None: - self._data_loader_iter_obj = iter(self.data_loader) - return self._data_loader_iter_obj - - def reset_data_loader(self, data_loader_builder): - """ - Delete and replace the current data loader with a new one, which will be created - by calling `data_loader_builder` (without argument). - """ - del self.data_loader - data_loader = data_loader_builder() - self.data_loader = data_loader - self._data_loader_iter_obj = None - - def _write_metrics( - self, - loss_dict: Mapping[str, torch.Tensor], - data_time: float, - prefix: str = "", - iter: Optional[int] = None, - ) -> None: - logger = logging.getLogger(__name__) - - iter = self.iter if iter is None else iter - if (iter + 1) % self.gather_metric_period == 0: - try: - SimpleTrainer.write_metrics(loss_dict, data_time, iter, prefix) - except Exception: - logger.exception("Exception in writing metrics: ") - raise - - @staticmethod - def write_metrics( - loss_dict: Mapping[str, torch.Tensor], - data_time: float, - cur_iter: int, - prefix: str = "", - ) -> None: - """ - Args: - loss_dict (dict): dict of scalar losses - data_time (float): time taken by the dataloader iteration - prefix (str): prefix for logging keys - """ - metrics_dict = {k: v.detach().cpu().item() for k, v in loss_dict.items()} - metrics_dict["data_time"] = data_time - - # Gather metrics among all workers for logging - # This assumes we do DDP-style training, which is currently the only - # supported method in detectron2. - all_metrics_dict = comm.gather(metrics_dict) - - if comm.is_main_process(): - storage = get_event_storage() - - # data_time among workers can have high variance. The actual latency - # caused by data_time is the maximum among workers. - data_time = np.max([x.pop("data_time") for x in all_metrics_dict]) - storage.put_scalar("data_time", data_time, cur_iter=cur_iter) - - # average the rest metrics - metrics_dict = { - k: np.mean([x[k] for x in all_metrics_dict]) for k in all_metrics_dict[0].keys() - } - total_losses_reduced = sum(metrics_dict.values()) - if not np.isfinite(total_losses_reduced): - raise FloatingPointError( - f"Loss became infinite or NaN at iteration={cur_iter}!\n" - f"loss_dict = {metrics_dict}" - ) - - storage.put_scalar( - "{}total_loss".format(prefix), total_losses_reduced, cur_iter=cur_iter - ) - if len(metrics_dict) > 1: - storage.put_scalars(cur_iter=cur_iter, **metrics_dict) - - def state_dict(self): - ret = super().state_dict() - ret["optimizer"] = self.optimizer.state_dict() - return ret - - def load_state_dict(self, state_dict): - super().load_state_dict(state_dict) - self.optimizer.load_state_dict(state_dict["optimizer"]) - - def after_train(self): - super().after_train() - self.concurrent_executor.shutdown(wait=True) - - -class AMPTrainer(SimpleTrainer): - """ - Like :class:`SimpleTrainer`, but uses PyTorch's native automatic mixed precision - in the training loop. - """ - - def __init__( - self, - model, - data_loader, - optimizer, - gather_metric_period=1, - zero_grad_before_forward=False, - grad_scaler=None, - precision: torch.dtype = torch.float16, - log_grad_scaler: bool = False, - async_write_metrics=False, - ): - """ - Args: - model, data_loader, optimizer, gather_metric_period, zero_grad_before_forward, - async_write_metrics: same as in :class:`SimpleTrainer`. - grad_scaler: torch GradScaler to automatically scale gradients. - precision: torch.dtype as the target precision to cast to in computations - """ - unsupported = "AMPTrainer does not support single-process multi-device training!" - if isinstance(model, DistributedDataParallel): - assert not (model.device_ids and len(model.device_ids) > 1), unsupported - assert not isinstance(model, DataParallel), unsupported - - super().__init__( - model, data_loader, optimizer, gather_metric_period, zero_grad_before_forward - ) - - if grad_scaler is None: - from torch.cuda.amp import GradScaler - - grad_scaler = GradScaler() - self.grad_scaler = grad_scaler - self.precision = precision - self.log_grad_scaler = log_grad_scaler - - def run_step(self): - """ - Implement the AMP training logic. - """ - assert self.model.training, "[AMPTrainer] model was changed to eval mode!" - assert torch.cuda.is_available(), "[AMPTrainer] CUDA is required for AMP training!" - from torch.cuda.amp import autocast - - start = time.perf_counter() - data = next(self._data_loader_iter) - data_time = time.perf_counter() - start - - if self.zero_grad_before_forward: - self.optimizer.zero_grad() - with autocast(dtype=self.precision): - loss_dict = self.model(data) - if isinstance(loss_dict, torch.Tensor): - losses = loss_dict - loss_dict = {"total_loss": loss_dict} - else: - losses = sum(loss_dict.values()) - - if not self.zero_grad_before_forward: - self.optimizer.zero_grad() - - self.grad_scaler.scale(losses).backward() - - if self.log_grad_scaler: - storage = get_event_storage() - storage.put_scalar("[metric]grad_scaler", self.grad_scaler.get_scale()) - - self.after_backward() - - if self.async_write_metrics: - # write metrics asynchronically - self.concurrent_executor.submit( - self._write_metrics, loss_dict, data_time, iter=self.iter - ) - else: - self._write_metrics(loss_dict, data_time) - - self.grad_scaler.step(self.optimizer) - self.grad_scaler.update() - - def state_dict(self): - ret = super().state_dict() - ret["grad_scaler"] = self.grad_scaler.state_dict() - return ret - - def load_state_dict(self, state_dict): - super().load_state_dict(state_dict) - self.grad_scaler.load_state_dict(state_dict["grad_scaler"]) diff --git a/spaces/brjathu/HMR2.0/vendor/pyrender/pyrender/node.py b/spaces/brjathu/HMR2.0/vendor/pyrender/pyrender/node.py deleted file mode 100644 index 1f37f7856cc732a37dc58253022a7c331489493e..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/pyrender/pyrender/node.py +++ /dev/null @@ -1,263 +0,0 @@ -"""Nodes, conforming to the glTF 2.0 standards as specified in -https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-node - -Author: Matthew Matl -""" -import numpy as np - -import trimesh.transformations as transformations - -from .camera import Camera -from .mesh import Mesh -from .light import Light - - -class Node(object): - """A node in the node hierarchy. - - Parameters - ---------- - name : str, optional - The user-defined name of this object. - camera : :class:`Camera`, optional - The camera in this node. - children : list of :class:`Node` - The children of this node. - skin : int, optional - The index of the skin referenced by this node. - matrix : (4,4) float, optional - A floating-point 4x4 transformation matrix. - mesh : :class:`Mesh`, optional - The mesh in this node. - rotation : (4,) float, optional - The node's unit quaternion in the order (x, y, z, w), where - w is the scalar. - scale : (3,) float, optional - The node's non-uniform scale, given as the scaling factors along the x, - y, and z axes. - translation : (3,) float, optional - The node's translation along the x, y, and z axes. - weights : (n,) float - The weights of the instantiated Morph Target. Number of elements must - match number of Morph Targets of used mesh. - light : :class:`Light`, optional - The light in this node. - """ - - def __init__(self, - name=None, - camera=None, - children=None, - skin=None, - matrix=None, - mesh=None, - rotation=None, - scale=None, - translation=None, - weights=None, - light=None): - # Set defaults - if children is None: - children = [] - - self._matrix = None - self._scale = None - self._rotation = None - self._translation = None - if matrix is None: - if rotation is None: - rotation = np.array([0.0, 0.0, 0.0, 1.0]) - if translation is None: - translation = np.zeros(3) - if scale is None: - scale = np.ones(3) - self.rotation = rotation - self.translation = translation - self.scale = scale - else: - self.matrix = matrix - - self.name = name - self.camera = camera - self.children = children - self.skin = skin - self.mesh = mesh - self.weights = weights - self.light = light - - @property - def name(self): - """str : The user-defined name of this object. - """ - return self._name - - @name.setter - def name(self, value): - if value is not None: - value = str(value) - self._name = value - - @property - def camera(self): - """:class:`Camera` : The camera in this node. - """ - return self._camera - - @camera.setter - def camera(self, value): - if value is not None and not isinstance(value, Camera): - raise TypeError('Value must be a camera') - self._camera = value - - @property - def children(self): - """list of :class:`Node` : The children of this node. - """ - return self._children - - @children.setter - def children(self, value): - self._children = value - - @property - def skin(self): - """int : The skin index for this node. - """ - return self._skin - - @skin.setter - def skin(self, value): - self._skin = value - - @property - def mesh(self): - """:class:`Mesh` : The mesh in this node. - """ - return self._mesh - - @mesh.setter - def mesh(self, value): - if value is not None and not isinstance(value, Mesh): - raise TypeError('Value must be a mesh') - self._mesh = value - - @property - def light(self): - """:class:`Light` : The light in this node. - """ - return self._light - - @light.setter - def light(self, value): - if value is not None and not isinstance(value, Light): - raise TypeError('Value must be a light') - self._light = value - - @property - def rotation(self): - """(4,) float : The xyzw quaternion for this node. - """ - return self._rotation - - @rotation.setter - def rotation(self, value): - value = np.asanyarray(value) - if value.shape != (4,): - raise ValueError('Quaternion must be a (4,) vector') - if np.abs(np.linalg.norm(value) - 1.0) > 1e-3: - raise ValueError('Quaternion must have norm == 1.0') - self._rotation = value - self._matrix = None - - @property - def translation(self): - """(3,) float : The translation for this node. - """ - return self._translation - - @translation.setter - def translation(self, value): - value = np.asanyarray(value) - if value.shape != (3,): - raise ValueError('Translation must be a (3,) vector') - self._translation = value - self._matrix = None - - @property - def scale(self): - """(3,) float : The scale for this node. - """ - return self._scale - - @scale.setter - def scale(self, value): - value = np.asanyarray(value) - if value.shape != (3,): - raise ValueError('Scale must be a (3,) vector') - self._scale = value - self._matrix = None - - @property - def matrix(self): - """(4,4) float : The homogenous transform matrix for this node. - - Note that this matrix's elements are not settable, - it's just a copy of the internal matrix. You can set the whole - matrix, but not an individual element. - """ - if self._matrix is None: - self._matrix = self._m_from_tqs( - self.translation, self.rotation, self.scale - ) - return self._matrix.copy() - - @matrix.setter - def matrix(self, value): - value = np.asanyarray(value) - if value.shape != (4,4): - raise ValueError('Matrix must be a 4x4 numpy ndarray') - if not np.allclose(value[3,:], np.array([0.0, 0.0, 0.0, 1.0])): - raise ValueError('Bottom row of matrix must be [0,0,0,1]') - self.rotation = Node._q_from_m(value) - self.scale = Node._s_from_m(value) - self.translation = Node._t_from_m(value) - self._matrix = value - - @staticmethod - def _t_from_m(m): - return m[:3,3] - - @staticmethod - def _r_from_m(m): - U = m[:3,:3] - norms = np.linalg.norm(U.T, axis=1) - return U / norms - - @staticmethod - def _q_from_m(m): - M = np.eye(4) - M[:3,:3] = Node._r_from_m(m) - q_wxyz = transformations.quaternion_from_matrix(M) - return np.roll(q_wxyz, -1) - - @staticmethod - def _s_from_m(m): - return np.linalg.norm(m[:3,:3].T, axis=1) - - @staticmethod - def _r_from_q(q): - q_wxyz = np.roll(q, 1) - return transformations.quaternion_matrix(q_wxyz)[:3,:3] - - @staticmethod - def _m_from_tqs(t, q, s): - S = np.eye(4) - S[:3,:3] = np.diag(s) - - R = np.eye(4) - R[:3,:3] = Node._r_from_q(q) - - T = np.eye(4) - T[:3,3] = t - - return T.dot(R.dot(S)) diff --git a/spaces/brogelio/air_draw/air_draw_nogradio.py b/spaces/brogelio/air_draw/air_draw_nogradio.py deleted file mode 100644 index d6a22b8dd6857c4b2fe8d73a639656376ac37bb7..0000000000000000000000000000000000000000 --- a/spaces/brogelio/air_draw/air_draw_nogradio.py +++ /dev/null @@ -1,174 +0,0 @@ -import cv2 -import numpy as np -from PIL import Image -import mediapipe as mp -import time - -""" -This code can not be run on HuggingFace's Spaces App due to constraints -brought by Gradio's limited input and output functionality - -This features both more and less functions - -- Same "pen-holding" gesture to write, let go of the pen to lift off the "paper" -- Open palm facing front gesture to save a copy of the paper to home directory -- Thumbs up gesture to clear the page - -*** Install dependencies from requirements.txt -*** packages.txt is device dependent -""" - - -def find_hands(brain, img): - img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # opencv image is in BGR form but mp is trained with RGB - results = brain.process(img_rgb) # process finds the hands and outputs classification and 21 landmarks for each hand - hands_landmarks = [] # initializing array to hold the dictionary for the hands - h, w, _ = img.shape # get height and width of image for scaling - if results.multi_hand_landmarks: - for hand_type, hand_lms in zip(results.multi_handedness, results.multi_hand_landmarks): # elegant solution for mp list object traversal - hand = {} # initializing dict for each hand - lm_list = [] # landmarks array for all 21 point of the hand - for lm in hand_lms.landmark: - px, py, pz = int(lm.x * w), int(lm.y * h), int(lm.z * w) # scaling landmark points to image size for frame coordinates - lm_list.append([px, py, pz]) - - hand["lm_list"] = lm_list # add "lm_list" key for all landmark points of the hand - hand["type"] = hand_type.classification[0].label # adds the label (left/right) for the hand - hands_landmarks.append(hand) # appends the dict - return hands_landmarks - - -def is_drawing(index, thumb): # proximity function with arbitrary threshold - npindex = np.array((index[0], index[1])) - npthumb = np.array((thumb[0], thumb[1])) - if np.linalg.norm(npindex - npthumb) < 30: - return True - else: - return False - - -def save(landmarks): # brute force finger orientation checking - if landmarks[8][1] < landmarks[6][1]: - if landmarks[12][1] < landmarks[10][1]: - if landmarks[16][1] < landmarks[14][1]: - if landmarks[20][1] < landmarks[18][1]: - return True - else: - return False - - -def clear(landmarks): # brute force finger orientation checking - if landmarks[4][1] < landmarks[3][1] < landmarks[2][1] < landmarks[8][1]: - return True - else: - return False - - -DOMINANT_HAND = "Right" - -width, height = 1280, 720 -width_, height_, = 256, 144 - -drawing_flag = False -sleepy_time = time.time() - - -if __name__ == '__main__': - cam = cv2.VideoCapture(0) - cam.set(3, width) - cam.set(4, height) - - detector = mp.solutions.hands.Hands(min_detection_confidence=0.8) # initialize mp model - # paper = np.zeros((width, height, 4), np.uint8) - paper = np.zeros((height, width, 3), dtype=np.uint8) # create blank page - paper.fill(255) - - past_holder = () # coordinates holder - palette = cv2.imread('palette.jpg') - - output_frames = [] - page_num = 0 - # runny = 1 - color = (0, 0, 0) - while True: - # runny -= 1 - x, rgb_image = cam.read() - rgb_image_f = cv2.flip(np.asanyarray(rgb_image), 1) - - hands = find_hands(detector, rgb_image_f) - - try: - if hands: - hand1 = hands[0] if hands[0]["type"] == DOMINANT_HAND else hands[1] - lm_list1 = hand1["lm_list"] # List of 21 Landmarks - handedness = hand1["type"] - - if handedness == DOMINANT_HAND: - idx_coords = lm_list1[8][0], lm_list1[8][1] # 0 is width (bigger) - # print(idx_coords) - cv2.circle(rgb_image_f, idx_coords, 5, color, cv2.FILLED) - - if idx_coords[1] < 72: # brute force but should be extremely marginally faster lol - if idx_coords[0] < 142: # red - color = (0, 0, 255) - if 142 < idx_coords[0] < 285: # orange - color = (0, 115, 255) - if 285 < idx_coords[0] < 426: # yellow - color = (0, 229, 255) - if 426 < idx_coords[0] < 569: # green - color = (0, 195, 88) - if 569 < idx_coords[0] < 711: # blue - color = (195, 85, 0) - if 711 < idx_coords[0] < 853: # indigo - color = (195, 0, 68) - if 853 < idx_coords[0] < 996: # violet - color = (195, 0, 143) - if 996 < idx_coords[0] < 1137: # black - color = (0, 0, 0) - if 1137 < idx_coords[0]: # white / eraser - color = (255, 255, 255) - - if len(past_holder) and drawing_flag: # start drawing - cv2.line(paper, past_holder, idx_coords, color, 5) - cv2.line(rgb_image_f, past_holder, idx_coords, color, 5) - # paper[idx_coords[0]][idx_coords[1]][0] = 255 - # paper[idx_coords[0]][idx_coords[1]][3] = 255 - cv2.circle(rgb_image_f, idx_coords, 5, color, cv2.FILLED) - - if save(lm_list1) and time.time() - sleepy_time > 3: # save page, 3 secs arbitrary, just to not iterate every loop iteration - paper[0:height_, w - width_: w] = 255 - paper = cv2.cvtColor(paper, cv2.COLOR_BGR2RGB) - im = Image.fromarray(paper) - im.save("paper%s.png" % page_num) - print("saved") - sleepy_time = time.time() - paper = cv2.cvtColor(paper, cv2.COLOR_RGB2BGR) - page_num += 1 - - if clear(lm_list1) and time.time() - sleepy_time > 3: # clear page - paper = np.zeros((height, width, 3), dtype=np.uint8) - paper.fill(255) - print("page cleared") - sleepy_time = time.time() - - past_holder = idx_coords - - if is_drawing(idx_coords, lm_list1[4]): # 4 is thumb for intuitive "hold pen" to draw - drawing_flag = True - else: - drawing_flag = False - - except: - pass - - finally: - rgb_image_f[0:72, ] = palette - presenter = cv2.resize(rgb_image_f, (width_, height_)) - h, w, _ = rgb_image_f.shape - paper[0:height_, w - width_: w] = presenter - cv2.imshow("Image", rgb_image_f) - cv2.imshow("paper", paper) - key = cv2.waitKey(1) - if key & 0xFF == ord('q') or key == 27: # Press esc or 'q' to close the image window - break - diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/MViTv2/configs/common/coco_loader_lsj.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/MViTv2/configs/common/coco_loader_lsj.py deleted file mode 100644 index 019b21fb23299542f757459da12a56df1c538e2b..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/MViTv2/configs/common/coco_loader_lsj.py +++ /dev/null @@ -1,19 +0,0 @@ -import detectron2.data.transforms as T -from detectron2 import model_zoo -from detectron2.config import LazyCall as L - -from .coco_loader import dataloader - -# Data using LSJ -image_size = 1024 -dataloader.train.mapper.augmentations = [ - L(T.RandomFlip)(horizontal=True), # flip first - L(T.ResizeScale)( - min_scale=0.1, max_scale=2.0, target_height=image_size, target_width=image_size - ), - L(T.FixedSizeCrop)(crop_size=(image_size, image_size)), -] -dataloader.train.mapper.image_format = "RGB" -dataloader.train.total_batch_size = 64 -# recompute boxes due to cropping -dataloader.train.mapper.recompute_boxes = True diff --git a/spaces/chawiii/open-reverse-proxy/Dockerfile b/spaces/chawiii/open-reverse-proxy/Dockerfile deleted file mode 100644 index 6953fc05439efb70991552cf56f28365b5b6c15b..0000000000000000000000000000000000000000 --- a/spaces/chawiii/open-reverse-proxy/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM node:18 - -WORKDIR /app - -RUN npm install express express-http-proxy - -COPY . . - -EXPOSE 7860 - -CMD [ "node", "server.js" ] \ No newline at end of file diff --git a/spaces/chendl/compositional_test/transformers/src/transformers/modeling_flax_utils.py b/spaces/chendl/compositional_test/transformers/src/transformers/modeling_flax_utils.py deleted file mode 100644 index eee84ba5f96591b7609ee4b57fa18b3850280ecc..0000000000000000000000000000000000000000 --- a/spaces/chendl/compositional_test/transformers/src/transformers/modeling_flax_utils.py +++ /dev/null @@ -1,1170 +0,0 @@ -# coding=utf-8 -# Copyright 2021 The Google Flax Team Authors and The HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import gc -import json -import os -import re -from functools import partial -from pickle import UnpicklingError -from typing import Any, Dict, Set, Tuple, Union - -import flax.linen as nn -import jax -import jax.numpy as jnp -import msgpack.exceptions -from flax.core.frozen_dict import FrozenDict, unfreeze -from flax.serialization import from_bytes, to_bytes -from flax.traverse_util import flatten_dict, unflatten_dict -from jax.random import PRNGKey - -from .configuration_utils import PretrainedConfig -from .dynamic_module_utils import custom_object_save -from .generation import FlaxGenerationMixin, GenerationConfig -from .modeling_flax_pytorch_utils import load_pytorch_checkpoint_in_flax_state_dict -from .utils import ( - FLAX_WEIGHTS_INDEX_NAME, - FLAX_WEIGHTS_NAME, - WEIGHTS_INDEX_NAME, - WEIGHTS_NAME, - PushToHubMixin, - add_code_sample_docstrings, - add_start_docstrings_to_model_forward, - cached_file, - copy_func, - download_url, - has_file, - is_offline_mode, - is_remote_url, - logging, - replace_return_docstrings, -) -from .utils.hub import convert_file_size_to_int, get_checkpoint_shard_files - - -logger = logging.get_logger(__name__) - - -def quick_gelu(x): - return x * jax.nn.sigmoid(1.702 * x) - - -ACT2FN = { - "gelu": partial(nn.gelu, approximate=False), - "relu": nn.relu, - "silu": nn.swish, - "swish": nn.swish, - "gelu_new": partial(nn.gelu, approximate=True), - "quick_gelu": quick_gelu, -} - - -def dtype_byte_size(dtype): - """ - Returns the size (in bytes) occupied by one parameter of type `dtype`. Example: - ```py - >>> dtype_byte_size(np.float32) - 4 - ``` - """ - if dtype == bool: - return 1 / 8 - bit_search = re.search(r"[^\d](\d+)$", dtype.name) - if bit_search is None: - raise ValueError(f"`dtype` is not a valid dtype: {dtype}.") - bit_size = int(bit_search.groups()[0]) - return bit_size // 8 - - -def flax_shard_checkpoint(params, max_shard_size="10GB"): - """ - Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a - given size. The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so - there is no optimization made to make each sub-checkpoint as close as possible to the maximum size passed. For - example, if the limit is 10GB and we have weights of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as - [6GB], [6+2GB], [6+2+2GB] and not [6+2+2GB], [6+2GB], [6GB]. - - - - If one of the model's weight is bigger that `max_shard_size`, it will end up in its own sub-checkpoint which will - have a size greater than `max_shard_size`. - - - - Args: - params (`Union[Dict, FrozenDict]`): A `PyTree` of model parameters. - max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): - The maximum size of each sub-checkpoint. If expressed as a string, needs to be digits followed by a unit - (like `"5MB"`). - """ - max_shard_size = convert_file_size_to_int(max_shard_size) - - sharded_state_dicts = [] - current_block = {} - current_block_size = 0 - total_size = 0 - - # flatten the weights to chunk - weights = flatten_dict(params, sep="/") - for item in weights: - weight_size = weights[item].size * dtype_byte_size(weights[item].dtype) - - # If this weight is going to tip up over the maximal size, we split. - if current_block_size + weight_size > max_shard_size: - sharded_state_dicts.append(current_block) - current_block = {} - current_block_size = 0 - - current_block[item] = weights[item] - current_block_size += weight_size - total_size += weight_size - - # Add the last block - sharded_state_dicts.append(current_block) - - # If we only have one shard, we return it - if len(sharded_state_dicts) == 1: - return {FLAX_WEIGHTS_NAME: sharded_state_dicts[0]}, None - - # Otherwise, let's build the index - weight_map = {} - shards = {} - for idx, shard in enumerate(sharded_state_dicts): - shard_file = FLAX_WEIGHTS_NAME.replace(".msgpack", f"-{idx+1:05d}-of-{len(sharded_state_dicts):05d}.msgpack") - shards[shard_file] = shard - for weight_name in shard.keys(): - weight_map[weight_name] = shard_file - - # Add the metadata - metadata = {"total_size": total_size} - index = {"metadata": metadata, "weight_map": weight_map} - return shards, index - - -class FlaxPreTrainedModel(PushToHubMixin, FlaxGenerationMixin): - r""" - Base class for all models. - - [`FlaxPreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading, - downloading and saving models. - - Class attributes (overridden by derived classes): - - - **config_class** ([`PretrainedConfig`]) -- A subclass of [`PretrainedConfig`] to use as configuration class - for this model architecture. - - **base_model_prefix** (`str`) -- A string indicating the attribute associated to the base model in derived - classes of the same architecture adding modules on top of the base model. - - **main_input_name** (`str`) -- The name of the principal input to the model (often `input_ids` for NLP - models, `pixel_values` for vision models and `input_values` for speech models). - """ - config_class = None - base_model_prefix = "" - main_input_name = "input_ids" - _auto_class = None - _missing_keys = set() - - def __init__( - self, - config: PretrainedConfig, - module: nn.Module, - input_shape: Tuple = (1, 1), - seed: int = 0, - dtype: jnp.dtype = jnp.float32, - _do_init: bool = True, - ): - if config is None: - raise ValueError("config cannot be None") - - if module is None: - raise ValueError("module cannot be None") - - # Those are private to be exposed as typed property on derived classes. - self._config = config - self._module = module - - # Those are public as their type is generic to every derived classes. - self.key = PRNGKey(seed) - self.dtype = dtype - self.input_shape = input_shape - self.generation_config = GenerationConfig.from_model_config(config) if self.can_generate() else None - - # To check if the model was intialized automatically. - self._is_initialized = _do_init - - if _do_init: - # randomly initialized parameters - random_params = self.init_weights(self.key, input_shape) - params_shape_tree = jax.eval_shape(lambda params: params, random_params) - else: - init_fn = partial(self.init_weights, input_shape=input_shape) - params_shape_tree = jax.eval_shape(init_fn, self.key) - - logger.info( - "Model weights are not initialized as `_do_init` is set to `False`. " - f"Make sure to call `{self.__class__.__name__}.init_weights` manually to initialize the weights." - ) - - # get the shape of the parameters - self._params_shape_tree = params_shape_tree - - # save required_params as set - self._required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys()) - - # initialize the parameters - if _do_init: - self.params = random_params - - def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> Dict: - raise NotImplementedError(f"init method has to be implemented for {self}") - - def enable_gradient_checkpointing(self): - raise NotImplementedError(f"gradient checkpointing method has to be implemented for {self}") - - @classmethod - def _from_config(cls, config, **kwargs): - """ - All context managers that the model should be initialized under go here. - """ - return cls(config, **kwargs) - - @property - def framework(self) -> str: - """ - :str: Identifies that this is a Flax model. - """ - return "flax" - - @property - def config(self) -> PretrainedConfig: - return self._config - - @property - def module(self) -> nn.Module: - return self._module - - @property - def params(self) -> Union[Dict, FrozenDict]: - if not self._is_initialized: - raise ValueError( - "`params` cannot be accessed from model when the model is created with `_do_init=False`. " - "You must call `init_weights` manually and store the params outside of the model and " - "pass it explicitly where needed." - ) - return self._params - - @property - def required_params(self) -> Set: - return self._required_params - - @property - def params_shape_tree(self) -> Dict: - return self._params_shape_tree - - @params.setter - def params(self, params: Union[Dict, FrozenDict]): - # don't set params if the model is not initialized - if not self._is_initialized: - raise ValueError( - "`params` cannot be set from model when the model is created with `_do_init=False`. " - "You store the params outside of the model." - ) - - if isinstance(params, FrozenDict): - params = unfreeze(params) - param_keys = set(flatten_dict(params).keys()) - if len(self.required_params - param_keys) > 0: - raise ValueError( - "Some parameters are missing. Make sure that `params` include the following " - f"parameters {self.required_params - param_keys}" - ) - self._params = params - - def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any: - """ - Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`. - """ - - # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27 - def conditional_cast(param): - if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating): - param = param.astype(dtype) - return param - - if mask is None: - return jax.tree_util.tree_map(conditional_cast, params) - - flat_params = flatten_dict(params) - flat_mask, _ = jax.tree_util.tree_flatten(mask) - - for masked, key in zip(flat_mask, flat_params.keys()): - if masked: - param = flat_params[key] - flat_params[key] = conditional_cast(param) - - return unflatten_dict(flat_params) - - def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None): - r""" - Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast - the `params` in place. - - This method can be used on TPU to explicitly convert the model parameters to bfloat16 precision to do full - half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed. - - Arguments: - params (`Union[Dict, FrozenDict]`): - A `PyTree` of model parameters. - mask (`Union[Dict, FrozenDict]`): - A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params - you want to cast, and should be `False` for those you want to skip. - - Examples: - - ```python - >>> from transformers import FlaxBertModel - - >>> # load model - >>> model = FlaxBertModel.from_pretrained("bert-base-cased") - >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision - >>> model.params = model.to_bf16(model.params) - >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale) - >>> # then pass the mask as follows - >>> from flax import traverse_util - - >>> model = FlaxBertModel.from_pretrained("bert-base-cased") - >>> flat_params = traverse_util.flatten_dict(model.params) - >>> mask = { - ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale")) - ... for path in flat_params - ... } - >>> mask = traverse_util.unflatten_dict(mask) - >>> model.params = model.to_bf16(model.params, mask) - ```""" - return self._cast_floating_to(params, jnp.bfloat16, mask) - - def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None): - r""" - Cast the floating-point `parmas` to `jax.numpy.float32`. This method can be used to explicitly convert the - model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place. - - Arguments: - params (`Union[Dict, FrozenDict]`): - A `PyTree` of model parameters. - mask (`Union[Dict, FrozenDict]`): - A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params - you want to cast, and should be `False` for those you want to skip - - Examples: - - ```python - >>> from transformers import FlaxBertModel - - >>> # Download model and configuration from huggingface.co - >>> model = FlaxBertModel.from_pretrained("bert-base-cased") - >>> # By default, the model params will be in fp32, to illustrate the use of this method, - >>> # we'll first cast to fp16 and back to fp32 - >>> model.params = model.to_f16(model.params) - >>> # now cast back to fp32 - >>> model.params = model.to_fp32(model.params) - ```""" - return self._cast_floating_to(params, jnp.float32, mask) - - def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None): - r""" - Cast the floating-point `parmas` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the - `params` in place. - - This method can be used on GPU to explicitly convert the model parameters to float16 precision to do full - half-precision training or to save weights in float16 for inference in order to save memory and improve speed. - - Arguments: - params (`Union[Dict, FrozenDict]`): - A `PyTree` of model parameters. - mask (`Union[Dict, FrozenDict]`): - A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params - you want to cast, and should be `False` for those you want to skip - - Examples: - - ```python - >>> from transformers import FlaxBertModel - - >>> # load model - >>> model = FlaxBertModel.from_pretrained("bert-base-cased") - >>> # By default, the model params will be in fp32, to cast these to float16 - >>> model.params = model.to_fp16(model.params) - >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale) - >>> # then pass the mask as follows - >>> from flax import traverse_util - - >>> model = FlaxBertModel.from_pretrained("bert-base-cased") - >>> flat_params = traverse_util.flatten_dict(model.params) - >>> mask = { - ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale")) - ... for path in flat_params - ... } - >>> mask = traverse_util.unflatten_dict(mask) - >>> model.params = model.to_fp16(model.params, mask) - ```""" - return self._cast_floating_to(params, jnp.float16, mask) - - @classmethod - def load_flax_sharded_weights(cls, shard_files): - """ - This is the same as [`flax.serialization.from_bytes`] - (https:lax.readthedocs.io/en/latest/_modules/flax/serialization.html#from_bytes) but for a sharded checkpoint. - - This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being - loaded in the model. - - Args: - shard_files (`List[str]`: - The list of shard files to load. - - Returns: - `Dict`: A nested dictionary of the model parameters, in the expected format for flax models : `{'model': - {'params': {'...'}}}`. - """ - - # Load the index - state_sharded_dict = {} - - for shard_file in shard_files: - # load using msgpack utils - try: - with open(shard_file, "rb") as state_f: - state = from_bytes(cls, state_f.read()) - except (UnpicklingError, msgpack.exceptions.ExtraData) as e: - with open(shard_file) as f: - if f.read().startswith("version"): - raise OSError( - "You seem to have cloned a repository without having git-lfs installed. Please" - " install git-lfs and run `git lfs install` followed by `git lfs pull` in the" - " folder you cloned." - ) - else: - raise ValueError from e - except (UnicodeDecodeError, ValueError): - raise EnvironmentError(f"Unable to convert {shard_file} to Flax deserializable object. ") - - state = flatten_dict(state, sep="/") - state_sharded_dict.update(state) - del state - gc.collect() - - # the state dict is unflattened to the match the format of model.params - return unflatten_dict(state_sharded_dict, sep="/") - - def can_generate(self) -> bool: - """ - Returns whether this model can generate sequences with `.generate()`. Returns: - `bool`: Whether this model can generate sequences with `.generate()`. - """ - # Detects whether `prepare_inputs_for_generation` has been overwritten, which is a requirement for generation - if "GenerationMixin" in str(self.prepare_inputs_for_generation): - return False - return True - - @classmethod - def from_pretrained( - cls, - pretrained_model_name_or_path: Union[str, os.PathLike], - dtype: jnp.dtype = jnp.float32, - *model_args, - **kwargs, - ): - r""" - Instantiate a pretrained flax model from a pre-trained model configuration. - - The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come - pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning - task. - - The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those - weights are discarded. - - Parameters: - pretrained_model_name_or_path (`str` or `os.PathLike`): - Can be either: - - - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. - Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - user or organization name, like `dbmdz/bert-base-german-cased`. - - A path to a *directory* containing model weights saved using - [`~FlaxPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. - - A path or url to a *pt index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In this case, - `from_pt` should be set to `True`. - dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`): - The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and - `jax.numpy.bfloat16` (on TPUs). - - This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If - specified all the computation will be performed with the given `dtype`. - - **Note that this only specifies the dtype of the computation and does not influence the dtype of model - parameters.** - - If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and - [`~FlaxPreTrainedModel.to_bf16`]. - model_args (sequence of positional arguments, *optional*): - All remaining positional arguments will be passed to the underlying model's `__init__` method. - config (`Union[PretrainedConfig, str, os.PathLike]`, *optional*): - Can be either: - - - an instance of a class derived from [`PretrainedConfig`], - - a string or path valid as input to [`~PretrainedConfig.from_pretrained`]. - - Configuration for the model to use instead of an automatically loaded configuration. Configuration can - be automatically loaded when: - - - The model is a model provided by the library (loaded with the *model id* string of a pretrained - model). - - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the - save directory. - - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a - configuration JSON file named *config.json* is found in the directory. - cache_dir (`Union[str, os.PathLike]`, *optional*): - Path to a directory in which a downloaded pretrained model configuration should be cached if the - standard cache should not be used. - from_pt (`bool`, *optional*, defaults to `False`): - Load the model weights from a PyTorch checkpoint save file (see docstring of - `pretrained_model_name_or_path` argument). - ignore_mismatched_sizes (`bool`, *optional*, defaults to `False`): - Whether or not to raise an error if some of the weights from the checkpoint do not have the same size - as the weights of the model (if for instance, you are instantiating a model with 10 labels from a - checkpoint with 3 labels). - force_download (`bool`, *optional*, defaults to `False`): - Whether or not to force the (re-)download of the model weights and configuration files, overriding the - cached versions if they exist. - resume_download (`bool`, *optional*, defaults to `False`): - Whether or not to delete incompletely received files. Will attempt to resume the download if such a - file exists. - proxies (`Dict[str, str]`, *optional*): - A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', - 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. - local_files_only(`bool`, *optional*, defaults to `False`): - Whether or not to only look at local files (i.e., do not try to download the model). - use_auth_token (`str` or `bool`, *optional*): - The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use - the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). - revision (`str`, *optional*, defaults to `"main"`): - The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a - git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any - identifier allowed by git. - - - - - To test a pull request you made on the Hub, you can pass `revision="refs/pr/". - - - - subfolder (`str`, *optional*, defaults to `""`): - In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can - specify the folder name here. - kwargs (remaining dictionary of keyword arguments, *optional*): - Can be used to update the configuration object (after it being loaded) and initiate the model (e.g., - `output_attentions=True`). Behaves differently depending on whether a `config` is provided or - automatically loaded: - - - If a configuration is provided with `config`, `**kwargs` will be directly passed to the - underlying model's `__init__` method (we assume all relevant updates to the configuration have - already been done) - - If a configuration is not provided, `kwargs` will be first passed to the configuration class - initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that - corresponds to a configuration attribute will be used to override said attribute with the - supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute - will be passed to the underlying model's `__init__` function. - - Examples: - - ```python - >>> from transformers import BertConfig, FlaxBertModel - - >>> # Download model and configuration from huggingface.co and cache. - >>> model = FlaxBertModel.from_pretrained("bert-base-cased") - >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable). - >>> model = FlaxBertModel.from_pretrained("./test/saved_model/") - >>> # Loading from a PyTorch checkpoint file instead of a PyTorch model (slower, for example purposes, not runnable). - >>> config = BertConfig.from_json_file("./pt_model/config.json") - >>> model = FlaxBertModel.from_pretrained("./pt_model/pytorch_model.bin", from_pt=True, config=config) - ```""" - config = kwargs.pop("config", None) - cache_dir = kwargs.pop("cache_dir", None) - from_pt = kwargs.pop("from_pt", False) - ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False) - force_download = kwargs.pop("force_download", False) - resume_download = kwargs.pop("resume_download", False) - proxies = kwargs.pop("proxies", None) - local_files_only = kwargs.pop("local_files_only", False) - use_auth_token = kwargs.pop("use_auth_token", None) - revision = kwargs.pop("revision", None) - trust_remote_code = kwargs.pop("trust_remote_code", None) - from_pipeline = kwargs.pop("_from_pipeline", None) - from_auto_class = kwargs.pop("_from_auto", False) - _do_init = kwargs.pop("_do_init", True) - subfolder = kwargs.pop("subfolder", "") - commit_hash = kwargs.pop("_commit_hash", None) - - if trust_remote_code is True: - logger.warning( - "The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is" - " ignored." - ) - - user_agent = {"file_type": "model", "framework": "flax", "from_auto_class": from_auto_class} - if from_pipeline is not None: - user_agent["using_pipeline"] = from_pipeline - - if is_offline_mode() and not local_files_only: - logger.info("Offline mode: forcing local_files_only=True") - local_files_only = True - - # Load config if we don't provide a configuration - if not isinstance(config, PretrainedConfig): - config_path = config if config is not None else pretrained_model_name_or_path - config, model_kwargs = cls.config_class.from_pretrained( - config_path, - cache_dir=cache_dir, - return_unused_kwargs=True, - force_download=force_download, - resume_download=resume_download, - proxies=proxies, - local_files_only=local_files_only, - use_auth_token=use_auth_token, - revision=revision, - subfolder=subfolder, - _from_auto=from_auto_class, - _from_pipeline=from_pipeline, - _commit_hash=commit_hash, - **kwargs, - ) - else: - model_kwargs = kwargs.copy() - - if commit_hash is None: - commit_hash = getattr(config, "_commit_hash", None) - - # Add the dtype to model_kwargs - model_kwargs["dtype"] = dtype - - # This variable will flag if we're loading a sharded checkpoint. In this case the archive file is just the - # index of the files. - is_sharded = False - - # Load model - if pretrained_model_name_or_path is not None: - pretrained_model_name_or_path = str(pretrained_model_name_or_path) - is_local = os.path.isdir(pretrained_model_name_or_path) - if os.path.isdir(pretrained_model_name_or_path): - if from_pt and os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)): - # Load from a PyTorch checkpoint - archive_file = os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME) - elif from_pt and os.path.isfile( - os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_INDEX_NAME) - ): - # Load from a sharded pytorch checkpoint - archive_file = os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_INDEX_NAME) - is_sharded = True - elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME)): - # Load from a Flax checkpoint - archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME) - elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_INDEX_NAME)): - # Load from a sharded Flax checkpoint - archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_INDEX_NAME) - is_sharded = True - # At this stage we don't have a weight file so we will raise an error. - elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)): - raise EnvironmentError( - f"Error no file named {FLAX_WEIGHTS_NAME} found in directory {pretrained_model_name_or_path} " - "but there is a file for PyTorch weights. Use `from_pt=True` to load this model from those " - "weights." - ) - else: - raise EnvironmentError( - f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory " - f"{pretrained_model_name_or_path}." - ) - elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)): - archive_file = pretrained_model_name_or_path - is_local = True - elif is_remote_url(pretrained_model_name_or_path): - filename = pretrained_model_name_or_path - resolved_archive_file = download_url(pretrained_model_name_or_path) - else: - filename = WEIGHTS_NAME if from_pt else FLAX_WEIGHTS_NAME - try: - # Load from URL or cache if already cached - cached_file_kwargs = { - "cache_dir": cache_dir, - "force_download": force_download, - "proxies": proxies, - "resume_download": resume_download, - "local_files_only": local_files_only, - "use_auth_token": use_auth_token, - "user_agent": user_agent, - "revision": revision, - "subfolder": subfolder, - "_raise_exceptions_for_missing_entries": False, - "_commit_hash": commit_hash, - } - resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs) - - # Since we set _raise_exceptions_for_missing_entries=False, we don't get an expection but a None - # result when internet is up, the repo and revision exist, but the file does not. - if resolved_archive_file is None and filename == FLAX_WEIGHTS_NAME: - # Maybe the checkpoint is sharded, we try to grab the index name in this case. - resolved_archive_file = cached_file( - pretrained_model_name_or_path, FLAX_WEIGHTS_INDEX_NAME, **cached_file_kwargs - ) - if resolved_archive_file is not None: - is_sharded = True - # Maybe the checkpoint is pytorch sharded, we try to grab the pytorch index name in this case. - elif resolved_archive_file is None and from_pt: - resolved_archive_file = cached_file( - pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **cached_file_kwargs - ) - if resolved_archive_file is not None: - is_sharded = True - if resolved_archive_file is None: - # Otherwise, maybe there is a TF or Flax model file. We try those to give a helpful error - # message. - has_file_kwargs = { - "revision": revision, - "proxies": proxies, - "use_auth_token": use_auth_token, - } - if has_file(pretrained_model_name_or_path, WEIGHTS_NAME, **has_file_kwargs): - raise EnvironmentError( - f"{pretrained_model_name_or_path} does not appear to have a file named" - f" {FLAX_WEIGHTS_NAME} but there is a file for PyTorch weights. Use `from_pt=True` to" - " load this model from those weights." - ) - elif has_file(pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **has_file_kwargs): - raise EnvironmentError( - f"{pretrained_model_name_or_path} does not appear to have a file named" - f" {FLAX_WEIGHTS_INDEX_NAME} but there is a sharded file for PyTorch weights. Use" - " `from_pt=True` to load this model from those weights." - ) - else: - raise EnvironmentError( - f"{pretrained_model_name_or_path} does not appear to have a file named" - f" {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}." - ) - except EnvironmentError: - # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted - # to the original exception. - raise - except Exception: - # For any other exception, we throw a generic error. - raise EnvironmentError( - f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it" - " from 'https://huggingface.co/models', make sure you don't have a local directory with the" - f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" - f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}." - ) - - if is_local: - logger.info(f"loading weights file {archive_file}") - resolved_archive_file = archive_file - else: - logger.info(f"loading weights file {filename} from cache at {resolved_archive_file}") - else: - resolved_archive_file = None - - # We'll need to download and cache each checkpoint shard if the checkpoint is sharded. - if is_sharded: - # resolved_archive_file becomes a list of files that point to the different checkpoint shards in this case. - resolved_archive_file, _ = get_checkpoint_shard_files( - pretrained_model_name_or_path, - resolved_archive_file, - cache_dir=cache_dir, - force_download=force_download, - proxies=proxies, - resume_download=resume_download, - local_files_only=local_files_only, - use_auth_token=use_auth_token, - user_agent=user_agent, - revision=revision, - subfolder=subfolder, - _commit_hash=commit_hash, - ) - - # init random models - model = cls(config, *model_args, _do_init=_do_init, **model_kwargs) - - if from_pt: - state = load_pytorch_checkpoint_in_flax_state_dict(model, resolved_archive_file, is_sharded) - else: - if is_sharded: - state = cls.load_flax_sharded_weights(resolved_archive_file) - else: - try: - with open(resolved_archive_file, "rb") as state_f: - state = from_bytes(cls, state_f.read()) - except (UnpicklingError, msgpack.exceptions.ExtraData) as e: - try: - with open(resolved_archive_file) as f: - if f.read().startswith("version"): - raise OSError( - "You seem to have cloned a repository without having git-lfs installed. Please" - " install git-lfs and run `git lfs install` followed by `git lfs pull` in the" - " folder you cloned." - ) - else: - raise ValueError from e - except (UnicodeDecodeError, ValueError): - raise EnvironmentError(f"Unable to convert {archive_file} to Flax deserializable object. ") - # make sure all arrays are stored as jnp.arrays - # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4: - # https://github.com/google/flax/issues/1261 - if _do_init: - state = jax.tree_util.tree_map(jnp.array, state) - else: - # keep the params on CPU if we don't want to initialize - state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.devices("cpu")[0]), state) - - if "batch_stats" in state: # if flax model contains batch norm layers - # if model is base model only use model_prefix key - if ( - cls.base_model_prefix not in dict(model.params_shape_tree["params"]) - and cls.base_model_prefix in state["params"] - ): - state["params"] = state["params"][cls.base_model_prefix] - state["batch_stats"] = state["batch_stats"][cls.base_model_prefix] - - # if model is head model and we are loading weights from base model - # we initialize new params dict with base_model_prefix - if ( - cls.base_model_prefix in dict(model.params_shape_tree["params"]) - and cls.base_model_prefix not in state["params"] - ): - state = { - "params": {cls.base_model_prefix: state["params"]}, - "batch_stats": {cls.base_model_prefix: state["batch_stats"]}, - } - - else: - # if model is base model only use model_prefix key - if cls.base_model_prefix not in dict(model.params_shape_tree) and cls.base_model_prefix in state: - state = state[cls.base_model_prefix] - - # if model is head model and we are loading weights from base model - # we initialize new params dict with base_model_prefix - if cls.base_model_prefix in dict(model.params_shape_tree) and cls.base_model_prefix not in state: - state = {cls.base_model_prefix: state} - - # flatten dicts - state = flatten_dict(state) - - random_state = flatten_dict(unfreeze(model.params if _do_init else model.params_shape_tree)) - - missing_keys = model.required_params - set(state.keys()) - unexpected_keys = set(state.keys()) - model.required_params - - # Disabling warning when porting pytorch weights to flax, flax does not uses num_batches_tracked - for unexpected_key in unexpected_keys.copy(): - if "num_batches_tracked" in unexpected_key[-1]: - unexpected_keys.remove(unexpected_key) - - if missing_keys and not _do_init: - logger.warning( - f"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. " - "Make sure to call model.init_weights to initialize the missing weights." - ) - cls._missing_keys = missing_keys - - # Mistmatched keys contains tuples key/shape1/shape2 of weights in the checkpoint that have a shape not - # matching the weights in the model. - mismatched_keys = [] - for key in state.keys(): - if key in random_state and state[key].shape != random_state[key].shape: - if ignore_mismatched_sizes: - mismatched_keys.append((key, state[key].shape, random_state[key].shape)) - state[key] = random_state[key] - else: - raise ValueError( - f"Trying to load the pretrained weight for {key} failed: checkpoint has shape " - f"{state[key].shape} which is incompatible with the model shape {random_state[key].shape}. " - "Using `ignore_mismatched_sizes=True` if you really want to load this checkpoint inside this " - "model." - ) - - # add missing keys as random parameters if we are initializing - if missing_keys and _do_init: - for missing_key in missing_keys: - state[missing_key] = random_state[missing_key] - - # remove unexpected keys to not be saved again - for unexpected_key in unexpected_keys: - del state[unexpected_key] - - if len(unexpected_keys) > 0: - logger.warning( - f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when" - f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are" - f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or" - " with another architecture (e.g. initializing a BertForSequenceClassification model from a" - " BertForPreTraining model).\n- This IS NOT expected if you are initializing" - f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly identical" - " (initializing a BertForSequenceClassification model from a BertForSequenceClassification model)." - ) - else: - logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n") - - if len(missing_keys) > 0: - logger.warning( - f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at" - f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably" - " TRAIN this model on a down-stream task to be able to use it for predictions and inference." - ) - elif len(mismatched_keys) == 0: - logger.info( - f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at" - f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the checkpoint" - f" was trained on, you can already use {model.__class__.__name__} for predictions without further" - " training." - ) - if len(mismatched_keys) > 0: - mismatched_warning = "\n".join( - [ - f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated" - for key, shape1, shape2 in mismatched_keys - ] - ) - logger.warning( - f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at" - f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not" - f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be able" - " to use it for predictions and inference." - ) - - # dictionary of key: dtypes for the model params - param_dtypes = jax.tree_util.tree_map(lambda x: x.dtype, state) - # extract keys of parameters not in jnp.float32 - fp16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.float16] - bf16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.bfloat16] - - # raise a warning if any of the parameters are not in jnp.float32 - if len(fp16_params) > 0: - logger.warning( - f"Some of the weights of {model.__class__.__name__} were initialized in float16 precision from " - f"the model checkpoint at {pretrained_model_name_or_path}:\n{fp16_params}\n" - "You should probably UPCAST the model weights to float32 if this was not intended. " - "See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this." - ) - - if len(bf16_params) > 0: - logger.warning( - f"Some of the weights of {model.__class__.__name__} were initialized in bfloat16 precision from " - f"the model checkpoint at {pretrained_model_name_or_path}:\n{bf16_params}\n" - "You should probably UPCAST the model weights to float32 if this was not intended. " - "See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this." - ) - - # If it is a model with generation capabilities, attempt to load the generation config - if model.can_generate(): - try: - model.generation_config = GenerationConfig.from_pretrained( - pretrained_model_name_or_path, - cache_dir=cache_dir, - force_download=force_download, - resume_download=resume_download, - proxies=proxies, - local_files_only=local_files_only, - use_auth_token=use_auth_token, - revision=revision, - subfolder=subfolder, - _from_auto=from_auto_class, - _from_pipeline=from_pipeline, - **kwargs, - ) - except OSError: - logger.info( - "Generation config file not found, using a generation config created from the model config." - ) - pass - - if _do_init: - # set correct parameters - model.params = unflatten_dict(state) - return model - else: - return model, unflatten_dict(state) - - def save_pretrained( - self, save_directory: Union[str, os.PathLike], params=None, push_to_hub=False, max_shard_size="10GB", **kwargs - ): - """ - Save a model and its configuration file to a directory, so that it can be re-loaded using the - `[`~FlaxPreTrainedModel.from_pretrained`]` class method - - Arguments: - save_directory (`str` or `os.PathLike`): - Directory to which to save. Will be created if it doesn't exist. - push_to_hub (`bool`, *optional*, defaults to `False`): - Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the - repository you want to push to with `repo_id` (will default to the name of `save_directory` in your - namespace). - max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): - The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size - lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). - - - - If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard - which will be bigger than `max_shard_size`. - - - - kwargs: - Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. - """ - if os.path.isfile(save_directory): - logger.error(f"Provided path ({save_directory}) should be a directory, not a file") - return - - os.makedirs(save_directory, exist_ok=True) - - if push_to_hub: - commit_message = kwargs.pop("commit_message", None) - repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) - repo_id = self._create_repo(repo_id, **kwargs) - files_timestamps = self._get_files_timestamps(save_directory) - - # get abs dir - save_directory = os.path.abspath(save_directory) - # save config as well - self.config.architectures = [self.__class__.__name__[4:]] - - # If we have a custom model, we copy the file defining it in the folder and set the attributes so it can be - # loaded from the Hub. - if self._auto_class is not None: - custom_object_save(self, save_directory, config=self.config) - - self.config.save_pretrained(save_directory) - if self.can_generate(): - self.generation_config.save_pretrained(save_directory) - - # save model - output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME) - - shards, index = flax_shard_checkpoint(params if params is not None else self.params, max_shard_size) - # Clean the folder from a previous save - for filename in os.listdir(save_directory): - full_filename = os.path.join(save_directory, filename) - if ( - filename.startswith(FLAX_WEIGHTS_NAME[:-4]) - and os.path.isfile(full_filename) - and filename not in shards.keys() - ): - os.remove(full_filename) - - if index is None: - with open(output_model_file, "wb") as f: - params = params if params is not None else self.params - model_bytes = to_bytes(params) - f.write(model_bytes) - - else: - save_index_file = os.path.join(save_directory, FLAX_WEIGHTS_INDEX_NAME) - # Save the index as well - with open(save_index_file, "w", encoding="utf-8") as f: - content = json.dumps(index, indent=2, sort_keys=True) + "\n" - f.write(content) - logger.info( - f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be " - f"split in {len(shards)} checkpoint shards. You can find where each parameters has been saved in the " - f"index located at {save_index_file}." - ) - for shard_file, shard in shards.items(): - # the shard item are unflattened, to save them we need to flatten them again - with open(os.path.join(save_directory, shard_file), mode="wb") as f: - params = unflatten_dict(shard, sep="/") - shard_bytes = to_bytes(params) - f.write(shard_bytes) - - logger.info(f"Model weights saved in {output_model_file}") - - if push_to_hub: - self._upload_modified_files( - save_directory, - repo_id, - files_timestamps, - commit_message=commit_message, - token=kwargs.get("use_auth_token"), - ) - - @classmethod - def register_for_auto_class(cls, auto_class="FlaxAutoModel"): - """ - Register this class with a given auto class. This should only be used for custom models as the ones in the - library are already mapped with an auto class. - - - - This API is experimental and may have some slight breaking changes in the next releases. - - - - Args: - auto_class (`str` or `type`, *optional*, defaults to `"FlaxAutoModel"`): - The auto class to register this new model with. - """ - if not isinstance(auto_class, str): - auto_class = auto_class.__name__ - - import transformers.models.auto as auto_module - - if not hasattr(auto_module, auto_class): - raise ValueError(f"{auto_class} is not a valid auto class.") - - cls._auto_class = auto_class - - -# To update the docstring, we need to copy the method, otherwise we change the original docstring. -FlaxPreTrainedModel.push_to_hub = copy_func(FlaxPreTrainedModel.push_to_hub) -if FlaxPreTrainedModel.push_to_hub.__doc__ is not None: - FlaxPreTrainedModel.push_to_hub.__doc__ = FlaxPreTrainedModel.push_to_hub.__doc__.format( - object="model", object_class="FlaxAutoModel", object_files="model checkpoint" - ) - - -def overwrite_call_docstring(model_class, docstring): - # copy __call__ function to be sure docstring is changed only for this function - model_class.__call__ = copy_func(model_class.__call__) - # delete existing docstring - model_class.__call__.__doc__ = None - # set correct docstring - model_class.__call__ = add_start_docstrings_to_model_forward(docstring)(model_class.__call__) - - -def append_call_sample_docstring(model_class, checkpoint, output_type, config_class, mask=None): - model_class.__call__ = copy_func(model_class.__call__) - model_class.__call__ = add_code_sample_docstrings( - checkpoint=checkpoint, - output_type=output_type, - config_class=config_class, - model_cls=model_class.__name__, - )(model_class.__call__) - - -def append_replace_return_docstrings(model_class, output_type, config_class): - model_class.__call__ = copy_func(model_class.__call__) - model_class.__call__ = replace_return_docstrings( - output_type=output_type, - config_class=config_class, - )(model_class.__call__) diff --git a/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/transforms.py b/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/transforms.py deleted file mode 100644 index a11f799e023864ff7082c1f49c0cc18351a13b47..0000000000000000000000000000000000000000 --- a/spaces/chikoto/Umamusume-DeBERTa-VITS2-TTS-JP/transforms.py +++ /dev/null @@ -1,209 +0,0 @@ -import torch -from torch.nn import functional as F - -import numpy as np - - -DEFAULT_MIN_BIN_WIDTH = 1e-3 -DEFAULT_MIN_BIN_HEIGHT = 1e-3 -DEFAULT_MIN_DERIVATIVE = 1e-3 - - -def piecewise_rational_quadratic_transform( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails=None, - tail_bound=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - if tails is None: - spline_fn = rational_quadratic_spline - spline_kwargs = {} - else: - spline_fn = unconstrained_rational_quadratic_spline - spline_kwargs = {"tails": tails, "tail_bound": tail_bound} - - outputs, logabsdet = spline_fn( - inputs=inputs, - unnormalized_widths=unnormalized_widths, - unnormalized_heights=unnormalized_heights, - unnormalized_derivatives=unnormalized_derivatives, - inverse=inverse, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - **spline_kwargs - ) - return outputs, logabsdet - - -def searchsorted(bin_locations, inputs, eps=1e-6): - bin_locations[..., -1] += eps - return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1 - - -def unconstrained_rational_quadratic_spline( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails="linear", - tail_bound=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound) - outside_interval_mask = ~inside_interval_mask - - outputs = torch.zeros_like(inputs) - logabsdet = torch.zeros_like(inputs) - - if tails == "linear": - unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1)) - constant = np.log(np.exp(1 - min_derivative) - 1) - unnormalized_derivatives[..., 0] = constant - unnormalized_derivatives[..., -1] = constant - - outputs[outside_interval_mask] = inputs[outside_interval_mask] - logabsdet[outside_interval_mask] = 0 - else: - raise RuntimeError("{} tails are not implemented.".format(tails)) - - ( - outputs[inside_interval_mask], - logabsdet[inside_interval_mask], - ) = rational_quadratic_spline( - inputs=inputs[inside_interval_mask], - unnormalized_widths=unnormalized_widths[inside_interval_mask, :], - unnormalized_heights=unnormalized_heights[inside_interval_mask, :], - unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :], - inverse=inverse, - left=-tail_bound, - right=tail_bound, - bottom=-tail_bound, - top=tail_bound, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - ) - - return outputs, logabsdet - - -def rational_quadratic_spline( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - left=0.0, - right=1.0, - bottom=0.0, - top=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - if torch.min(inputs) < left or torch.max(inputs) > right: - raise ValueError("Input to a transform is not within its domain") - - num_bins = unnormalized_widths.shape[-1] - - if min_bin_width * num_bins > 1.0: - raise ValueError("Minimal bin width too large for the number of bins") - if min_bin_height * num_bins > 1.0: - raise ValueError("Minimal bin height too large for the number of bins") - - widths = F.softmax(unnormalized_widths, dim=-1) - widths = min_bin_width + (1 - min_bin_width * num_bins) * widths - cumwidths = torch.cumsum(widths, dim=-1) - cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0) - cumwidths = (right - left) * cumwidths + left - cumwidths[..., 0] = left - cumwidths[..., -1] = right - widths = cumwidths[..., 1:] - cumwidths[..., :-1] - - derivatives = min_derivative + F.softplus(unnormalized_derivatives) - - heights = F.softmax(unnormalized_heights, dim=-1) - heights = min_bin_height + (1 - min_bin_height * num_bins) * heights - cumheights = torch.cumsum(heights, dim=-1) - cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0) - cumheights = (top - bottom) * cumheights + bottom - cumheights[..., 0] = bottom - cumheights[..., -1] = top - heights = cumheights[..., 1:] - cumheights[..., :-1] - - if inverse: - bin_idx = searchsorted(cumheights, inputs)[..., None] - else: - bin_idx = searchsorted(cumwidths, inputs)[..., None] - - input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0] - input_bin_widths = widths.gather(-1, bin_idx)[..., 0] - - input_cumheights = cumheights.gather(-1, bin_idx)[..., 0] - delta = heights / widths - input_delta = delta.gather(-1, bin_idx)[..., 0] - - input_derivatives = derivatives.gather(-1, bin_idx)[..., 0] - input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0] - - input_heights = heights.gather(-1, bin_idx)[..., 0] - - if inverse: - a = (inputs - input_cumheights) * ( - input_derivatives + input_derivatives_plus_one - 2 * input_delta - ) + input_heights * (input_delta - input_derivatives) - b = input_heights * input_derivatives - (inputs - input_cumheights) * ( - input_derivatives + input_derivatives_plus_one - 2 * input_delta - ) - c = -input_delta * (inputs - input_cumheights) - - discriminant = b.pow(2) - 4 * a * c - assert (discriminant >= 0).all() - - root = (2 * c) / (-b - torch.sqrt(discriminant)) - outputs = root * input_bin_widths + input_cumwidths - - theta_one_minus_theta = root * (1 - root) - denominator = input_delta + ( - (input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta - ) - derivative_numerator = input_delta.pow(2) * ( - input_derivatives_plus_one * root.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - root).pow(2) - ) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, -logabsdet - else: - theta = (inputs - input_cumwidths) / input_bin_widths - theta_one_minus_theta = theta * (1 - theta) - - numerator = input_heights * ( - input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta - ) - denominator = input_delta + ( - (input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta - ) - outputs = input_cumheights + numerator / denominator - - derivative_numerator = input_delta.pow(2) * ( - input_derivatives_plus_one * theta.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - theta).pow(2) - ) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, logabsdet diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/shared.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/shared.py deleted file mode 100644 index 9199643251d9dd47a5dc8ca370a3f09f3cc8a97b..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/shared.py +++ /dev/null @@ -1,250 +0,0 @@ -# encoding: utf-8 - -""" -Objects shared by docx modules. -""" - -from __future__ import absolute_import, print_function, unicode_literals - - -class Length(int): - """ - Base class for length constructor classes Inches, Cm, Mm, Px, and Emu. - Behaves as an int count of English Metric Units, 914,400 to the inch, - 36,000 to the mm. Provides convenience unit conversion methods in the form - of read-only properties. Immutable. - """ - _EMUS_PER_INCH = 914400 - _EMUS_PER_CM = 360000 - _EMUS_PER_MM = 36000 - _EMUS_PER_PT = 12700 - _EMUS_PER_TWIP = 635 - - def __new__(cls, emu): - return int.__new__(cls, emu) - - @property - def cm(self): - """ - The equivalent length expressed in centimeters (float). - """ - return self / float(self._EMUS_PER_CM) - - @property - def emu(self): - """ - The equivalent length expressed in English Metric Units (int). - """ - return self - - @property - def inches(self): - """ - The equivalent length expressed in inches (float). - """ - return self / float(self._EMUS_PER_INCH) - - @property - def mm(self): - """ - The equivalent length expressed in millimeters (float). - """ - return self / float(self._EMUS_PER_MM) - - @property - def pt(self): - """ - Floating point length in points - """ - return self / float(self._EMUS_PER_PT) - - @property - def twips(self): - """ - The equivalent length expressed in twips (int). - """ - return int(round(self / float(self._EMUS_PER_TWIP))) - - -class Inches(Length): - """ - Convenience constructor for length in inches, e.g. - ``width = Inches(0.5)``. - """ - def __new__(cls, inches): - emu = int(inches * Length._EMUS_PER_INCH) - return Length.__new__(cls, emu) - - -class Cm(Length): - """ - Convenience constructor for length in centimeters, e.g. - ``height = Cm(12)``. - """ - def __new__(cls, cm): - emu = int(cm * Length._EMUS_PER_CM) - return Length.__new__(cls, emu) - - -class Emu(Length): - """ - Convenience constructor for length in English Metric Units, e.g. - ``width = Emu(457200)``. - """ - def __new__(cls, emu): - return Length.__new__(cls, int(emu)) - - -class Mm(Length): - """ - Convenience constructor for length in millimeters, e.g. - ``width = Mm(240.5)``. - """ - def __new__(cls, mm): - emu = int(mm * Length._EMUS_PER_MM) - return Length.__new__(cls, emu) - - -class Pt(Length): - """ - Convenience value class for specifying a length in points - """ - def __new__(cls, points): - emu = int(points * Length._EMUS_PER_PT) - return Length.__new__(cls, emu) - - -class Twips(Length): - """ - Convenience constructor for length in twips, e.g. ``width = Twips(42)``. - A twip is a twentieth of a point, 635 EMU. - """ - def __new__(cls, twips): - emu = int(twips * Length._EMUS_PER_TWIP) - return Length.__new__(cls, emu) - - -class RGBColor(tuple): - """ - Immutable value object defining a particular RGB color. - """ - def __new__(cls, r, g, b): - msg = 'RGBColor() takes three integer values 0-255' - for val in (r, g, b): - if not isinstance(val, int) or val < 0 or val > 255: - raise ValueError(msg) - return super(RGBColor, cls).__new__(cls, (r, g, b)) - - def __repr__(self): - return 'RGBColor(0x%02x, 0x%02x, 0x%02x)' % self - - def __str__(self): - """ - Return a hex string rgb value, like '3C2F80' - """ - return '%02X%02X%02X' % self - - @classmethod - def from_string(cls, rgb_hex_str): - """ - Return a new instance from an RGB color hex string like ``'3C2F80'``. - """ - r = int(rgb_hex_str[:2], 16) - g = int(rgb_hex_str[2:4], 16) - b = int(rgb_hex_str[4:], 16) - return cls(r, g, b) - - -def lazyproperty(f): - """ - @lazyprop decorator. Decorated method will be called only on first access - to calculate a cached property value. After that, the cached value is - returned. - """ - cache_attr_name = '_%s' % f.__name__ # like '_foobar' for prop 'foobar' - docstring = f.__doc__ - - def get_prop_value(obj): - try: - return getattr(obj, cache_attr_name) - except AttributeError: - value = f(obj) - setattr(obj, cache_attr_name, value) - return value - - return property(get_prop_value, doc=docstring) - - -def write_only_property(f): - """ - @write_only_property decorator. Creates a property (descriptor attribute) - that accepts assignment, but not getattr (use in an expression). - """ - docstring = f.__doc__ - - return property(fset=f, doc=docstring) - - -class ElementProxy(object): - """ - Base class for lxml element proxy classes. An element proxy class is one - whose primary responsibilities are fulfilled by manipulating the - attributes and child elements of an XML element. They are the most common - type of class in python-docx other than custom element (oxml) classes. - """ - - __slots__ = ('_element', '_parent') - - def __init__(self, element, parent=None): - self._element = element - self._parent = parent - - def __eq__(self, other): - """ - Return |True| if this proxy object refers to the same oxml element as - does *other*. ElementProxy objects are value objects and should - maintain no mutable local state. Equality for proxy objects is - defined as referring to the same XML element, whether or not they are - the same proxy object instance. - """ - if not isinstance(other, ElementProxy): - return False - return self._element is other._element - - def __ne__(self, other): - if not isinstance(other, ElementProxy): - return True - return self._element is not other._element - - @property - def element(self): - """ - The lxml element proxied by this object. - """ - return self._element - - @property - def part(self): - """ - The package part containing this object - """ - return self._parent.part - - -class Parented(object): - """ - Provides common services for document elements that occur below a part - but may occasionally require an ancestor object to provide a service, - such as add or drop a relationship. Provides ``self._parent`` attribute - to subclasses. - """ - def __init__(self, parent): - super(Parented, self).__init__() - self._parent = parent - - @property - def part(self): - """ - The package part containing this object - """ - return self._parent.part diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/subset/util.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/subset/util.py deleted file mode 100644 index d20e925d7eb81a374f3c6477d478fb6827c96a08..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/subset/util.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Private utility methods used by the subset modules""" - - -def _add_method(*clazzes): - """Returns a decorator function that adds a new method to one or - more classes.""" - - def wrapper(method): - done = [] - for clazz in clazzes: - if clazz in done: - continue # Support multiple names of a clazz - done.append(clazz) - assert clazz.__name__ != "DefaultTable", "Oops, table class not found." - assert not hasattr( - clazz, method.__name__ - ), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__) - setattr(clazz, method.__name__, method) - return None - - return wrapper - - -def _uniq_sort(l): - return sorted(set(l)) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/G_S_U_B_.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/G_S_U_B_.py deleted file mode 100644 index bb8375a5f83029d2b05388d5c882edd9c4aba95c..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/G_S_U_B_.py +++ /dev/null @@ -1,5 +0,0 @@ -from .otBase import BaseTTXConverter - - -class table_G_S_U_B_(BaseTTXConverter): - pass diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_g_a_s_p.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_g_a_s_p.py deleted file mode 100644 index 10c32a87f4b2cbedac5e346c6f5d578cb7a6b65d..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/ttLib/tables/_g_a_s_p.py +++ /dev/null @@ -1,55 +0,0 @@ -from fontTools.misc.textTools import safeEval -from . import DefaultTable -import struct - - -GASP_SYMMETRIC_GRIDFIT = 0x0004 -GASP_SYMMETRIC_SMOOTHING = 0x0008 -GASP_DOGRAY = 0x0002 -GASP_GRIDFIT = 0x0001 - - -class table__g_a_s_p(DefaultTable.DefaultTable): - def decompile(self, data, ttFont): - self.version, numRanges = struct.unpack(">HH", data[:4]) - assert 0 <= self.version <= 1, "unknown 'gasp' format: %s" % self.version - data = data[4:] - self.gaspRange = {} - for i in range(numRanges): - rangeMaxPPEM, rangeGaspBehavior = struct.unpack(">HH", data[:4]) - self.gaspRange[int(rangeMaxPPEM)] = int(rangeGaspBehavior) - data = data[4:] - assert not data, "too much data" - - def compile(self, ttFont): - version = 0 # ignore self.version - numRanges = len(self.gaspRange) - data = b"" - items = sorted(self.gaspRange.items()) - for rangeMaxPPEM, rangeGaspBehavior in items: - data = data + struct.pack(">HH", rangeMaxPPEM, rangeGaspBehavior) - if rangeGaspBehavior & ~(GASP_GRIDFIT | GASP_DOGRAY): - version = 1 - data = struct.pack(">HH", version, numRanges) + data - return data - - def toXML(self, writer, ttFont): - items = sorted(self.gaspRange.items()) - for rangeMaxPPEM, rangeGaspBehavior in items: - writer.simpletag( - "gaspRange", - [ - ("rangeMaxPPEM", rangeMaxPPEM), - ("rangeGaspBehavior", rangeGaspBehavior), - ], - ) - writer.newline() - - def fromXML(self, name, attrs, content, ttFont): - if name != "gaspRange": - return - if not hasattr(self, "gaspRange"): - self.gaspRange = {} - self.gaspRange[safeEval(attrs["rangeMaxPPEM"])] = safeEval( - attrs["rangeGaspBehavior"] - ) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/Empty-2159e5e9.js b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/Empty-2159e5e9.js deleted file mode 100644 index 185277c52d88d2fc0e3ad0120ef78b675f39cdbe..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/gradio/templates/cdn/assets/Empty-2159e5e9.js +++ /dev/null @@ -1,2 +0,0 @@ -import{S as h,e as b,s as z,a9 as v,N as f,K as g,U as u,p as k,M as C,ab as E,ac as B,ad as R,z as S,v as q,A,h as K}from"./index-f877dfd5.js";import"./Button-11a87b79.js";function M(n){let e,o,a;const _=n[5].default,s=v(_,n,n[4],null);return{c(){e=f("div"),o=f("div"),s&&s.c(),g(o,"class","icon svelte-lk9eg8"),g(e,"class","empty svelte-lk9eg8"),u(e,"small",n[0]==="small"),u(e,"large",n[0]==="large"),u(e,"unpadded_box",n[1]),u(e,"small_parent",n[3])},m(t,i){k(t,e,i),C(e,o),s&&s.m(o,null),n[6](e),a=!0},p(t,[i]){s&&s.p&&(!a||i&16)&&E(s,_,t,t[4],a?R(_,t[4],i,null):B(t[4]),null),(!a||i&1)&&u(e,"small",t[0]==="small"),(!a||i&1)&&u(e,"large",t[0]==="large"),(!a||i&2)&&u(e,"unpadded_box",t[1]),(!a||i&8)&&u(e,"small_parent",t[3])},i(t){a||(S(s,t),a=!0)},o(t){q(s,t),a=!1},d(t){t&&A(e),s&&s.d(t),n[6](null)}}}function N(n,e,o){let a,{$$slots:_={},$$scope:s}=e,{size:t="small"}=e,{unpadded_box:i=!1}=e,d;function m(l){if(!l)return;const{height:r}=l.getBoundingClientRect(),{height:c}=l.parentElement?.getBoundingClientRect()||{height:r};return r>c+2}function p(l){K[l?"unshift":"push"](()=>{d=l,o(2,d)})}return n.$$set=l=>{"size"in l&&o(0,t=l.size),"unpadded_box"in l&&o(1,i=l.unpadded_box),"$$scope"in l&&o(4,s=l.$$scope)},n.$$.update=()=>{n.$$.dirty&4&&o(3,a=m(d))},[t,i,d,a,s,_,p]}class w extends h{constructor(e){super(),b(this,e,N,M,z,{size:0,unpadded_box:1})}}export{w as E}; -//# sourceMappingURL=Empty-2159e5e9.js.map diff --git a/spaces/cihyFjudo/fairness-paper-search/Girl Shitting 15 Animoticons Auswahl.md b/spaces/cihyFjudo/fairness-paper-search/Girl Shitting 15 Animoticons Auswahl.md deleted file mode 100644 index 0db954ba031169c3486b5c952e42eb4cd1311ed3..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Girl Shitting 15 Animoticons Auswahl.md +++ /dev/null @@ -1,6 +0,0 @@ -

Girl Shitting 15 animoticons auswahl


Download 🆗 https://tinurli.com/2uwjVO



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/cncn102/bingo1/src/components/toaster.tsx b/spaces/cncn102/bingo1/src/components/toaster.tsx deleted file mode 100644 index 4d2693460b61307a1d4c127fd01df9bee16e59ff..0000000000000000000000000000000000000000 --- a/spaces/cncn102/bingo1/src/components/toaster.tsx +++ /dev/null @@ -1,3 +0,0 @@ -'use client' - -export { Toaster } from 'react-hot-toast' diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dctref.h b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dctref.h deleted file mode 100644 index f6fde8863a3a6d2e002683eb60c5528aa4125952..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dctref.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * reference discrete cosine transform (double precision) - * Copyright (C) 2009 Dylan Yudaken - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef AVCODEC_DCTREF_H -#define AVCODEC_DCTREF_H - -void ff_ref_fdct(short *block); -void ff_ref_idct(short *block); -void ff_ref_dct_init(void); - -#endif /* AVCODEC_DCTREF_H */ diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dirac_dwt.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dirac_dwt.c deleted file mode 100644 index 4039899cf01852ddde5b1b7c7b0fd8adb9e8046b..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/dirac_dwt.c +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2004-2010 Michael Niedermayer - * Copyright (C) 2008 David Conrad - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "libavutil/attributes.h" -#include "libavutil/common.h" -#include "dirac_dwt.h" - -#define TEMPLATE_8bit -#include "dirac_dwt_template.c" - -#define TEMPLATE_10bit -#include "dirac_dwt_template.c" - -#define TEMPLATE_12bit -#include "dirac_dwt_template.c" - -int ff_spatial_idwt_init(DWTContext *d, DWTPlane *p, enum dwt_type type, - int decomposition_count, int bit_depth) -{ - int ret = 0; - - d->buffer = p->buf; - d->width = p->width; - d->height = p->height; - d->stride = p->stride; - d->temp = p->tmp; - d->decomposition_count = decomposition_count; - - if (bit_depth == 8) - ret = spatial_idwt_init_8bit(d, type); - else if (bit_depth == 10) - ret = spatial_idwt_init_10bit(d, type); - else if (bit_depth == 12) - ret = spatial_idwt_init_12bit(d, type); - else - av_log(NULL, AV_LOG_WARNING, "Unsupported bit depth = %i\n", bit_depth); - - if (ret) { - av_log(NULL, AV_LOG_ERROR, "Unknown wavelet type %d\n", type); - return AVERROR_INVALIDDATA; - } - -#if ARCH_X86 - if (bit_depth == 8) - ff_spatial_idwt_init_x86(d, type); -#endif - return 0; -} - -void ff_spatial_idwt_slice2(DWTContext *d, int y) -{ - int level, support = d->support; - - for (level = d->decomposition_count-1; level >= 0; level--) { - int wl = d->width >> level; - int hl = d->height >> level; - int stride_l = d->stride << level; - - while (d->cs[level].y <= FFMIN((y>>level)+support, hl)) - d->spatial_compose(d, level, wl, hl, stride_l); - } -} diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/g729data.h b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/g729data.h deleted file mode 100644 index 365ca47ec6da3b9dbe6f3686208d6e2d0a07d9a4..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/g729data.h +++ /dev/null @@ -1,382 +0,0 @@ -/* - * data for G.729, G729 Annex D decoders - * Copyright (c) 2007 Vladimir Voroshilov - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef AVCODEC_G729DATA_H -#define AVCODEC_G729DATA_H - -#include - -#define MA_NP 4 ///< Moving Average (MA) prediction order - -#define VQ_1ST_BITS 7 ///< first stage vector of quantizer (size in bits) -#define VQ_2ND_BITS 5 ///< second stage vector of quantizer (size in bits) - -#define GC_1ST_IDX_BITS_8K 3 ///< gain codebook (first stage) index, 8k mode (size in bits) -#define GC_2ND_IDX_BITS_8K 4 ///< gain codebook (second stage) index, 8k mode (size in bits) - -#define GC_1ST_IDX_BITS_6K4 3 ///< gain codebook (first stage) index, 6.4k mode (size in bits) -#define GC_2ND_IDX_BITS_6K4 3 ///< gain codebook (second stage) index, 6.4k mode (size in bits) - -/** - * first stage LSP codebook - * (10-dimensional, with 128 entries (3.24 of G.729) - */ -static const int16_t cb_lsp_1st[1<priv_data; - ParseContext *pc = &s->pc; - int next; - - if (!s->block_size) { - switch (avctx->codec_id) { - case AV_CODEC_ID_GSM: - s->block_size = GSM_BLOCK_SIZE; - s->duration = GSM_FRAME_SIZE; - break; - case AV_CODEC_ID_GSM_MS: - s->block_size = avctx->block_align ? avctx->block_align - : GSM_MS_BLOCK_SIZE; - s->duration = GSM_FRAME_SIZE * 2; - break; - default: - av_assert0(0); - } - } - - if (!s->remaining) - s->remaining = s->block_size; - if (s->remaining <= buf_size) { - next = s->remaining; - s->remaining = 0; - } else { - next = END_NOT_FOUND; - s->remaining -= buf_size; - } - - if (ff_combine_frame(pc, next, &buf, &buf_size) < 0 || !buf_size) { - *poutbuf = NULL; - *poutbuf_size = 0; - return buf_size; - } - - s1->duration = s->duration; - - *poutbuf = buf; - *poutbuf_size = buf_size; - return next; -} - -const AVCodecParser ff_gsm_parser = { - .codec_ids = { AV_CODEC_ID_GSM, AV_CODEC_ID_GSM_MS }, - .priv_data_size = sizeof(GSMParseContext), - .parser_parse = gsm_parse, - .parser_close = ff_parse_close, -}; diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/h2645data.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/h2645data.c deleted file mode 100644 index 9897ca31862c2f8cf0aa5504a42db13a18230720..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/h2645data.c +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "h2645data.h" - -const AVRational ff_h2645_pixel_aspect[] = { - { 0, 1 }, - { 1, 1 }, - { 12, 11 }, - { 10, 11 }, - { 16, 11 }, - { 40, 33 }, - { 24, 11 }, - { 20, 11 }, - { 32, 11 }, - { 80, 33 }, - { 18, 11 }, - { 15, 11 }, - { 64, 33 }, - { 160, 99 }, - { 4, 3 }, - { 3, 2 }, - { 2, 1 }, -}; diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/jvdec.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/jvdec.c deleted file mode 100644 index e0287a9cb9d0181fe2ec41dc2f5d7665035b4da0..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/jvdec.c +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Bitmap Brothers JV video decoder - * Copyright (c) 2011 Peter Ross - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/** - * @file - * Bitmap Brothers JV video decoder - * @author Peter Ross - */ - -#include "libavutil/intreadwrite.h" - -#include "avcodec.h" -#include "blockdsp.h" -#include "codec_internal.h" -#include "decode.h" -#include "get_bits.h" - -typedef struct JvContext { - BlockDSPContext bdsp; - AVFrame *frame; - uint32_t palette[AVPALETTE_COUNT]; - int palette_has_changed; -} JvContext; - -static av_cold int decode_init(AVCodecContext *avctx) -{ - JvContext *s = avctx->priv_data; - - if (!avctx->width || !avctx->height || - (avctx->width & 7) || (avctx->height & 7)) { - av_log(avctx, AV_LOG_ERROR, "Invalid video dimensions: %dx%d\n", - avctx->width, avctx->height); - return AVERROR(EINVAL); - } - - s->frame = av_frame_alloc(); - if (!s->frame) - return AVERROR(ENOMEM); - - avctx->pix_fmt = AV_PIX_FMT_PAL8; - ff_blockdsp_init(&s->bdsp); - return 0; -} - -/** - * Decode 2x2 block - */ -static inline void decode2x2(GetBitContext *gb, uint8_t *dst, int linesize) -{ - int i, j, v[2]; - - switch (get_bits(gb, 2)) { - case 1: - v[0] = get_bits(gb, 8); - for (j = 0; j < 2; j++) - memset(dst + j * linesize, v[0], 2); - break; - case 2: - v[0] = get_bits(gb, 8); - v[1] = get_bits(gb, 8); - for (j = 0; j < 2; j++) - for (i = 0; i < 2; i++) - dst[j * linesize + i] = v[get_bits1(gb)]; - break; - case 3: - for (j = 0; j < 2; j++) - for (i = 0; i < 2; i++) - dst[j * linesize + i] = get_bits(gb, 8); - } -} - -/** - * Decode 4x4 block - */ -static inline void decode4x4(GetBitContext *gb, uint8_t *dst, int linesize) -{ - int i, j, v[2]; - - switch (get_bits(gb, 2)) { - case 1: - v[0] = get_bits(gb, 8); - for (j = 0; j < 4; j++) - memset(dst + j * linesize, v[0], 4); - break; - case 2: - v[0] = get_bits(gb, 8); - v[1] = get_bits(gb, 8); - for (j = 2; j >= 0; j -= 2) { - for (i = 0; i < 4; i++) - dst[j * linesize + i] = v[get_bits1(gb)]; - for (i = 0; i < 4; i++) - dst[(j + 1) * linesize + i] = v[get_bits1(gb)]; - } - break; - case 3: - for (j = 0; j < 4; j += 2) - for (i = 0; i < 4; i += 2) - decode2x2(gb, dst + j * linesize + i, linesize); - } -} - -/** - * Decode 8x8 block - */ -static inline void decode8x8(GetBitContext *gb, uint8_t *dst, int linesize, - BlockDSPContext *bdsp) -{ - int i, j, v[2]; - - switch (get_bits(gb, 2)) { - case 1: - v[0] = get_bits(gb, 8); - bdsp->fill_block_tab[1](dst, v[0], linesize, 8); - break; - case 2: - v[0] = get_bits(gb, 8); - v[1] = get_bits(gb, 8); - for (j = 7; j >= 0; j--) - for (i = 0; i < 8; i++) - dst[j * linesize + i] = v[get_bits1(gb)]; - break; - case 3: - for (j = 0; j < 8; j += 4) - for (i = 0; i < 8; i += 4) - decode4x4(gb, dst + j * linesize + i, linesize); - } -} - -static int decode_frame(AVCodecContext *avctx, AVFrame *rframe, - int *got_frame, AVPacket *avpkt) -{ - JvContext *s = avctx->priv_data; - const uint8_t *buf = avpkt->data; - const uint8_t *buf_end = buf + avpkt->size; - int video_size, video_type, i, j, ret; - - if (avpkt->size < 6) - return AVERROR_INVALIDDATA; - - video_size = AV_RL32(buf); - video_type = buf[4]; - buf += 5; - - if (video_size) { - if (video_size < 0 || video_size > avpkt->size - 5) { - av_log(avctx, AV_LOG_ERROR, "video size %d invalid\n", video_size); - return AVERROR_INVALIDDATA; - } - - if (video_type == 0 || video_type == 1) { - GetBitContext gb; - init_get_bits(&gb, buf, 8 * video_size); - - if ((ret = ff_reget_buffer(avctx, s->frame, 0)) < 0) - return ret; - - if (avctx->height/8 * (avctx->width/8) > 4 * video_size) { - av_log(avctx, AV_LOG_ERROR, "Insufficient input data for dimensions\n"); - return AVERROR_INVALIDDATA; - } - - for (j = 0; j < avctx->height; j += 8) - for (i = 0; i < avctx->width; i += 8) - decode8x8(&gb, - s->frame->data[0] + j * s->frame->linesize[0] + i, - s->frame->linesize[0], &s->bdsp); - - buf += video_size; - } else if (video_type == 2) { - int v = *buf++; - - av_frame_unref(s->frame); - if ((ret = ff_get_buffer(avctx, s->frame, AV_GET_BUFFER_FLAG_REF)) < 0) - return ret; - - for (j = 0; j < avctx->height; j++) - memset(s->frame->data[0] + j * s->frame->linesize[0], - v, avctx->width); - } else { - av_log(avctx, AV_LOG_WARNING, - "unsupported frame type %i\n", video_type); - return AVERROR_INVALIDDATA; - } - } - - if (buf_end - buf >= AVPALETTE_COUNT * 3) { - for (i = 0; i < AVPALETTE_COUNT; i++) { - uint32_t pal = AV_RB24(buf); - s->palette[i] = 0xFFU << 24 | pal << 2 | ((pal >> 4) & 0x30303); - buf += 3; - } - s->palette_has_changed = 1; - } - - if (video_size) { - s->frame->key_frame = 1; - s->frame->pict_type = AV_PICTURE_TYPE_I; - s->frame->palette_has_changed = s->palette_has_changed; - s->palette_has_changed = 0; - memcpy(s->frame->data[1], s->palette, AVPALETTE_SIZE); - - if ((ret = av_frame_ref(rframe, s->frame)) < 0) - return ret; - *got_frame = 1; - } - - return avpkt->size; -} - -static av_cold int decode_close(AVCodecContext *avctx) -{ - JvContext *s = avctx->priv_data; - - av_frame_free(&s->frame); - - return 0; -} - -const FFCodec ff_jv_decoder = { - .p.name = "jv", - CODEC_LONG_NAME("Bitmap Brothers JV video"), - .p.type = AVMEDIA_TYPE_VIDEO, - .p.id = AV_CODEC_ID_JV, - .priv_data_size = sizeof(JvContext), - .init = decode_init, - .close = decode_close, - FF_CODEC_DECODE_CB(decode_frame), - .p.capabilities = AV_CODEC_CAP_DR1, -}; diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/metasound_data.h b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/metasound_data.h deleted file mode 100644 index 6ff84cf23ffbce9bdfbe76c7fa5302dd27bcce78..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/metasound_data.h +++ /dev/null @@ -1,13942 +0,0 @@ -/* - * MetaSound decoder - * Copyright (c) 2013 Konstantin Shishkov - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef AVCODEC_METASOUND_DATA_H -#define AVCODEC_METASOUND_DATA_H - -#include "twinvq.h" - -static const int16_t cb0806sl0[] = { - -417, -225, -84, 16, -106, -34, -246, -164, - 112, 48, -47, 36, -65, -68, -172, -1655, - -36, 140, -3, -2, -2, 2, 0, 0, - 178, 7, -181, -177, 120, -64, -129, 80, - -6826, -38, -25, 147, 148, -13, -25, 110, - 21, 21, -1, 0, 0, 0, 0, 0, - 3319, 632, -734, -187, 40, -249, -155, -1, - -173, 95, 28, -2, 20, -44, 35, 120, - -47, -221, -5, 2, -7, 1, 0, 0, - 63, 268, -260, -419, 187, -75, -228, 296, - -470, 177, -515, 318, 124, 308, 92, 371, - 3046, 362, -1, -1, -10, 1, 0, 0, - -356, -16, -199, 117, -75, 46, -108, -14, - -124, -173, 4914, -75, -474, 105, 87, 190, - -183, -208, 0, 0, 1, 1, 0, -1, - 162, 89, 49, -314, -2788, 265, -263, -3, - -3156, 316, 112, 128, -333, -138, -114, -141, - -287, -234, -1, 0, 0, 0, 0, 1, - 733, 126, -424, -389, 642, 432, 134, -251, - 407, -51, -151, -491, -308, 91, 50, 3836, - 87, 100, -5, -6, 0, 1, 0, 0, - 304, 1727, 83, -8, 216, -81, -189, 152, - -67, 15, 310, -93, 6, -37, 54, -110, - -15, 78, 0, 0, 1, 12, 0, -1, - 129, -198, 1, -48, -66, -147, 30, 264, - -84, 102, 42, 126, 1, -6451, 225, -51, - 8, 123, 0, -1, 0, -1, 0, 0, - -374, 66, -256, -80, -1139, 303, 2002, -199, - -98, -98, -39, -76, 180, 15, -456, 148, - -183, 118, -2, 1, 0, 0, 0, 0, - 151, 13, -114, 65, 6156, 76, -82, -30, - -26, 163, 81, 167, -83, -101, 55, -40, - 161, -793, -8, 0, 0, -1, -1, 0, - -102, -33, 55, -131, 434, 108, 70, 68, - 62, 1913, -109, 235, 110, 124, -25, -58, - -76, 18, -1, -1, 0, 0, 0, 0, - -105, -7322, -9, 82, 53, -43, -5, 18, - 90, 91, 20, -34, 26, -93, -50, -46, - -77, 105, 0, 6, -12, -6, 1, 0, - -1334, 980, -163, -351, -514, 537, 62, -300, - 80, -318, 14, -3570, -52, -116, -280, 540, - 250, -775, -7, 0, 0, 0, 0, 0, - 507, 317, -417, -236, -2438, -72, -346, 2507, - 302, -185, 30, 1539, 205, 87, -112, -482, - -296, 132, -1, 0, -1, 1, 0, 0, - -64, -208, -159, 1, 336, -62, -14, 13, - 81, 101, 382, 32, 116, -5, -41, 25, - -175, -7829, 1, 0, 1, 0, 0, 0, - 7551, -7, 86, -165, -57, -17, 183, -207, - 69, 54, -99, -25, 167, -58, 107, -81, - 165, 172, 2, -2, 0, 1, 0, -9, - 26, 28, 86, -183, -320, -32, 116, -53, - -49, -15, 133, -283, -152, 576, 6630, 185, - 44, 25, 20, 1, -12, 1, -1, 0, - -145, -51, -114, -29, -228, 78, -409, 235, - 147, 45, -192, 177, -91, 68, -2572, -52, - 81, 181, -5, 13, -1, -1, -17, 0, - -65, -23, -28, 9, 242, 14, -35, 88, - 77, -20, 37, -7097, -58, 51, 137, 126, - -90, 136, 0, 4, -1, 0, 0, 0, - -266, -82, -205, 816, -309, 3267, 1053, 369, - -216, -302, 18, 168, 395, 273, 343, 243, - -98, -53, 1, 0, 0, 1, 0, 0, - -65, -76, 1850, -991, -454, -535, 2927, -145, - 101, 23, 20, 234, -74, 77, 114, 4, - -106, 527, -11, 4, 0, 1, -1, 0, - 573, -46, 207, 2640, -956, 47, 26, -10, - 317, -217, -5, -867, -3, 213, 52, 53, - -428, -175, 0, 0, -1, -1, 0, -1, - -223, -55, 135, 184, 313, 0, 2868, 245, - -3187, -721, -291, 9, -265, -120, -105, -36, - 454, 55, -1, 49, 0, 1, -1, 0, - -291, 41, 84, 557, -201, -2300, 429, 283, - 21, -2, 132, 286, -124, 149, -14, 146, - 320, -298, 0, -1, 1, -2, 0, 0, - -86, -3493, 131, -3581, 185, 26, -197, -65, - -96, 147, -53, -150, -35, -35, 179, 68, - -157, 0, 0, 2, 0, 1, 2, -1, - -22, -218, 13, -1447, -400, 288, -1295, 0, - -119, 69, -56, -139, 157, -26, -122, -61, - -38, -108, -1, 1, 0, 0, 0, 0, - -229, 3335, 103, -108, 10, 3008, -712, 50, - 27, 152, -307, -106, 148, -77, -178, -46, - 7, -114, 0, -9, 0, 0, 1, 0, - 932, -443, 311, -75, 62, -80, -179, 459, - -232, -160, 2, 169, 134, -260, 41, -149, - 23, 92, -2, 0, 11, 1, 0, 0, - 16, -90, -574, -171, 163, 261, -299, 2994, - 74, -3818, -396, -171, 13, -29, -45, -168, - -287, -390, 1, 0, 0, -4, 0, -1, - 89, -702, 2223, 101, -249, 2983, 36, -333, - -382, 410, -262, 185, -146, 98, -8, -317, - -279, -879, 0, 0, 0, 0, 4, 0, - -98, -325, 75, -229, -13, 112, -5743, -34, - -89, 263, -155, 80, 140, -50, 33, 143, - -60, -77, 1, -2, 0, -1, 1, 0, - 52, -576, -543, -1142, -947, -184, 449, -71, - -75, -156, -3412, -50, -487, 307, 663, -1000, - -415, -2348, -7, -1, -1, 0, 0, 0, - 64, 3, -35, 11, 14, -198, -2, -8042, - 140, -11, -93, 29, -65, 330, 34, 110, - -19, -137, 2, 0, 0, 0, 0, 0, - 1236, 303, 2681, 234, -217, -406, -395, -380, - 247, 349, -101, -33, 370, -39, 139, 59, - 18, 24, 0, 0, 0, 0, 0, 0, - 166, -21, -5392, -117, -296, 114, 230, -255, - 131, -53, 13, -45, 200, 7, -56, 87, - 46, 223, -59, 0, -1, 0, 0, -1, - 214, -511, 175, 204, -123, -47, -440, 6, - 23, 92, -355, 80, -4885, -238, -37, 78, - -218, 175, 0, 2, 0, 0, 0, 0, - -146, 74, -13, -4, 27, -45, 51, 81, - -80, 53, -18, 173, -146, -64, -8, 8192, - 79, 15, 0, -3, 0, 1, 0, 0, - -3, -16, -28, 288, -61, 4, -187, 6, - -5, -14, 77, -12, -53, 16, -41, -7, - -10, -2, 7, -1, -9, 1, 0, 0, - -285, -35, -8, 221, -68, 114, 135, -8, - -203, -181, -91, 2043, -58, 127, 201, 111, - 46, -344, -11, -49, 0, 1, 0, -1, - -160, -186, 58, 4761, 289, 51, -145, 51, - -32, 71, 62, 175, -13, 181, 203, 141, - -200, 106, -1, 4, -2, 0, 0, 0, - 803, -76, -96, -940, 300, 3429, -84, 3037, - 262, -9, -39, 120, -629, -309, 233, -374, - 398, 894, -12, 1, 1, 1, 0, 0, - -282, 2525, -31, -176, -2473, 53, 102, -610, - 180, -145, 42, -51, 223, 27, -69, 727, - -14, -51, 0, 0, 0, -3, 0, -40, - 214, 72, 41, 1, 190, 78, -228, -235, - 105, -4619, -140, -46, -7, 49, 9, -19, - 137, -2, 9, 1, 0, 0, 0, 0, - -142, -262, 29, -142, 39, -39, -92, 95, - 50, -282, 2, -106, 114, 8, 35, 78, - -121, 2589, 1, -4, -10, 1, 1, 0, - -192, 59, 287, 400, -67, -6989, -301, 446, - 115, 7, 33, -60, 111, 102, 8, 206, - 46, -31, -1, -1, -2, 0, 0, 0, - -104, 332, -223, 1066, -188, 1270, -222, 309, - -296, 259, 780, -460, -1914, 218, -556, 210, - 2962, 130, 1, -2, 2, 0, 1, 0, - -320, -365, -266, 822, -119, 824, -312, 58, - -1857, 235, 48, -3985, 118, -307, -703, -931, - -560, 105, -2, -3, 0, 0, 0, 1, - 156, -48, 187, 214, -212, 180, 342, 373, - 1973, 128, -5, 146, -40, -11, 71, -60, - 76, 17, 0, 0, -1, 2, 0, 7, - 214, 63, 274, 2876, -65, 314, 400, 344, - 140, 39, 193, -226, 124, -3177, 68, 46, - -60, -317, 2, 0, -1, 0, 7, 0, - -160, 118, 233, 239, -465, 96, 253, 3178, - -88, 299, 368, -220, 197, 397, -353, -463, - -202, -103, -4, 0, 0, 0, 0, 0, - 687, -448, -749, 87, -35, 112, 309, -33, - -16, 88, 141, 63, -51, 274, -113, -76, - 46, -273, -1, 1, 0, 1, 0, 1, - -298, -206, 670, 303, -451, -277, -493, 404, - -173, 284, 148, 626, -322, -296, -68, 3044, - -442, 1138, -7, 2, 0, 1, 0, 0, - -1338, 18, 2862, 223, 250, 260, 144, 259, - -38, -647, 602, -160, 75, -5, -8, 34, - 237, 50, 2, 0, 1, -1, -1, 0, - -412, 2153, 933, 478, 768, 186, -424, -657, - -3458, -443, 294, 224, -468, -58, -120, -1565, - 211, -420, 0, 0, 1, -1, 0, 0, - 198, 227, -112, 350, 297, -303, 108, -192, - 153, 32, -2717, -111, -1093, -200, 476, 326, - -271, 627, 0, -4, 0, 0, 0, -1, - 462, -616, 126, 316, -2413, 204, -350, -3549, - -263, -386, -112, 483, -1339, 636, 70, -531, - 96, 38, 8, -1, 0, -3, 0, 0, - -310, -1128, 616, -339, -168, -124, -905, -151, - -383, 76, 137, -44, 3689, -388, 184, 1799, - -102, -930, 6, -1, -1, -1, 0, 0, - -284, 280, 39, -728, 143, 15, 181, 798, - 382, 10, 2267, -12, -3582, -27, 357, 514, - -565, -121, 0, -1, 0, -9, -1, 0, - 429, -16, 2993, -2903, 47, -136, 30, 792, - -327, -347, -69, -50, -93, -223, -438, 158, - 203, -475, 0, -4, -1, 2, 0, 0, - -3465, 415, -963, 252, 397, -945, -448, -231, - -130, 673, 504, 55, -355, 221, 29, 167, - -19, 134, -1, -1, -4, 0, -14, -2, - 44, 433, -535, -216, 2485, 33, 19, -100, - -185, -171, 91, 336, -208, 140, -3, 46, - -67, -116, 32, 0, 5, 3, 0, 0, - 220, 91, -65, -15, -169, 217, -183, -169, - -47, 181, -272, 138, -166, 110, -9, 41, - -6957, 33, -5, -2, 1, 1, 0, -1, - 164, -4062, -109, 230, -220, 1748, -1338, -246, - -242, -98, 300, 217, -202, -130, 157, -3, - -19, -453, 0, 2, 0, 0, 0, 0, -}; - -static const int16_t cb0806sl1[] = { - 75, 87, -31, 607, -132, 5963, -262, 494, - 134, -4, 141, 19, 225, 229, 239, 93, - -20, -189, 2, 0, -3, -1, -1, 0, - 214, -206, 877, 83, -588, 83, 132, 78, - 5, -85, 66, -24, 47, -11, 25, 26, - -3, 46, 2, -5, 0, 1, -1, 0, - -113, 295, -81, 74, 223, -50, -93, -5671, - -28, 115, 256, -228, -31, -539, 300, -278, - -59, 426, -110, -1, 1, 1, 0, 0, - -95, -116, 266, 176, 761, -3, 90, -91, - 98, -209, -414, -27, -56, 26, -76, 6, - -32, 4634, 1, 0, -4, 0, 0, 0, - 177, 147, -236, -93, -7925, 11, -111, -74, - 36, 176, 352, 88, 112, 16, 144, -110, - 91, 329, -1, 2, 0, 1, 0, 1, - 119, 304, -94, -422, 113, 129, -70, 155, - 247, -116, -139, 327, -355, 77, 143, -5362, - 27, -377, -1, 7, 2, 1, 0, 0, - 179, 127, 1500, -324, -15, 673, 184, -1382, - 167, 1833, -3058, 200, -1203, 459, -1905, 1020, - -259, -120, 10, -4, 0, 1, 0, 0, - 995, -112, 37, -160, -21, -4011, 172, 228, - -210, 80, -131, 1, 20, -128, -252, -288, - -132, 337, -1, 0, -1, 0, 1, -1, - -60, 61, 197, -185, -40, -2951, -592, -57, - 210, -3248, -226, -44, 391, -167, -7, 219, - -15, 172, 0, -1, 1, 0, 0, 0, - 106, -70, -291, 192, 45, 162, 37, 143, - 91, 21, -7032, 12, -173, -30, 1, 259, - -286, 387, -36, 0, 0, 0, 0, 0, - -1593, -210, 83, 47, 194, 61, 85, -182, - -23, 40, -74, 22, 12, 216, 59, -165, - -163, -159, -8, 0, 0, 2, 0, 0, - -3, 182, -80, 2068, 702, 115, -164, -85, - 21, -124, -191, -113, 263, 138, 4235, 37, - 204, -436, 0, 24, 1, -1, 0, 0, - 147, 83, -177, -168, -609, -9, -16, -46, - 127, 120, -25, 3435, 51, 31, 49, 366, - 31, -129, 1, -32, 0, -1, 0, -2, - 295, 158, 116, 11, -280, 471, 169, 29, - -2589, 338, 32, 299, 172, -187, -32, 437, - -38, 359, -1, -1, 1, 0, 0, 0, - 243, 413, -29, -4774, 187, 12, -117, 168, - -114, -208, -55, 5, 0, -31, 436, 545, - -45, 272, 0, -4, 0, 0, 1, 0, - 127, 38, 6620, -33, -103, 34, 84, -35, - 30, -131, -8, -79, -126, -98, 17, -75, - -31, -176, 14, -1, 0, 0, -1, -1, - 273, -219, 176, -83, 187, -36, 1, 2639, - 158, 3812, 127, -233, 175, 310, 148, 387, - -14, 308, 0, -3, 0, 0, 0, 0, - 3321, -447, 153, -128, 254, -275, 79, -181, - 17, 146, 61, 46, -48, 253, 51, -17, - 1, 1, 0, 1, -1, -2, 0, -13, - 791, -130, 40, 78, -64, -179, 42, -455, - 422, 112, -19, -4499, -113, -341, 52, 69, - 67, 254, -6, -1, 4, 0, 0, 1, - -98, -976, 68, 1563, 228, 1018, 458, -1020, - 411, 249, -627, 2321, 738, -460, -1469, 362, - 884, -261, 0, -1, 1, 1, 0, 0, - -601, 378, -71, 61, -160, 800, -386, -773, - 303, -53, 248, -22, 59, -3809, -61, 102, - -45, 395, 0, 0, 28, 0, -12, 0, - 717, -424, 499, 296, -15, 11, 2732, -103, - -119, -116, 107, -50, 462, 73, -82, 75, - 41, 131, 0, 3, 1, -1, 0, 0, - -134, 109, 48, -1847, -205, -6, 20, -203, - 136, 197, 113, -77, -124, -50, 184, 225, - -175, -295, -1, -1, -6, -1, -1, 0, - -59, -2017, -193, -237, 226, 630, 1950, -2, - 179, -3666, -34, 140, 88, 157, 51, 81, - -263, -169, 1, 0, 0, 0, 0, 0, - 229, -14, -1590, -123, 162, 63, -224, -332, - 119, 2931, 21, -48, 406, 15, 320, -51, - 64, -228, -9, -1, 0, -1, 0, 0, - -453, 84, -320, -654, -4, -91, -61, 558, - -61, -233, 31, -224, -105, 63, 86, 3771, - 162, -1535, 3, -3, 1, 1, 0, 1, - -1992, -279, -59, -3048, -1696, 102, -168, 194, - 172, -142, 55, 134, 116, -146, -29, -287, - 102, 265, -3, 1, 0, 1, 0, 0, - -96, 46, -16, 2474, -58, -712, -25, -294, - 187, 22, -39, -102, 62, 2666, -237, -1, - 32, -41, 0, 0, 0, 0, 0, 0, - -282, -25, -198, -862, -127, -379, -210, -20, - 45, -79, -2805, -364, 575, 106, 215, -410, - -76, 511, 15, -44, -1, 1, 0, 0, - 329, 224, 130, 43, -1, -255, -51, -297, - 4529, 52, 186, 757, -68, -89, 46, 250, - 46, -79, 5, 1, 0, 1, 0, -19, - 79, 74, 65, 256, 260, 492, -106, -217, - -357, 20, 166, 233, 132, 165, 18, -1, - 4445, -22, 5, 3, -7, 0, 0, -6, - -922, 2156, 269, 1385, 235, -206, -94, 130, - 112, 145, -126, 166, 1, 45, 83, 36, - -153, -255, 0, -1, 0, 0, 1, 0, - 241, -237, -117, -510, 85, 7, -4418, 30, - 94, -92, 99, -71, 140, -265, 149, 69, - 286, 104, 0, -2, 1, 0, 0, 0, - -165, 22, -245, 29, 50, 145, -53, 1641, - -40, -128, -112, -190, 47, 53, -247, -50, - 88, 39, 1, -1, 0, 0, 0, 0, - -288, 130, 88, -132, 4055, -7, 55, -105, - 277, 81, 69, -66, -53, 52, -56, 90, - 160, 386, 1, -4, 0, -2, 0, 0, - 107, 124, -39, 40, 25, -6, -248, -81, - 70, -13, 46, 5, 20, 24, -5, -2, - -41, -34, 1, 1, -8, 0, -4, 0, - -61, 1, 457, 454, 768, 89, 640, 61, - 66, -360, -2727, -155, -370, -44, -292, 570, - 34, -3209, -5, -1, 1, 0, -1, 0, - 22, -82, -20, -125, -91, 98, 7843, 25, - -2, -31, 2, -52, -73, -25, 31, -35, - -6, -114, 1, -1, 2, 0, 0, 0, - 217, -5202, 86, -76, -76, 109, 389, -95, - -253, 124, 130, 58, 190, -44, -67, -142, - 54, 6, -1, 1, 1, 1, 0, 0, - -183, 547, -200, 348, 372, 437, 425, 547, - -457, 388, 87, 38, -522, -210, -556, 41, - -2979, -17, 7, -4, 6, 0, 0, 0, - 189, 196, 240, -75, 46, -50, 101, -160, - -16, -223, 92, 71, -7633, 78, 90, 69, - 190, -75, 2, 1, -2, -1, 0, 1, - 205, -433, -267, -175, 3068, -210, -514, 330, - -3099, -273, 155, 132, -306, 361, 316, -53, - -421, -125, -3, 0, -11, 0, 0, 0, - 179, -38, 151, -36, 215, -102, -145, 139, - 50, 200, 383, 37, 3102, -27, 9, -157, - -68, 367, 1, 1, 0, 0, 1, 0, - -50, 177, -24, 24, 119, 4, 76, 99, - -111, -7367, 26, 51, -11, -146, -125, -48, - 54, 50, 1, 0, 0, 0, -1, 0, - -71, -16, -184, -61, -36, -151, 79, -128, - -102, 135, -228, 190, -79, -10, -176, -113, - 1008, -856, -13, -4, 8, 28, 0, 1, - -4909, -93, -167, -141, 51, -203, 71, -199, - -49, 106, -142, -94, 126, -225, 158, 36, - 269, 159, 0, 1, 1, 0, 0, -5, - -61, -79, -20, 306, 67, -621, 1774, 346, - -442, 125, 305, -170, 55, -2537, -103, 118, - 87, 505, 16, -7, -2, 0, 20, 0, - 35, -154, -158, 224, -36, -344, 79, 4232, - 234, -219, -71, 204, -484, -131, 1153, 23, - 111, 499, 5, 0, -17, 0, 0, 1, - 1135, -3469, -489, 2572, -450, -432, -358, -34, - -78, -10, -775, 17, -131, -154, 218, 82, - -312, 279, 1, 0, 1, 0, 0, 0, - 96, 230, 18, 47, -5, -102, 646, -122, - 35, -81, 183, 171, -1479, 201, 84, -24, - 143, 302, 1, 5, 0, 0, 0, 0, - -34, -48, 89, 7789, -85, -27, -56, 46, - 39, 30, 98, -40, 138, -147, 104, -35, - -41, -151, 1, 9, 1, 0, 0, 0, - -140, -1970, -170, 273, 226, 33, -324, -38, - 11, 188, 603, 188, -183, 98, -58, -67, - -63, 7, 0, 0, 0, 0, 1, 0, - 384, 899, 493, 765, -1062, 646, 275, -2699, - 93, 796, 120, -25, 177, -85, 721, -189, - -295, -436, 0, -1, 0, 0, -1, 0, - -358, 117, -2435, 325, -3137, -158, 23, 97, - 6, 204, 288, -426, 156, 22, -101, 171, - -56, 235, 0, -1, 0, -1, 0, 0, - 656, 3878, -286, -383, 75, -50, 114, -377, - -105, 106, 154, -30, -204, -105, 171, -56, - 230, -587, 0, 1, 0, 8, 1, -1, - -58, 177, -7, 45, -159, 405, 45, 84, - -206, 77, 277, -259, 121, 3719, 140, 79, - -202, 843, -8, 0, -1, 1, -2, 0, - -248, 560, 2651, -49, -625, -147, -2416, 119, - -70, 87, 137, 18, -401, -147, -598, -150, - 239, -1004, 7, 3, 13, 1, 1, 1, - 276, 342, 97, 600, 230, 95, 213, 159, - -259, -25, -176, 3360, -283, -325, -37, -2626, - -151, 178, -1, -18, 0, 0, 0, 0, - -233, 237, -78, 290, -284, 141, -20, 146, - 58, -21, 73, -35, -101, -23, -4068, -116, - 49, -196, -5, -2, 0, 1, -1, 0, - -292, -195, 51, -714, 172, 44, -119, 134, - 168, 107, -74, -2379, 308, 173, -252, -3470, - -135, 641, -10, 0, 0, 1, 0, 0, - 146, 2060, -84, -164, -247, 26, -1724, 216, - 226, -2499, 312, -66, 850, 41, -1, 20, - -1339, 411, 0, 0, -1, -12, 0, 0, - 921, 17, -3510, -119, 325, 34, -97, -205, - 3, -188, 252, 91, 0, -135, -76, 208, - 199, -202, -1, 1, 1, 2, 0, -1, - -88, -461, 319, -963, 266, 1540, 643, -3424, - 76, -1058, 501, 342, 297, 268, -158, -103, - 26, -30, 0, -1, -1, 0, 0, 0, - 211, 245, 183, 1579, 106, 26, -3450, -22, - -1053, -266, -736, 113, 475, -241, 117, -85, - -492, 372, 0, 1, 1, 0, 0, 0, -}; - -static const int16_t cb0806ss0[] = { - -381, -1638, -8192, 5, 983, -1481, -20, -719, - -238, 767, 571, -200, 754, 460, 1678, 1376, - -155, -1998, 294, -455, 80, 2, 26, 3, - 10, 25, -931, -1098, -1166, -3221, -1995, 702, - 104, -2429, -2270, 1372, 2326, -37, -1492, 1692, - 644, -1283, 363, 624, -483, -15, 346, -6, - 2, 0, 1, 3, 2, -2429, -8192, -956, - 1190, 706, -955, 367, 959, -194, -723, -1104, - 375, 554, -962, -229, 66, 368, 18, -150, - 56, 968, -15, 0, -1, -5, 0, 9, - -250, -720, 1910, 827, 198, -645, 2021, 32, - -1972, -705, 441, 373, 800, -2293, 1747, 1504, - -537, -1731, -1192, 1597, -4031, 24, 0, -2, - 1, 1, 1, -131, 1594, -153, 1127, 2732, - 469, -558, -11, 1190, 115, -933, 1988, 1841, - -4530, 1385, 571, 2399, 1709, -63, -3663, -2681, - 57, -4, 11, -4, 0, -3, 426, -4257, - 2755, -76, -1667, 2450, -373, 3375, -91, -232, - 511, 648, 886, 1182, 1667, 65, -3029, -579, - 865, 2186, 2911, 537, 0, 2, -3, 0, - 7, 585, 8192, -2855, 8192, 5527, -5491, -1926, - -4231, -1204, 1953, -1193, 191, 3278, -1726, 259, - -2794, 4205, 4315, -6121, -606, -1922, 3666, -324, - -238, -313, -720, -1447, -539, -794, 3151, -1726, - 3444, 876, 584, -671, -497, 407, 909, -2183, - 2575, 246, -673, 270, 824, 1784, -201, 7329, - 589, -70, -1, 4, -5, -3, -8, -417, - 382, 2786, -972, 520, 1154, 886, 521, 6032, - -687, 3791, -522, -1226, 608, 428, 891, -1524, - -1015, 1147, 1278, 559, -6, 3, 0, 6, - 2, -3, 115, 3586, -2847, 95, 460, 2832, - 2326, -1665, 1720, 453, 965, 1154, 452, -1721, - -1375, -269, 2138, -2032, 55, -674, -870, -124, - 0, 5, 0, -5, -3, -283, 1077, 2604, - 1270, -1082, -1753, 6840, -2502, 988, -1790, 1378, - 1231, 438, -1188, 286, 540, -138, 1054, -111, - -2321, 74, 56, -3, -2, 0, -32, 5, - 1539, -1399, 7413, -903, -1698, 1781, -255, -466, - -1436, 3419, 1916, 852, 590, -1126, -1617, -1309, - -5560, -241, 3363, -1225, 2682, 620, -6, 58, - 2, -186, -17, -2959, 619, 2228, -2627, -3119, - 730, 3716, -538, -101, -1863, -516, 142, -2384, - -1514, -5506, -825, 514, 714, 746, -2790, 569, - -425, 4, -68, 70, 24, 12, 817, -276, - -3363, -2942, 103, -581, -925, 651, 561, 43, - 434, 712, -541, -2042, -1291, -453, -443, -4312, - -1344, 1277, 605, -4, 0, -1, -1, 1, - 2, -930, 276, 3219, -404, -944, -497, 840, - 278, -98, -1432, -1136, -1975, -1863, -1102, -1446, - 938, 693, -5186, -1, 1085, -2275, 1, 1, - -1, -1, -2, 3, -1194, -312, -1257, 1973, - 1570, -1703, -1637, 639, -855, 1925, 970, 604, - 1313, 780, -5170, -603, 220, -731, 2952, -872, - 166, 30, 0, -2, -1, 3, -1, -743, - 504, 1363, 1436, 1632, -634, -709, -2346, 87, - 1149, 3468, 2132, 3028, -1039, -92, 2087, -990, - -301, 966, -773, -1057, 42, 0, -2, 0, - 2, 2, 252, 217, 3625, -2323, 212, -381, - -1121, 1664, -307, 1680, 2193, -1854, -187, -3100, - 254, -673, 595, 1995, 669, -687, -509, 13, - 0, 8, -3, 11, -3, -552, -87, 6, - 2933, -267, -1392, 40, 644, 32, 2966, -1386, - -2480, -956, 1160, 1399, 1049, 3902, -2092, -525, - 1724, 69, -33, 0, -2, 0, 2, 2, - -452, -4739, -3237, -510, -598, -1397, 855, 1573, - 2143, -79, -1546, -17, -973, -2400, 1689, 133, - -1213, 784, 726, 916, -388, -390, 1, -1, - -3, -1, 0, 170, -205, -2905, 8192, -465, - 3119, 4407, -709, -403, 859, -373, -1301, -1397, - -750, -88, 277, -2097, -222, -134, -88, -1189, - 974, -56, -57, -83, -21, 102, 626, -114, - -2304, 979, -1836, -868, 1261, 2226, -261, 579, - 983, 655, -2578, 1803, 117, -1128, 365, 3971, - 3539, -21, -790, -62, 2, 3, 23, -3, - 31, 1273, 3212, -1617, 4116, -281, 725, -284, - 1079, 293, -3759, 2581, -1617, -259, -19, -1999, - 3040, -3077, -1522, 1056, -92, 897, 243, -1, - 36, -19, -10, -46, 231, 1129, 363, -1978, - -882, -1788, 319, 4807, -1707, -1379, -1465, 2327, - -827, -681, 410, -1816, -2507, 1036, 740, 730, - -687, 100, -1, -1, -1, 1, -4, -276, - 303, -2331, -2912, -1864, -3694, 412, -1218, 1642, - 4448, 658, -213, 872, 2867, 227, 868, -590, - 2293, 1759, -1666, -1585, -140, 1, -3, -1, - 26, -10, -287, 898, -2442, 3997, -1655, -1341, - -56, 689, -1869, 572, -2044, 616, -2603, -278, - 2987, 2397, -2055, 247, 128, 598, 1732, -146, - 0, 3, -1, -3, 5, 842, 597, 779, - -1529, -802, 2142, -1668, 2339, -3550, -2651, 1733, - -1531, -46, 600, 618, -867, -665, 1524, 392, - -1386, -3279, 45, 0, 9, -7, -3, -8, - -224, -2632, -147, -505, 2223, 1773, 1799, -1696, - 194, -1186, -543, 775, -1171, 5491, -2319, -3193, - -313, -355, -133, -1097, 125, -22, -2, 2, - 1, -3, -10, -354, -1447, -662, -313, -4302, - 3888, -121, -323, 1112, -801, -1513, -814, -1646, - -616, -1207, 347, 483, 670, 900, -35, -885, - 14, 1, 0, 1, -2, 7, -432, -486, - -1539, 785, 4853, 904, 925, 895, -1223, -2464, - 3395, -506, -808, 207, 197, 874, -928, 1347, - -107, 1512, 1063, -182, 1, -4, -1, -6, - 3, -1236, -1047, 774, 26, -630, 863, 1055, - -2632, -1187, -534, -619, -1079, -2574, -2037, 658, - 1229, -262, 2702, -3393, -2187, 1764, 66, 0, - 7, 0, 7, -3, 677, -444, -2111, -5256, - -4485, -1667, 2077, 1613, 1483, -1520, 1600, 1767, - 1148, 2054, 1676, 1866, 783, -2199, 765, 568, - 2779, -683, 4, 17, 0, -32, 15, 45, - 228, -2445, 752, 2510, -1657, -1039, 113, 1107, - -1054, -1765, -1245, -2527, 589, 455, 328, 640, - -579, 2370, 1313, -540, 31, 1, -1, -4, - 2, -3, -235, -560, 455, 3809, 102, 403, - -21, 1844, 402, 148, -32, 5573, -3765, -265, - -718, -399, -349, 366, -1105, 91, 1881, 34, - 1, 1, 5, 0, 9, 289, -1146, 795, - -2504, 412, 1156, -302, -946, 2063, -2569, -273, - -1434, 141, 642, -631, 4856, -1008, 169, -40, - 191, -2293, -86, 6, 1, -2, 0, 1, - 139, 1955, -1111, -944, 140, -1074, 1071, -1312, - -541, 664, 1801, -892, 1605, -1750, -654, -680, - -8102, 120, -24, 1014, -351, -120, 0, -2, - 1, -1, -1, 1038, 5199, 779, -1195, 128, - 462, 184, 3705, -1292, -2247, -2481, 2610, 4396, - 4161, 4039, 1111, 838, 188, -571, 2811, -1915, - -1909, 13, 99, -20, -2, 11, 395, 155, - 2667, -202, -2639, 1303, -912, -1734, 1097, -583, - 3532, -218, -1514, -3881, 378, -46, -1189, -957, - -3010, -743, -648, 15, 1, 3, 3, 4, - -4, 330, 198, -275, -677, -8192, -629, 1953, - -783, 592, 926, 1487, -39, -1002, 1134, 1560, - -27, -118, -1363, -360, 2163, 442, 92, 1, - 1, -2, 5, 1, -670, 326, 2773, 1346, - -26, 327, 184, -1091, -121, 576, -1324, 212, - -645, 860, -2111, -493, -2119, 316, -688, 475, - -652, -33, 0, 1, 2, 0, -3, 92, - 170, 6224, 2162, 761, -1994, 2176, 1692, -1773, - 561, -966, 3406, -20, -593, 574, -681, 1121, - -335, -412, -2651, -4712, -79, 1, 2, -1, - 4, -6, 932, -2579, 344, -2614, 1119, 6623, - -314, -1068, 338, 1977, -1375, -1338, -1996, 1310, - 118, -500, -393, 622, -1798, -1232, 3, -75, - 0, 17, 0, -2, -9, 715, 8135, 400, - 3748, 2156, 1882, 772, 2728, -403, -775, 2110, - 1603, -766, -2592, 767, -618, 4727, 668, 2280, - -1157, 1246, -794, -14, -2, 2, 5, 16, - -107, 642, -1806, -158, -2447, 309, -764, 2313, - -101, -766, 209, -691, 2001, 268, -273, 615, - 803, 6062, -434, 1287, -543, -3, 0, 0, - 1, 1, 0, 503, -598, -2043, -1160, 1074, - 1255, 3269, 1405, 1182, 197, 3098, -138, 2326, - -244, -772, 901, -225, 337, -65, -536, -331, - 15, 2, 13, 8, -3, 20, -32, -52, - -1012, 232, 1502, -17, -1574, -741, -57, 164, - -22, 74, -181, 1616, 296, -1483, 1387, -357, - -5380, -322, -1346, 6, -3, 2, -3, 1, - 0, -392, -811, -650, -485, 3038, 2750, -776, - -503, -1664, -323, 253, -280, -3459, -1313, 541, - 2182, 1287, -782, 1785, -695, -49, 72, -4, - 0, -15, 3, -21, -211, 1382, -149, 684, - 2210, 2654, -1440, -1209, 152, 1080, -3078, -694, - 4738, 985, -1337, 819, -518, 1799, -671, 3201, - 2636, 7, 1, -6, 14, -31, 0, -34, - 4296, -23, 194, 1976, -993, 1353, 709, -342, - -1142, -140, -271, 2291, -709, 1734, 818, -3571, - 1125, 912, -590, 784, -275, -2, -1, -5, - -1, 0, -381, 2754, 1545, -2270, 3608, 2308, - -1899, 178, 391, 1826, -127, -1417, -822, -712, - 1682, 2225, 2247, 446, 994, 56, 734, 196, - 7, 3, 8, 0, 7, 639, 833, -3313, - 675, -263, -648, 3016, -701, 235, -1304, -582, - -2930, -210, -1243, 374, -3095, -2013, 354, 599, - -1469, 140, -17, -1, -3, 2, 0, -2, - -183, 399, -603, 796, -1424, 2685, -3929, 416, - -2291, 1737, 1906, 1667, 810, -222, 3242, -3636, - 5196, -1542, 940, -124, 2047, -67, -4, 6, - -1, 13, 2, -161, 417, 4132, 492, -1068, - -817, 2732, -250, -1457, 1723, 2104, 1121, -1276, - 1147, 990, -523, -1533, 297, 1219, 3901, -2549, - -22, 0, 0, 0, 0, 2, -1632, 172, - 829, -747, -1229, -1990, -1070, 1134, 1623, 228, - 3689, 625, -757, 8192, -82, 738, 213, 1900, - -1200, 91, 892, -45, 15, -1, 5, -4, - 5, 392, -3067, -1903, 139, 661, 43, 2174, - -1919, -270, -1490, -569, 2, 85, -1091, 6740, - 886, 85, -1052, -647, -563, -2971, -145, -1, - 39, -5, -6, -7, -1023, -1104, -1774, -3154, - -1058, 3488, -2551, 3547, -253, -204, -235, -1544, - -73, -584, -302, -3118, -2314, -308, 1790, 916, - 152, -155, -11, 6, -26, -1, -31, 21, - 919, -1856, -456, -1050, 663, 1454, -1515, -2606, - -4287, 1553, 3564, 1334, 1797, 1540, -392, -701, - -971, -3442, 281, -271, 133, 1, 5, 4, - 32, 3, -521, -1530, -1368, 1787, -515, -913, - -2391, 93, 2690, -578, -576, -1656, 554, 649, - -1509, -258, -605, 1233, -2258, 640, 837, -43, - 1, -3, 0, 5, 3, 148, -4761, 1783, - 3244, -277, -1139, 1539, -2016, 1898, -1276, -776, - -1725, -1900, -51, 559, 311, 1737, -928, 3687, - -1087, 1329, 134, 2, -2, -7, 9, 5, - -77, -1116, 4986, -940, -905, -3229, -773, 3335, - -23, 578, -2376, 386, 122, 1253, 363, -2748, - -512, -4612, 1690, 848, -1116, 195, 5, 2, - 11, 1, 18, 659, -1282, 562, 1170, 4701, - 903, 490, -3508, 3468, -39, 654, -1196, -909, - -268, 980, 283, 3221, 348, 1121, -897, -1011, - -103, -11, -2, -9, 16, -8, -274, -4100, - -2312, -2379, 617, 1629, 2154, 3026, -1737, -603, - -803, -366, 977, 1035, -1835, -255, -275, -1245, - 1274, -161, -4476, -181, -4, 0, -2, 1, - 2, 156, 551, -832, -630, 3740, -2115, 344, - 229, 1295, 65, 290, -1462, -1794, 3297, -1049, - 2451, 322, -2642, -2810, -1246, 613, 90, -1, - -1, 0, 0, 0, -277, 854, 1259, 1542, - -433, 3601, -453, 1091, -113, 1438, 994, -2746, - -786, 867, 1422, 1093, -1723, -1167, -1389, -1062, - -436, -81, 2, 1, 11, 1, 26, -197, -}; - -static const int16_t cb0806ss1[] = { - 1760, -4335, 6384, -2036, 2874, -2504, -1529, 102, - 6995, -1267, -3141, 1050, -59, 1556, -1002, 1536, - 1024, 1867, 40, -1156, -2627, -213, -1034, -660, - 291, -963, -323, 462, -804, 2219, -859, 1709, - 550, -3390, 319, 24, 644, 3154, 4503, -1961, - 744, 194, -151, -1255, -1318, 3033, -899, -18, - 1, 0, 2, 0, 28, -1213, -3725, -2525, - -177, -1164, 361, -357, -649, -459, 1324, 2463, - -3108, -3323, -575, -2744, -108, -121, -508, -564, - -849, -773, -288, 0, 8, 0, -2, 5, - 691, -602, 2269, 2373, -2027, 786, 3011, 3234, - -1387, -310, 659, -358, 1058, -1554, 1031, 795, - 2254, -549, 334, 325, 599, -36, -1, -1, - -2, 3, 4, -450, -533, -1657, -1928, -1034, - -636, -1446, -320, 2695, 1184, 697, 1126, 1159, - 2970, 449, -30, -2058, -1171, -684, -66, 905, - -43, 1, 0, 3, 0, 3, 228, 272, - -79, -718, 1978, 667, -2760, 1507, -1893, -796, - 1164, 35, -4440, -4492, -1667, 4189, 6485, -495, - 1721, -1639, -526, 458, 0, 385, -183, 511, - -153, -2025, -376, 2948, -2606, -910, -741, -427, - -1080, 2128, 565, -483, 1791, -2222, -45, -1204, - 799, 512, -4790, 1462, 511, -1906, 15, 0, - 0, 1, 3, 8, -867, -685, -140, 5299, - 376, -891, 1657, 1843, -1465, -1297, 518, -4640, - 303, -277, -650, -97, 2308, -679, 720, -171, - -475, -269, 0, -5, 4, -1, 9, -1155, - -4954, 1684, -2045, 939, 819, -751, -165, -93, - -2327, 306, 965, 4999, 557, -55, -999, 30, - -36, 989, -1680, -1594, 318, -3, -8, -4, - 1, -9, -402, 8192, 475, 2080, -418, -1739, - -273, -55, -441, 794, -79, 272, -2039, 789, - 2266, 874, 2495, 627, 2203, 1212, -1052, 389, - 14, -24, -59, 10, 133, -535, -1160, -1139, - -146, 180, 1064, 3718, -1412, 1153, 1873, -549, - -1698, -1479, 209, 725, -940, 2152, 1848, 678, - 2493, 4608, -11, 0, -1, -3, -3, 2, - 334, 681, 673, -8192, 3958, -3111, 1641, 1500, - 1184, -268, -3147, 571, 958, -663, -1031, -870, - -674, -1098, -529, 78, 1212, 120, -8, -13, - -5, -42, -37, -498, 1304, -2541, 1730, -355, - 1462, 2315, 2017, -403, -2010, 555, 1391, 887, - 2039, 366, 135, 85, 371, 1291, -225, 335, - -45, 0, 1, 2, -1, 2, -1095, -261, - 3249, 3212, -1877, 934, -1671, -1289, 1398, -2287, - -205, 1659, 642, 1105, 751, 2864, 1171, -1001, - 318, -290, 60, -54, 5, 3, 5, 2, - 1, -105, 590, 36, -194, 1832, -639, 777, - 3243, 578, 2820, 428, 2020, 623, -2104, -52, - -331, -1015, 3064, -347, -303, -1100, 61, -1, - -1, 0, 2, -1, 592, 127, 887, -1094, - -2819, 2573, -2670, -1693, -2775, 48, -266, -961, - 1220, -472, 167, 3201, 1118, -173, 1304, -26, - -899, 76, 0, 3, 0, 1, -1, -718, - -746, 947, -524, 142, 958, -1609, -777, -1362, - 385, -578, -6947, 157, -290, 1357, -1703, 484, - 117, -2224, -3736, -838, -96, -1, 11, 5, - 4, 2, 475, -426, 500, -767, -2304, 1248, - 2200, -1829, -992, -225, -573, -1107, -832, 2555, - -2866, 3453, 4335, -88, -1160, -1666, -94, -33, - 0, 0, 1, -2, -7, -147, -8192, 1204, - -1181, -702, -604, -770, 1032, -173, 770, 861, - 611, -509, 802, -467, 839, 491, -785, 523, - -669, 73, -34, 0, 0, -2, -3, -3, - 286, -2183, -1238, 1743, 387, -2228, -1404, -3439, - -1701, -2371, -451, 2294, 2061, 3062, -1122, -1489, - -1274, 51, 5649, -170, 2197, 365, -1, -13, - 4, 3, -5, -15, -4099, 789, 4132, 4982, - -1996, 784, 748, 2123, 3535, -1493, -1454, -344, - -867, 40, 831, -1198, 66, 542, 1633, -2402, - 117, -119, -18, 49, 18, 40, -500, 808, - -726, 1192, 3623, 1526, -484, 1080, -2502, -579, - 1315, -1887, 84, 1771, -2902, 1387, -1098, 1559, - -1126, 652, -896, 32, -1, 3, 1, 3, - -2, 233, 782, 8192, 566, -701, -352, 1047, - 581, -1070, 3159, -1157, -1585, 1599, -978, -663, - -931, -2581, 5074, 781, -551, -590, -247, -63, - -54, -50, 253, -138, -313, 387, -3004, -1136, - 654, -1283, 1318, 434, 80, -1486, 694, -512, - 393, -238, -700, -232, 706, 1478, -8192, 377, - 601, 18, -1, -3, 0, -6, -3, 2221, - 3531, -862, 1792, -242, -3686, 420, 1891, 918, - 1324, 234, -819, -601, 2363, -1097, 2355, 754, - -125, 245, -615, 3285, 204, 0, 6, -4, - -3, -1, -637, 673, 1233, 2886, 265, -195, - -226, 2521, 281, -210, 1809, -2733, -3865, -2287, - 641, -2604, -4235, 107, 789, 1163, -2600, -463, - -5, 10, 2, -10, 39, 1380, 754, -5077, - 4061, -1633, -1738, -1604, 1937, 1815, 1039, 3696, - -593, 2218, -1061, 1081, -1217, 2062, -637, -1580, - 149, -626, -253, -3, -17, 2, 33, 1, - 118, 525, 158, 1213, 910, -105, -1437, -1311, - 2255, -419, -2394, 1542, -3830, -1167, -998, -1099, - 1635, 1678, -1112, -275, 122, -50, 0, 3, - 0, -1, -1, 998, -4020, -1913, -1083, -159, - 1853, -436, -683, 298, 211, 711, 4128, -1977, - -958, 1048, 642, -420, 329, -1150, 459, 2161, - 29, -4, 0, -1, -6, 1, 1365, 1053, - 1032, 952, 854, 2405, 5106, 1863, 3049, 981, - -863, -397, 508, -1283, -631, 17, 532, -1453, - -1056, 66, 501, -27, -1, 3, -1, -13, - -2, -273, -2924, 839, -433, -395, -252, 1945, - 195, -307, -1297, -1474, -985, 4412, -1017, 1074, - 2711, 996, 919, 183, -10, -605, 38, 1, - -1, -1, 2, 1, 2115, -422, 3655, -1972, - 1473, -2033, 2461, -1112, -1267, 179, -394, -906, - -1273, -432, 1082, 367, -720, 1746, -657, 595, - 701, 16, -1, 0, 0, 2, -3, -255, - 443, -1840, -2379, 296, 258, -675, -221, 406, - -216, -6295, -1041, 1062, 199, 1705, -1032, -1627, - -2399, 198, -1097, -271, -99, 0, 1, -2, - 2, -13, 343, -219, -1447, 1779, 630, -1944, - -1093, -1578, -62, -1334, 2811, -815, 1311, -3102, - -300, 67, 24, 98, 764, -1246, 203, 6, - 0, -4, 0, 1, 0, -18, -1704, -1427, - -352, -2665, -588, 287, 715, -454, 688, -424, - 1736, -1124, 1028, -7581, -752, -482, -363, -75, - -720, -619, 449, 0, 3, 0, 16, -3, - -1211, 2484, 3490, -547, -705, 1776, -286, -1580, - 2896, -2257, -214, -1784, -1266, -562, -1170, -542, - 785, 1606, 535, 51, -1405, -7, -1, -1, - 0, -1, 2, -428, -579, -1091, -2627, 2287, - -757, 1445, -411, -160, 567, 108, -1305, -4356, - -390, -917, 345, -2169, -896, 3772, 1224, 691, - -25, 1, 1, 1, -2, 1, 281, 1365, - -1628, -585, 3485, 169, 746, -395, 1072, 1569, - -1073, 744, 1274, -3472, 1035, -906, -3394, -1537, - -869, 2841, 401, 4, -1, -3, -3, -1, - -3, -37, -1628, -888, 785, 3328, 1105, 3551, - 6946, -1688, 2690, -2051, -2212, -3750, -1903, -497, - 1251, 1187, -6198, 3930, 85, -1077, 16, -23, - -80, -130, 43, 66, -974, 579, -2047, -3607, - -666, -2248, 4619, 6846, 88, -649, 1129, -255, - 3567, -124, 41, 58, 634, -1252, 696, 2536, - -1590, 209, 12, -102, -275, 27, 216, 1110, - 259, -2091, 1775, -3768, 598, 441, -1809, -431, - 22, -991, -621, 84, -1803, 1585, 559, -1101, - 42, 456, -392, -874, -4, 0, 0, 1, - -1, 0, -371, -211, -339, -1232, 438, -2683, - -1007, 1250, 5343, 861, -1305, -577, 2107, -2649, - -3227, 1020, -127, 562, 5495, -3136, -414, -529, - 12, -53, -34, 151, 106, -2946, -575, -1796, - 3095, -257, -591, 126, 967, -547, -271, 560, - 974, -3335, -2110, -1403, 5915, -1108, 388, -1266, - -522, 336, 167, 1, -3, -2, 2, -3, - -312, 19, 3356, 1123, -676, -247, 697, 548, - 1768, 1174, -525, -253, -423, 546, -2373, -2940, - -1055, -2304, 203, 1309, -574, -8, 0, -3, - 4, 0, 4, -215, 8192, -670, -1289, -1547, - -304, 1498, -967, -529, -582, -2205, 1752, 321, - 573, -1096, 64, 1152, -87, 574, -250, 539, - 62, 7, 2, -1, -3, 3, -465, 243, - -1179, 828, -2501, -223, 198, -883, -740, 1113, - -1821, -2068, -3234, 1715, 1989, 1817, 727, 1640, - 3386, -1538, -864, 45, 0, -4, 0, 0, - 2, 608, -1495, 1259, -132, 1311, 350, 537, - 2735, 1428, 151, 1324, 547, -3983, -1892, 104, - 2023, 1908, -1042, 1130, 1252, -701, 9, 0, - -2, -1, 1, 1, 602, -8192, -2776, -661, - 1640, 443, 3452, -738, 829, 637, 292, 232, - 1352, 4879, 1429, 912, 649, 1593, 308, -330, - 68, 63, -3, 4, -57, 26, 25, 1250, - 400, -4839, 211, -2748, -664, 996, 341, -1053, - 321, 2458, 764, 743, -729, 12, -283, -346, - 118, -249, -153, -2329, -37, 0, -1, 0, - 1, 1, 352, -878, 2336, -634, -2690, -3415, - -2949, -531, 1259, 394, 163, -994, 845, 1259, - 890, 1400, 279, 1908, 161, -2174, 1876, 76, - 1, -1, -1, 10, 0, 47, -1123, 1611, - 489, 618, -816, -7, 2001, -1190, 1857, -2749, - -311, -331, 733, 1412, 1390, -1525, 1262, -1393, - -263, 3124, -98, 0, 1, 0, 1, -2, - 514, -3533, -2394, 3623, 249, -1056, 515, 1279, - 2821, 477, 183, 689, 1182, 1378, 1287, -711, - 1264, -713, -278, 217, -664, -225, -1, 0, - 6, 2, 9, -1171, 3119, 1340, -1229, -1929, - 1984, -1333, 1018, 10, 1205, 63, 358, -1108, - -455, -413, 854, -1550, -423, -180, 2529, -8192, - -18, 0, -2, -1, 0, 0, -678, 3819, - -1316, 1159, 590, -231, 2203, -1533, 986, 4289, - 1114, 1135, -1162, -921, -58, 691, 11, -1718, - -270, -531, 530, 65, 0, -1, 1, 4, - 0, -1184, -1359, 7230, -533, -2077, -1188, 113, - -1472, 490, 1518, 1476, -1885, 934, 244, 1840, - -696, -480, -2476, 3324, -2433, 1102, 120, 1, - -11, -2, 18, -3, -1016, 189, -3835, -1659, - -46, -180, -2659, 1998, -1437, 1107, -2248, 165, - -657, -5079, -224, 1246, 469, 421, 1145, 1148, - 84, -18, 3, 0, 0, -6, 0, -66, - -206, 2279, -220, 1606, -421, -1482, -413, -1237, - 374, 3691, 491, -774, 410, 791, 380, 3385, - 615, -950, -620, -197, 65, -1, 3, -3, - 2, -1, -484, 1396, 273, -3591, 1317, -1013, - 1563, -134, 602, -1069, 733, -1167, 233, 319, - -262, 350, 780, -407, -496, -1285, 1326, -13, - 0, 2, -1, 0, -1, -328, -626, -848, - 745, -1047, 4048, -380, -456, -1894, 869, -1085, - -373, 2829, 622, 473, 394, 237, -2175, 1167, - -4942, 246, 100, -1, 1, -6, 1, -6, - -70, 35, 1613, 2597, 1307, 1756, -1184, 1082, - 971, -2004, -1459, -494, -40, 745, 2788, -830, - 76, 536, -2002, 401, -57, -20, 0, 0, - 0, 0, 0, -8, 244, 1927, 1162, -2416, - -1414, 463, -89, 1217, -798, 394, -1527, -719, - -666, 998, 1518, -2455, -3049, -1174, -2696, -3119, - 2, 0, -2, 2, 2, 3, 1093, -623, - 1660, -1635, 1457, 2560, 763, -2750, 931, 1798, - 2550, 1402, 914, -919, 1931, -383, -435, -583, - 439, 9, -1106, -12, -1, 0, 0, 0, - -2, -335, -730, -2102, -1414, 2576, -3869, 1025, - -1657, -2, 857, -336, -3011, 205, 1108, 364, - -789, -179, 171, 331, 2204, 527, -13, 1, - -3, 2, 1, -4, -565, -211, -139, 1799, - 195, -877, -632, 358, -244, -1459, 1398, 2271, - 550, 1987, 2206, -337, 199, -7036, 589, 195, - -466, 72, -1, 2, 1, 0, 0, -27, -}; - -static const int16_t cb0806sm0[] = { - -8192, 389, 245, -67, -42, 79, 503, -488, - -310, 107, -13, -431, -203, 96, 510, 151, - 270, 0, 0, 0, 0, 0, -463, -23, - -72, -322, 74, 1589, -152, -198, 81, 1120, - -125, -434, -3275, -2210, -348, -344, 91, 0, - 0, 0, 0, 0, -254, -224, 46, -154, - -131, -465, -57, 8192, 345, 112, -725, -49, - 183, -191, 246, 263, 370, 0, 0, 0, - 0, 0, 39, -739, -6603, -2454, -95, 312, - -53, -392, 63, -165, 31, -505, 111, 484, - -535, 179, 143, 0, 0, 0, 0, 0, - 1279, -139, -1769, 244, 59, -135, -429, 707, - 809, -4355, -354, 428, -300, 108, -799, -1421, - 599, 0, 0, 0, 0, 0, 4, -5, - 7, 75, 49, 8192, 276, 200, 191, -167, - -14, 82, 222, -277, -483, -216, -441, 0, - 0, 0, 0, 0, 171, -423, 174, 401, - -517, -377, -234, -644, -829, -350, -976, -146, - -928, 296, 3003, 3545, -30, 0, 0, 0, - 0, 0, 161, -6753, 1138, -855, -132, -242, - 559, -225, -346, -168, 10, -481, -6, -1208, - 252, -323, -191, 0, 0, 0, 0, 0, - -262, 574, 433, -145, 622, 329, -2634, -439, - -1178, 351, -433, -842, 4125, 296, 305, 359, - -22, 0, 0, 0, 0, 0, -34, -56, - -1019, -247, -163, 305, 574, -51, -179, 24, - -1097, 248, -166, -18, 303, 252, -555, 0, - 0, 0, 0, 0, -400, -254, -256, 2783, - -296, -1904, 552, 1284, -336, -2371, 3396, -1092, - 102, 176, 140, 640, -359, 0, 0, 0, - 0, 0, 373, 473, -2167, -774, -388, 405, - -1402, -1391, -1319, -155, 1104, -533, 382, 1561, - -2958, 406, 787, 0, 0, 0, 0, 0, - -3800, -58, 2098, -181, -570, 385, -4125, 759, - -1584, 9, -278, 201, -528, -527, -435, 436, - 681, 0, 0, 0, 0, 0, 30, -80, - -60, -4031, -70, -3367, 316, -861, 67, -169, - -144, 1598, 966, 32, -1263, -434, -738, 0, - 0, 0, 0, 0, 181, 12, 115, 91, - 253, 518, 517, 216, 830, 336, -568, -3125, - -796, -847, 1627, 58, -158, 0, 0, 0, - 0, 0, 48, -851, -286, 393, 390, 707, - 595, 427, -235, -116, 814, -198, 6145, -1590, - 647, 15, -259, 0, 0, 0, 0, 0, - -621, 152, 590, -16, 215, -633, -784, -140, - 1087, 723, -4191, 2701, 951, -972, 273, -554, - 387, 0, 0, 0, 0, 0, -124, -2939, - -38, 383, 234, 687, -2873, -466, 61, -472, - 854, -396, 305, -233, 82, -2677, -206, 0, - 0, 0, 0, 0, -120, -246, -614, -394, - 8192, 75, -450, 177, -251, 45, -142, 65, - -1248, -14, 389, 375, 114, 0, 0, 0, - 0, 0, 2870, 158, -473, -166, 928, -618, - -1909, 224, -931, 1898, -16, 427, 447, -1044, - 85, -333, 197, 0, 0, 0, 0, 0, - 78, 114, -167, 73, -1070, -80, 3512, -3004, - -1553, 769, 213, 851, -377, 978, 1097, 71, - 66, 0, 0, 0, 0, 0, -129, 248, - 455, -376, 344, 128, -60, 546, -321, -7898, - -719, -55, -941, 1242, 207, 215, 323, 0, - 0, 0, 0, 0, -24, -225, 136, 142, - -739, -117, 2, 242, -152, -20, -1775, -484, - -36, -408, -2767, -471, 251, 0, 0, 0, - 0, 0, 22, 111, -180, -7417, 365, 293, - -313, 1031, -191, 154, -210, -239, 121, -333, - -1504, 209, 146, 0, 0, 0, 0, 0, - 898, -643, 3080, 528, -91, -718, -512, 275, - -3564, 396, 160, -850, 346, -595, 1558, 684, - -310, 0, 0, 0, 0, 0, 234, -419, - -724, -433, 292, -1003, 682, -117, -1318, -914, - -5137, 128, 53, 291, 408, 1269, -284, 0, - 0, 0, 0, 0, -252, 190, -2911, 130, - 255, -172, -4331, 26, -267, 280, -133, -613, - -1063, -1135, 759, -1290, 216, 0, 0, 0, - 0, 0, 133, -177, 4069, -311, -197, 3260, - 341, 201, -117, -515, 105, -658, 975, 81, - -333, -333, 262, 0, 0, 0, 0, 0, - 273, -87, 321, 190, 1385, 274, 182, -2553, - -150, 164, -830, 89, -459, -5279, -624, -336, - 399, 0, 0, 0, 0, 0, -172, -232, - 11, 45, 121, -254, -457, 196, -3487, -838, - 512, -310, -2831, -85, 98, -145, -331, 0, - 0, 0, 0, 0, -55, -149, 2068, -61, - 3087, -143, 1574, -1381, 2853, 1899, -453, -580, - -137, 1211, -1413, 171, 125, 0, 0, 0, - 0, 0, -228, 30, -956, 5569, 209, -89, - 25, 573, -1669, 507, 182, -132, 697, -132, - -2964, -637, 139, 0, 0, 0, 0, 0, - -3078, -3278, -771, 928, -38, -463, 820, 1141, - -1234, 620, 652, -1710, -382, -1618, -409, 179, - 483, 0, 0, 0, 0, 0, -102, 4256, - -20, -162, 2021, 730, 1439, 2776, 459, 498, - -152, 482, 35, -271, 810, -1345, -249, 0, - 0, 0, 0, 0, 131, 5, -281, 431, - -2498, -1046, 482, 842, 297, -311, -1260, 148, - -906, -4217, -1411, -102, -361, 0, 0, 0, - 0, 0, 116, -3083, 235, -1195, -19, -646, - 42, 487, 309, 1654, 1051, -1643, 689, -823, - 2279, 1488, 571, 0, 0, 0, 0, 0, - 42, -95, -3, 36, -170, -114, 8104, 217, - 140, -217, 599, -774, -64, -675, -211, 166, - 204, 0, 0, 0, 0, 0, 99, 594, - -48, 224, 52, -1499, 271, 2224, -219, 3184, - -165, 828, -1345, -785, 181, 133, 124, 0, - 0, 0, 0, 0, -235, -286, 254, -171, - -4980, -453, -1432, 12, 734, -391, -640, 339, - 537, 313, -700, 1016, 148, 0, 0, 0, - 0, 0, -49, -19, 803, 935, 520, -90, - 641, 1053, -454, 2338, -6071, -478, 616, -559, - -339, 445, -1464, 0, 0, 0, 0, 0, - -175, 111, -132, 65, -264, 732, 221, 231, - -1972, -305, 325, -859, 583, 1272, -441, 2651, - 229, 0, 0, 0, 0, 0, -286, -4646, - -262, 593, 613, 936, 310, -615, 83, 223, - -816, 1910, 2041, 281, -190, -434, 114, 0, - 0, 0, 0, 0, -123, 684, -208, 524, - -606, -1223, 264, -983, -109, -1057, 696, 195, - -521, 945, -7503, 193, -120, 0, 0, 0, - 0, 0, 98, -358, -2165, 244, 277, 393, - 771, 3360, -258, -1218, -122, -1253, -2297, 806, - -198, 540, 7, 0, 0, 0, 0, 0, - 78, -281, -368, 2809, 159, 2611, 833, -120, - -3987, 933, 360, -49, -515, -106, -360, 650, - -125, 0, 0, 0, 0, 0, 203, 1369, - 749, -502, -2295, -326, 448, -309, 630, -84, - 345, -520, -4, -623, 1066, -3915, 373, 0, - 0, 0, 0, 0, -4603, -794, -625, -355, - 1071, -601, -553, 593, -296, 626, -328, 621, - 85, 1348, 92, -288, 204, 0, 0, 0, - 0, 0, -9, 602, -162, -749, -104, 464, - -372, -1375, -1905, 2200, 61, -3308, -897, 634, - 1036, -2112, -182, 0, 0, 0, 0, 0, - -76, 2341, -675, -72, -29, 704, -536, 1656, - -541, -736, -1420, -1539, 2458, -228, 674, -1258, - -3, 0, 0, 0, 0, 0, -133, 1111, - 63, 327, 470, 1226, 541, -276, -3042, -1594, - -3192, 357, -617, 658, -315, -978, 631, 0, - 0, 0, 0, 0, 111, -188, 619, 236, - 104, 54, 545, 424, 5912, -332, 711, -1249, - -533, 291, -1544, -216, 113, 0, 0, 0, - 0, 0, -199, 267, 152, -301, -172, 1294, - 2311, -482, -2451, -82, 1833, 214, 130, -1183, - -2212, 403, -625, 0, 0, 0, 0, 0, - -106, 662, -48, -131, 324, 2337, 445, 462, - -349, -189, 669, 4945, -1797, 16, 268, -602, - 2, 0, 0, 0, 0, 0, 55, 154, - 892, -35, -145, 357, 562, 42, -9, -284, - 177, 84, 422, -181, -358, 7618, 29, 0, - 0, 0, 0, 0, -353, 68, -41, -4096, - 177, -20, -267, 782, 954, -430, 1573, -696, - 1785, -3611, 89, -243, 683, 0, 0, 0, - 0, 0, -220, 1983, -891, 614, 226, -202, - 67, 761, 1904, 179, 226, 416, -657, -3409, - 1026, 2834, -438, 0, 0, 0, 0, 0, - -551, -229, -304, -462, -2277, -419, 451, -122, - -108, 258, 784, 1105, 382, 137, 5695, -241, - -491, 0, 0, 0, 0, 0, 34, -272, - -1687, 1769, -332, 365, 33, -2594, 3729, 325, - 85, -295, -290, -152, 2238, -611, -41, 0, - 0, 0, 0, 0, 102, 166, 241, 1098, - -107, 775, -414, 4256, -277, 935, -200, 495, - 255, 1144, 468, -184, -59, 0, 0, 0, - 0, 0, 94, -282, -57, 12, -390, 245, - 1872, -620, 1089, 3754, 432, 947, -509, -284, - -3836, 26, 482, 0, 0, 0, 0, 0, - 9, 971, -373, 1111, -480, 2342, -182, 528, - 802, 1196, -1017, -879, 499, 2800, -830, -230, - -4, 0, 0, 0, 0, 0, -382, -815, - -1669, -2437, -593, 193, -688, 632, 479, 2883, - 565, 540, 5, 1598, 1618, -640, -246, 0, - 0, 0, 0, 0, -421, -103, 1482, -3026, - -65, -101, 4, 3921, 688, -941, -234, 49, - 202, 1905, 935, -1155, -4, 0, 0, 0, - 0, 0, 210, -625, -118, -3215, 344, 978, - -10, 773, -126, -804, -1534, 182, -1146, -646, - -146, 2011, 463, 0, 0, 0, 0, 0, -}; - -static const int16_t cb0806sm1[] = { - 35, -237, 547, 705, -9, 1612, 382, 195, - -191, -250, -101, -357, 709, 153, 850, -5091, - -100, 0, 0, 0, 0, 0, -6406, -158, - -527, 137, -330, 580, -484, 63, 541, -1245, - -205, 138, 247, -489, -147, -132, -863, 0, - 0, 0, 0, 0, 53, -38, 283, -22, - -1506, -467, -418, 117, 133, -2152, -48, -991, - 808, -1047, 2402, 261, 423, 0, 0, 0, - 0, 0, -14, 500, 4697, -174, -544, 87, - -379, -243, 577, 682, 258, -1190, -1984, 599, - 607, -123, -290, 0, 0, 0, 0, 0, - 60, 4254, 194, 888, -81, -395, 422, -1786, - 916, 288, 1191, -658, 502, 2177, -977, -301, - 587, 0, 0, 0, 0, 0, 232, 204, - -452, -853, -4266, -219, 1164, 92, 91, 1561, - 950, -705, -1217, -734, 1617, 120, -324, 0, - 0, 0, 0, 0, -3442, -456, -667, 987, - -89, 1383, -704, -187, -280, -583, 341, -732, - 649, -2129, -3505, -175, -215, 0, 0, 0, - 0, 0, 200, -635, -471, -1221, 215, 2844, - 1633, 522, -720, 1722, -272, 473, 198, -604, - 480, -88, 169, 0, 0, 0, 0, 0, - -160, -268, 130, 284, -612, 95, 43, 42, - 641, -258, -6884, -167, -689, 123, 276, -592, - 717, 0, 0, 0, 0, 0, 313, -90, - -4310, 2706, -1708, 648, -796, 791, 998, -468, - 632, 1893, 43, 1937, -1279, -22, -64, 0, - 0, 0, 0, 0, -106, 135, -287, 335, - -7999, 51, -250, -388, 16, 285, -101, 685, - -944, 604, -624, -792, 209, 0, 0, 0, - 0, 0, 496, -205, 422, 49, 274, -229, - 220, 73, -734, 381, -394, -8192, -405, 755, - -9, 46, 116, 0, 0, 0, 0, 0, - -28, 332, 1152, -129, 244, 84, -2193, 632, - -1854, -384, 110, -302, -270, 435, -1689, -797, - 686, 0, 0, 0, 0, 0, -1660, 624, - -664, 2611, 30, -1155, -419, -3539, -568, 1719, - -1374, -676, -55, -1934, 863, 1391, 433, 0, - 0, 0, 0, 0, -1012, 290, 2302, -330, - -95, -2355, -55, -763, -1995, -298, -680, 715, - -85, 1615, 1011, -1989, -1028, 0, 0, 0, - 0, 0, 21, -5001, 507, -58, 229, -37, - -113, 632, 1809, -62, 334, -1201, -893, -344, - 98, 438, -65, 0, 0, 0, 0, 0, - 0, 143, 131, -18, -135, -306, 392, 232, - 265, 543, 376, -562, 362, 2458, 785, 3653, - -456, 0, 0, 0, 0, 0, 855, -4009, - -1207, 118, -86, -223, 266, 154, -1886, -1145, - 241, -397, 246, 244, -776, 808, -132, 0, - 0, 0, 0, 0, 2, -633, 113, -94, - -154, -173, -162, -168, 439, -6548, 778, -392, - -60, 99, -1901, 171, -130, 0, 0, 0, - 0, 0, -11, -324, 711, -903, 560, -1654, - 1473, -300, 1048, 137, -1140, -1115, -1302, -1008, - -792, -3264, -540, 0, 0, 0, 0, 0, - -347, 78, -103, -7, -3, 437, 6053, 299, - -435, 323, 664, 477, 1097, 158, 656, 273, - 200, 0, 0, 0, 0, 0, -101, 80, - -153, 144, -235, 492, -399, -3, 4958, 699, - -586, -162, 153, -860, 161, 665, 4, 0, - 0, 0, 0, 0, -87, -189, 1744, -350, - -1840, 325, -2354, 1193, 1386, -1589, 80, 1055, - -188, 273, 807, 2038, -419, 0, 0, 0, - 0, 0, 50, -185, 68, -59, -9, 78, - -585, -121, -7888, 771, -908, -284, 349, 158, - -1122, -139, -189, 0, 0, 0, 0, 0, - 310, -286, 235, -687, -919, -364, -697, -253, - 492, 300, -238, 272, 518, -525, -5863, -190, - -59, 0, 0, 0, 0, 0, 151, 616, - -4420, 227, 240, -252, 516, -250, 68, 411, - -192, -87, -607, 671, 1281, -317, -305, 0, - 0, 0, 0, 0, -9, 817, -451, -1079, - 86, 5060, -1157, -1159, -421, 302, 1636, -316, - -66, -518, 1010, 1068, 96, 0, 0, 0, - 0, 0, -576, -362, 107, 3516, 303, -364, - -402, 805, 574, 993, -554, 298, -925, 410, - 1898, 13, 138, 0, 0, 0, 0, 0, - -340, -150, 528, 142, -464, 1034, -397, 3944, - -697, 962, 902, 1393, 2212, -1021, -1034, -961, - -319, 0, 0, 0, 0, 0, 58, 38, - 382, 221, -212, 826, -1373, -4559, 1329, -123, - 216, -23, -736, 95, -300, -418, -4, 0, - 0, 0, 0, 0, -58, 7814, 218, 141, - -90, -124, 455, -27, 49, -311, -364, 80, - -136, -1257, 96, 332, -287, 0, 0, 0, - 0, 0, -8, 624, 127, 1857, -480, -869, - -575, -1461, -493, -261, 97, 32, -328, -467, - 173, -2588, 132, 0, 0, 0, 0, 0, - 5257, -1037, 191, -844, 247, 130, -571, -548, - -496, 216, -161, 336, 62, 990, 130, 517, - -65, 0, 0, 0, 0, 0, -89, 9, - -138, 405, -701, -479, 3605, 699, -629, -102, - 27, -1374, -1059, -18, -2707, -172, -557, 0, - 0, 0, 0, 0, -67, 209, 571, -93, - -405, -172, -260, -19, 86, 22, 659, -630, - 222, -8192, 106, -34, 60, 0, 0, 0, - 0, 0, -10, -3386, 336, 651, -1377, 681, - -16, -45, -382, 1102, -280, 169, -822, 522, - 434, -1111, -299, 0, 0, 0, 0, 0, - 194, -445, -231, -532, -438, -180, -591, -1680, - 179, 5921, -184, -685, -467, 875, -573, 282, - 235, 0, 0, 0, 0, 0, 339, 139, - -745, -68, -201, 467, -743, 477, -23, -1177, - 1384, -357, -1254, -3760, 454, 1175, 252, 0, - 0, 0, 0, 0, 109, -252, 8027, -765, - 136, 111, -86, -593, -84, -750, -121, 782, - 739, -296, 284, 213, -1196, 0, 0, 0, - 0, 0, -40, 69, 1992, 452, -75, -84, - 683, 1678, -1350, -1846, 3068, -749, -1410, -271, - 536, 1120, 117, 0, 0, 0, 0, 0, - 4053, 340, 108, -88, 411, 990, 217, 3675, - 755, 752, -206, 205, -297, -573, 188, 127, - -313, 0, 0, 0, 0, 0, 47, -2870, - -3417, 216, 1730, -83, 189, -1615, 1016, -44, - -502, 2151, 6, -1057, 550, 194, -498, 0, - 0, 0, 0, 0, -133, 1, -387, -497, - 586, 173, 923, -4078, -1232, 329, -2086, -185, - 592, 681, 3320, -914, -327, 0, 0, 0, - 0, 0, -132, 493, -179, 220, 142, -4345, - 422, -173, 357, 1317, 240, -525, 1613, -178, - -1584, -734, 549, 0, 0, 0, 0, 0, - -337, 111, -1238, 116, 302, 325, 189, 610, - -3180, -284, -817, 1383, 1559, -802, 422, 438, - 460, 0, 0, 0, 0, 0, -96, 372, - 335, -843, 3967, 221, 380, 227, 309, 447, - -199, -257, 372, -397, -534, 736, -152, 0, - 0, 0, 0, 0, -144, 463, -54, -288, - -83, 115, -574, -229, 485, -2643, 58, 4312, - -1155, 642, -647, 1122, 118, 0, 0, 0, - 0, 0, 157, 6, -1017, -1155, 687, -288, - 918, -212, -332, -2486, -197, -1025, -546, 4099, - 155, -731, -333, 0, 0, 0, 0, 0, - -43, -496, -546, -541, 283, -521, -47, -18, - 208, -552, 1899, 2107, 588, 818, -911, -1104, - -84, 0, 0, 0, 0, 0, -71, 40, - -326, 92, 216, -106, -255, 28, 120, -58, - -2720, -133, -288, -28, -1157, 1563, 400, 0, - 0, 0, 0, 0, 40, -4, 559, 1350, - 30, 3905, -675, -1092, -587, -1524, -1987, -1031, - 1892, -679, -623, 1051, -33, 0, 0, 0, - 0, 0, -98, 106, 105, -5887, -463, 424, - -42, -506, -589, 376, 840, 140, -640, 771, - 23, -441, -6, 0, 0, 0, 0, 0, - 22, 203, -3452, -635, -605, 1668, 422, 2973, - 394, -1605, -968, -739, 344, -1438, 820, -1318, - -26, 0, 0, 0, 0, 0, 258, -32, - 1061, 643, -152, 92, -454, -1305, 1621, 554, - 344, 82, -404, 5222, -344, 286, 177, 0, - 0, 0, 0, 0, 63, -360, -127, 814, - 3639, -3322, 390, 12, -515, -493, 1515, 1706, - -727, 394, 1164, 357, -208, 0, 0, 0, - 0, 0, -27, 648, -342, -125, -327, 194, - -3639, 598, 29, 244, 898, -493, 372, -635, - 567, 31, -237, 0, 0, 0, 0, 0, - -160, 2798, -1768, -2186, 493, 517, -82, -468, - -290, 2890, -460, 450, 414, -265, -1121, 219, - -1115, 0, 0, 0, 0, 0, 14, 76, - -2806, 338, -1429, -402, 253, -130, -235, -799, - 309, -525, 3823, 175, 36, 113, 247, 0, - 0, 0, 0, 0, 352, 521, 213, -107, - -71, -762, 790, -856, -252, -246, -729, -631, - 1258, -3276, 1534, -436, -635, 0, 0, 0, - 0, 0, -54, 118, -453, -124, -32, 539, - 356, -169, -202, -590, 721, -444, -6260, -275, - -239, -105, -52, 0, 0, 0, 0, 0, - -464, 507, -796, 1273, 2297, 790, 652, 392, - 3364, -1949, 2154, -701, -229, 99, 88, 471, - -524, 0, 0, 0, 0, 0, 71, -914, - 1835, -156, -242, -196, 513, 431, -481, -84, - -734, 4501, -510, 115, 461, -428, 83, 0, - 0, 0, 0, 0, -3987, 1063, -717, -2640, - -963, -667, -147, 536, -68, 422, 341, -1916, - -616, 996, 522, 568, 1174, 0, 0, 0, - 0, 0, 8, 112, 693, 392, 445, 5309, - 259, 121, 1670, 343, 176, 472, 197, 419, - -240, -1178, -107, 0, 0, 0, 0, 0, -}; - -static const int16_t cb0808l0[] = { - 164, -3637, -3563, -243, -123, -47, -87, -32, - 62, 129, -2, 131, -36, -202, -197, 37, - -35, -442, -139, -69, -59, 29, -62, -67, - -17, -42, 74, 10, 107, 74, -109, 40, - -10210, -33, -3210, -410, -106, 512, 40, -17, - 109, 67, 99, 170, 53, 34, -68, -16, - 3895, -71, -116, 1, 608, 66, -215, 34, - 77, 50, -45, -73, 3, 11, -33, 18, - -34, 58, 25, 4420, 96, 77, -67, 23, - -83, -6724, 226, -32, -150, -154, 30, -12, - -8, -7, 89, 42, 173, -51, 38, -1852, - 40, -48, -40, 81, 34, 81, 66, 16, - 20, 3, 99, 41, 123, 52, 154, 20, - -38, 6, 10889, -44, 22, -39, 55, -34, - 25, -45, -22, 139, 19, -20, -64, -2242, - -473, -113, 316, 127, -31, 128, -363, -124, - 196, 259, -60, -3792, -41, -103, 104, -80, - -389, 179, 110, 83, 3174, 60, -197, 101, - 66, -47, -107, 96, -27, 45, -21, 6, - 116, -51, -8, -594, 377, -279, 158, -159, - 4595, -163, -210, 19, 3, -292, -67, 14, - 115, -41, -125, -154, -263, -101, 4, -11, - -89, 130, 58, 32, 92, 16, 126, -93, - -99, -4239, -69, 88, 5, -113, -18, 35, - 31, -48, -16, 35, 62, -2839, 14, 121, - 19, 41, 125, -102, 26, -13144, 6, -30, - -7, 60, 4, 36, -40, -26, 54, -57, - -9, -30, 13, -1, 73, -131, 29, 256, - 39, -51, -12, 1788, 4, 10, -58, 17, - -36, -2, 13, 59, -20, -21, 173, 129, - -435, -107, -214, 33, 3078, 13, 31, 148, - -2975, -311, 38, 25, -247, -542, 34, 106, - -392, 85, -203, 182, -232, 423, 629, -183, - 800, -466, 3145, -2498, -305, 39, 22, 41, - 0, -14, 671, -181, 3197, 109, 2900, 72, - -64, 8, 414, 133, 244, -263, 53, -69, - 70, -13756, -13, 21, 50, 12, -14, -12, - -7, 97, -32, 24, 51, -24, -29, 53, - 34, -19, -2341, 976, 25, -58, 18, -48, - -2490, -55, -31, -165, -36, 28, -26, 92, - 60, 137, 69, -5341, -125, 1966, -154, -66, - -13, -84, -13, 81, -46, -96, 50, -50, - -114, 15, 30, -211, -147, -555, 3998, 88, - 358, -159, -105, -51, -109, -16, 70, 91, - 268, 125, -95, -62, 38, -3227, 3591, -15, - 92, -72, 115, 144, -40, 142, 172, 72, - -17, 23, 1, 28, -38, -135, 220, -80, - -179, 9, -32, -6, 37, -33, -3, -89, - 7314, 5, 194, -13, 23, 31, 42, 84, - 197, -163, -251, -273, 193, 206, -613, 394, - 3469, 2587, -701, 62, 301, -104, 200, 164, - -201, -473, 52, -473, 128, -381, 404, -69, - -230, -537, 157, 389, -7, 2783, 3058, 95, - -59, 1618, 1, 4, 53, -6, 28, 10, - 2, 82, 28, -8, -14, 25, 59, 10, - -4, 36, -777, -4984, 29, 8, 85, -43, - -137, -34, 53, -58, 1, -27, 91, 15, - 80, -19, -186, 467, 94, -382, 129, 327, - 3053, -221, 399, -2821, 1090, 278, -2, -163, - -398, 126, -266, 180, -235, 70, -18, -34, - -45, 159, -32, 66, 11, 3177, -188, 27, - 35, -52, 114, -28, -136, 186, 2146, 100, - 92, 6, 58, -70, 159, -14, -32, 9, - 6, -27, -73, 28, 23, -24, 101, 148, - 80, -52, -27, -53, -36, 4, -74, 47, - -30, -108, 34, 7213, 12, 31, -17, -185, - 3318, 199, 192, 3450, -87, 3, 47, 46, - -141, 49, 83, -82, -132, -82, 68, 138, - -1031, -236, 390, -37, 23, -94, -7, 9, - -2958, -1846, -43, 23, 25, -79, -193, -77, - -3332, -3355, -139, 56, 163, -3302, -82, -25, - 35, 96, 73, 166, -154, 174, -121, 14, - -89, 101, -3751, -344, -240, -35, 401, -14, - 47, -49, 24, -78, 24, 6, 68, 51, - -145, 20, 83, 57, 147, -100, 60, 33, - -53, 11, 37, -5793, -93, -67, -9, 117, - 112, -51, 60, 48, 49, 328, 293, 127, - -314, -3022, 374, 3283, -86, 588, -346, 436, - -7, -26, -88, 104, 205, 150, 147, 34, - 126, 85, 46, -125, -119, 75, 13, 144, - 3721, 275, -71, 43, 163, -73, -292, -381, - -79, 33, 79, -79, 34, -94, 18, 229, - 63, 28, -44, 97, -3606, 77, -95, -162, - 163, 62, 6180, 81, -51, -19, -5, 109, - 71, 7, -37, -100, -31, -94, 188, 169, - -14, 2606, -417, 18, -4371, -25, 180, 108, - 17, 33, 48, -46, -93, -77, 32, -37, - -71, -271, -48, -273, -14, 115, -59, -312, - -3334, -3046, 71, -166, 379, 209, -142, 22, - 89, -41, -40, -7, -50, 8, -15, 12, - -70, -27, -27, 25, -31, 38, -5, 2831, - -89, -8, -50, -110, 1368, -59, -2307, 6, - 179, 75, 189, 170, -55, 330, -70, 172, - 67, -492, -57, -3408, 9, -93, -11400, 14, - -1, -21, 65, -15, 45, -22, 40, -10, - -41, 23, -29, -96, -55, -66, -57, -61, - -29, -15, -101, -9831, 33, 42, -35, 42, - -44, -58, 11, -40, 27, 21, 715, -315, - -255, -115, 1736, 4, 41, -70, -51, -108, - 160, -9, 87, -6, 36, -20, -68, 10, - 82, -33, -42, 15, -57, -40, -31, 21, - 10023, 62, -41, -10, 85, -65, -12, -61, - -72, -610, 128, -76, 198, 367, -4564, 60, - 158, -13, -134, -45, -33, -11, -51, -72, - 111, -188, 232, -494, -27, 42, 46, -23, - 137, 3174, -3598, 211, 152, 155, -299, 56, - -23, -123, 132, 50, 28, -64, 28, 9, - -17, 31, 112, -19, 4, 45, -7175, 54, - -61, -7, 87, 164, 195, -29, -48, 28, - -60, 70, -69, 112, -295, 5, -89, 38, - 36, -11501, 17, -26, -64, -222, 91, -23, - -89, 0, -94, 2191, -74, -84, -61, -41, - 57, 24, -35, -28, -37, 486, 131, 3699, - -277, 64, -125, -243, 270, 313, -112, 145, - 47, -2862, -254, -110, -27, -69, -342, -120, - 216, 35, 24, 62, -39, -29, 2402, -7, - -3, 14, -47, -27, 4, 27, 20, 81, - 138, 75, 178, 421, -2943, -3080, -84, -40, - -58, -195, -182, 101, -187, 6, -83, 269, - -32, -99, 51, -38, 44, 82, -14, -35, - 0, 8, -23, 10754, -73, -57, 68, 107, - 85, 77, 101, 1, -28, 103, -10, 48, - 55, 33, -93, -18, 8, 28, -14, -575, - 28, -11712, 90, -186, 58, 38, -42, 2156, - -82, 28, -23, 43, 43, 8, 25, 65, - 0, -53, 28, -88, 388, -36, 363, 64, - 3068, 56, 320, -202, -3433, 73, -339, -157, - 373, -216, -43, 171, 140, -437, -143, -2820, - -101, 53, -111, 65, -39, 65, -30, 69, - -55, 49, 45, 126, 174, 220, 73, -101, - -60, -151, -13, -41, -48, -9, 25, -122, - -80, -2450, 19, 94, 14, -18, -19, 60, - -3252, -10, 3390, -15, -365, -15, -73, -222, - 307, 70, -95, 237, -142, -163, -44, -138, - -7, 6, -36, -67, 9, -22, 10235, -56, - -8, 44, -155, -117, -22, -32, -74, -14, -}; - -static const int16_t cb0808l1[] = { - -58, 222, -154, -74, -53, 4939, 421, 67, - 26, 132, 60, -97, -1, -43, 328, 2, - 460, -66, -11, -45, -56, -86, -10569, -129, - 58, -25, 39, 28, 26, 45, -61, -139, - -22, -135, -282, -517, -368, 55, -47, 30, - -110, 47, 75, -13, 65, -41, 104, 4745, - -149, -99, 28, 421, 517, -56, 81, -309, - 67, -42, -6, 17, -60, -151, 50, -84, - -9, 29, -72, -3019, 82, -195, 41, -14, - -206, -34, -58, -18, 30, 2154, -20, 2, - -1, 41, -10, 7, 86, 494, 123, 328, - 73, 213, -29, 17, 43, -92, -61, -9, - -130, -113, 33, -28, -6677, -198, -185, -236, - 183, -108, 739, 60, 98, -314, 66, 10, - -3161, -159, -2850, 118, 37, -41, -119, 3087, - 43, -36, 42, 106, -174, -3379, -92, -142, - -237, 94, -59, -123, -117, 144, -75, 146, - -268, 561, -1160, 336, 1477, 207, 89, 130, - 127, 3763, -372, 48, 99, 204, 84, 209, - 103, 118, 125, 326, -29, -206, 139, -61, - 94, 77, 6624, -163, 23, 27, -104, 150, - -76, -205, -186, -30, -227, -58, 17, 25, - -6536, -19, -66, -45, -72, 41, 49, -79, - 105, -4, -117, -37, -183, 216, -27, -23, - -31, -2720, 53, -23, -46, -9, -10, 50, - -12, -50, -56, 35, 5498, -110, -2, 44, - -1, 13, 52, -18, -61, -80, -29, 25, - 61, -37, 93, -19, 67, 75, -41, 254, - 161, 118, -3379, 398, -9, -208, -143, 207, - -135, -32, 171, 187, -194, 466, -55, 158, - 34, 105, 4986, 27, -41, 20, 87, -110, - 39, 80, -37, 8, -25, -44, -108, -171, - -366, 208, -225, 1, -124, 21, 81, -10349, - -51, 33, -51, 141, -36, 106, -100, 320, - 122, 3, 266, 72, -8, -112, 55, -107, - -4154, -69, 0, 71, -153, -80, -50, 20, - -112, 225, -1982, 273, -19, -127, 109, -25, - 47, 57, -98, -10, 42, -25, 10, 24, - 41, -73, 45, -3523, -370, 3213, 54, -87, - 67, -185, 100, -33, -41, 3, -38, 70, - -108, -120, -67, -144, -181, -33, -104, 429, - 89, 849, 3022, -2765, -341, 184, -248, 610, - 408, -222, 184, 84, -64, 479, -146, 47, - -100, 13, 17, -7, 58, -13, -36, -23, - -1, -25, 10, 2666, -113, -41, -140, 3064, - 105, 31, 3042, -75, -132, -113, 80, -100, - -39, 216, -4, 7, -43, 242, 19, -1031, - 731, -3659, -24, -20, 109, 126, 2980, 19, - -11, -48, 57, -138, -11, -211, -151, 540, - -113, -110, 0, -415, 150, -80, -80, 209, - -82, -5212, -125, 376, 8, 131, -138, 30, - -922, -320, 181, -75, 138, -112, 146, -72, - 64, -75, -262, 4872, -11, -61, 37, -205, - 48, -2257, 82, 106, 93, -66, 48, 71, - 29, 72, 32, 29, 17, 5, 34, 29, - -29, -72, 50, -7702, -114, -117, 47, 11, - 19, 100, 48, -28, -8, 53, 21, 80, - -43, 37, 164, 22, -15, -5258, -23, -32, - 108, 52, 7, -161, 11, 84, 141, -8, - -12, -25, 111, 146, -96, 66, 7388, 54, - 17, -54, 62, 44, -66, -13, 26, 13, - 85, -79, -21, 98, 156, 181, -103, -188, - -35, -179, 83, 117, -92, 49, -185, 3800, - -90, 14, 42, 94, -83, -178, -156, -8, - 33, 42, 204, 42, 1, -85, 47, 10, - 10804, 36, 8, 26, -47, -51, -189, 83, - -47, -23, 104, -7142, -67, 55, 21, 68, - 8, -84, -60, -43, 142, -41, 27, -72, - -70, -170, -141, 202, -198, -105, 41, -3553, - -34, -148, 34, -62, -161, -20, -73, 128, - 162, -8343, 4, -71, -46, 12, 27, 48, - -41, 50, -19, -88, 7, 79, 29, -19, - -31, -49, -147, -1886, -103, -213, 28, -183, - 4119, 87, 6, -6, 51, -190, -167, -116, - 23, -26, 7, -38, 5442, -1869, -81, 197, - 105, -122, 65, 220, 32, -57, -39, -15, - 4, 112, -55, -139, -825, 985, -109, 2558, - 218, 94, 65, -184, 3269, 101, -65, 42, - 372, -38, 58, 8, -143, -544, -268, 121, - 38, 61, -63, -10, -30, -52, -76, -74, - -6690, -5, -160, 76, -77, 74, 374, -917, - 239, -203, 550, -84, -305, 292, -51, 36, - 135, -79, 27, -69, -309, 4561, -67, 11, - -60, 43, 18, -2, 8, -15, 20, 22, - -2, -41, -2396, 37, -79, 67, 27, -84, - 353, -213, -2336, 58, 39, 126, -78, -98, - -90, -3, -9, -43, -2, -29, -5, -149, - 42, 98, -109, 137, 58, -83, -38, 51, - 6525, 50, 97, -31, 8, 132, -71, -55, - 11, 120, 2, -43, 136, -37, -85, 150, - 133, 67, -41, -452, -104, 4, 126, 100, - -2660, -108, -109, -64, 615, -75, 45, 10, - -57, -57, -108, 167, -218, -10, -331, -26, - -21, 6561, 73, -599, 126, -23, 250, -103, - -4, -28, -20, -35, -19, 51, 9, -25, - -40, -11220, -2, 28, -12, 23, 3481, 169, - 159, -217, -48, 114, -93, -34, -191, -63, - 31, 182, 79, 90, 55, 67, -145, 409, - 190, -7791, -26, 18, 71, -113, -80, 69, - -21, -27, -121, 51, -148, 103, 196, 2726, - -67, 3022, -28, 26, -99, 51, 24, 61, - 104, 89, -57, -23, -112, 43, 6, 13, - -184, -168, 117, -29, 1865, -3, 20, 8, - 30, 32, -81, 80, -20, -59, 37, 19, - -107, -3920, -259, 44, 23, -129, 24, -66, - -27, -3071, 116, 9, -76, 56, -83, 25, - 54, -20, 2, 230, 56, -41, 131, -15, - -62, 61, 56, 74, -34, 110, 4606, -4, - 18, -47, 331, -106, -78, 70, 53, 70, - -22, 77, -71, -60, -101, 70, 7, 104, - -7, 39, -27, 7210, 253, -15, 0, -96, - 32, 50, -10, 33, 2058, 11, -15, 42, - -14, 51, 4, -3, -11, -86, 10, 33, - 21, -18, -31, -7, 53, -7, 95, 7, - 75, -11314, 7, 17, -16, -83, -475, -887, - -1141, 1, -101, 5, -46, 110, -90, -47, - -15, 19, 66, -4078, 104, 43, 105, -126, - 181, 43, -1655, -81, -11, 33, -33, 33, - 28, -44, 35, -6, -38, 68, -40, 67, - 73, -29, 171, 11982, 42, -8, -66, -66, - 40, -19, 14, 33, -63, 24, 94, -94, - -106, 584, 330, -108, -3841, 782, -300, -11, - -303, -174, -217, -3, 24, 168, 187, -166, - 54, 238, -269, -27, 182, -4, -72, -47, - 32, 39, 7622, -46, -67, -53, 56, 123, - -50, 69, -36, -275, 628, -55, 195, -56, - -265, -132, -39, -4, 169, 113, -180, -19, - 88, -6427, 42, -257, 1180, 359, 335, 3821, - 116, 79, 3, -93, 67, -44, 58, -16, - 265, 172, -39, -44, 18, 92, 4, 218, - 122, -2993, 150, 138, 618, 66, -618, 402, - 2227, 10, 38, 308, 338, -70, 265, 1047, - -104, -182, 305, -162, -99, 510, -20, -114, - 529, -42, -3569, 52, -80, -314, 716, -31, - 259, 59, -73, -117, 38, -44, -16, -74, - -5060, 35, 10, -30, 54, 217, 36, -205, -}; - -static const int16_t cb0808s0[] = { - -2191, -865, -1906, -251, 274, 594, -1214, 677, - 482, -1176, 43, -1098, -203, -537, 1834, 1332, - 308, 432, -191, 3091, 1892, 926, -446, -1206, - -613, 198, 575, -38, 264, 375, 278, -691, - -107, 17, -239, 261, 848, -620, 183, 624, - 122, -358, -50, 1017, -1075, -705, -346, 337, - -121, 100, -218, -1051, -463, -4728, -513, -1151, - 737, 4356, 684, -1374, 1630, 521, -520, -52, - 90, 119, -43, -131, 24, -2, -184, -65, - 614, 371, -448, -414, 1415, -687, -224, 584, - -768, -1210, 2941, -3057, 132, 406, -952, 291, - 295, -798, 608, -1476, -516, 21, -302, 2085, - -1700, -2655, -355, 175, -409, 662, 46, -247, - -201, -580, 179, -54, 458, 836, 1543, 1829, - -282, -278, 412, 2422, 2077, 197, -897, 451, - 595, 1547, 538, 825, 563, 443, -576, -854, - -572, 241, -471, 201, -311, -529, 112, -5128, - -173, -233, -435, 340, 158, -41, 273, -224, - 919, -1570, 1075, 265, -282, 1256, 1007, 231, - 720, 417, -401, -4589, -747, -453, -1112, 54, - 156, -561, 2746, -422, -83, -91, -381, -270, - -1226, 987, -965, 625, -474, 565, 2890, -85, - 1291, -280, 626, -26, 840, 1122, -1915, 780, - -702, 792, -578, -122, -9, 1175, -194, -571, - 2940, 540, 31, 1817, -352, 264, 953, -2035, - 238, 3250, -1561, 653, -331, -393, 827, -382, - 323, 281, -1339, -819, 545, 207, 14, 338, - 432, 860, 1691, 142, 711, 381, -1151, 4164, - -867, -241, 111, -513, -863, 78, 1453, -363, - -128, -232, -1853, 2373, -1156, 210, 698, 1134, - -869, -177, -352, 1514, -1370, -789, -1193, 819, - 348, 80, 492, 179, -909, 591, -600, -377, - -1709, 59, -539, 557, -45, -362, 778, -4919, - -647, 203, 865, -313, -257, 173, -2415, 1005, - -1771, 843, -474, 1619, 1193, -186, 305, 636, - -662, 1976, 546, -82, -108, -751, 850, 521, - -1625, -3135, -388, 64, 249, -1189, -1552, 2629, - 2, -221, -105, 754, 251, 219, -270, -202, - 545, 147, 1019, 108, -1358, -1317, 1362, -1323, - -3322, -405, -371, -554, -334, 296, 493, 248, - -4, 1340, 123, -584, -804, -766, -164, -470, - 295, 218, -3, 62, -194, -657, 5016, 280, - -4, -69, -281, -994, 209, 307, 8648, -37, - -138, 45, -329, -101, -65, 98, 58, 714, - 56, -170, 60, -203, -248, 103, 107, -408, - 596, 170, 61, 584, 727, -434, -181, -5116, - -502, 494, 52, 83, -105, 325, 68, -561, - -274, 371, -1833, -78, -2990, 320, 141, -748, - 1764, 1157, -538, -276, -1594, -152, 838, -45, - 1137, 13, -803, -162, -838, -1199, 2003, 580, - 3687, -844, -552, -271, -462, -1034, -29, 273, - 862, 269, 95, 186, -222, -124, 79, -34, - -684, 808, -1061, -916, 610, 539, 1289, 782, - 1216, 3213, -38, -546, -1209, -398, 98, -39, - 58, -1271, -611, 573, 499, -2170, -157, -943, - -595, 436, 1203, 487, -1419, -570, 1468, 711, - -589, -101, 3299, -45, -1432, -453, 1820, 677, - 1052, -1793, 1071, -400, 268, -464, 443, 508, - -273, -736, -233, 270, -1187, -1931, -1208, -519, - -879, 325, 1032, 280, 565, 294, 2588, -303, - 640, -1398, 1070, 674, 57, -165, -46, 512, - 757, -3471, -812, -854, 45, 101, 3195, -786, - -61, 122, -1234, -74, 119, -389, 254, -84, - 829, 1465, -930, 171, -248, 201, 939, 1, - 52, -3517, -1854, 147, -843, 310, 502, 729, - 191, 525, 333, -669, -3358, 215, 552, 156, - -1771, 982, -746, 523, -187, -684, 456, 123, - -1544, -145, 58, -1083, -1646, -1309, 775, 1436, - 1409, -1114, -171, 26, -1775, 1103, -392, -2053, - -1221, 100, -1120, 25, -295, 306, -105, -514, - -4362, 156, -2172, -191, -90, 7, -62, 244, - -107, 521, 309, 22, -663, 239, -213, -226, - 100, 2228, -330, -197, -1247, -876, 1561, -1, - -354, 439, -163, -318, -61, -1184, -3022, 1434, - 65, 87, 806, -2093, 3016, 1022, -779, -391, - -18, -1371, -548, 910, -910, -438, 673, 48, - 1028, 548, 153, -337, 554, 353, 1686, 468, - -190, -113, -560, 542, 94, -140, -194, -58, - 165, -154, -311, 4744, -148, 49, -253, 180, - -65, -125, -139, -49, -115, -270, 439, 139, - 210, 202, -207, -65, -477, 168, -4720, -96, - -1091, -2071, -567, -1330, 237, 411, -123, 1197, - 2625, 1348, -230, 362, -147, -139, -699, 1210, - -299, 92, 2835, -36, -296, 287, 2426, -1171, - -218, 884, -320, 1130, -1085, 1177, -953, -776, - 609, 827, -90, 131, -2757, 567, 885, -2359, - 955, -200, -1883, 131, 282, -80, 141, -8, - -33, 333, 809, 357, -13, 499, 597, 923, - -1725, -1533, 465, -93, 2187, -841, 751, 74, - -2158, 99, -1078, -459, 648, -258, 349, -917, - 1200, 374, -1741, -1013, 724, -61, 182, 4032, - -581, 1123, -400, -459, -443, -316, 3, -271, - -248, -17, 595, 206, -1188, 2869, 1338, -253, - 316, -474, 1680, -856, -1487, 547, 679, 425, - -258, 92, -4, -24, 117, -157, 385, -257, - -332, -5597, -68, -329, -65, -108, -277, 202, - -400, 124, -51, 5, 71, 90, -927, 966, - 780, 305, 703, 802, -1661, -1415, -66, 437, - -610, 317, 795, 599, -189, 322, -519, -4010, - 729, -620, -2127, 351, 506, -68, 162, -983, - -288, 3167, -140, 991, -599, 128, 1868, 64, - -63, -1, 2047, 155, -871, -130, 226, 508, - 499, 882, 3762, -383, -23, 0, -345, -488, - 167, 648, 395, 114, 1121, 343, 232, -538, - 15, 342, -820, 38, 435, -468, -282, -415, - -5021, -293, 147, 533, -128, -70, 503, 844, - -86, 1836, -2103, -1143, -70, -510, 576, -689, - 410, -2101, 433, 339, -417, 820, 157, 173, - 454, -586, 1219, -73, -5123, 344, 397, 53, - 105, 501, -59, 515, 194, 356, 78, 706, - 303, 332, 4532, 739, 961, -521, -392, 20, - -697, 823, 607, -243, 332, 365, -330, 307, - 429, -865, -8, 545, -3, 6041, -310, 272, - 464, 22, -156, 142, -63, -87, 297, -24, - 562, -9, 147, 341, -21, 119, 1386, 947, - -1738, -500, -655, 95, 32, 32, 187, 518, - 1330, 95, -324, 3620, 737, -54, 55, 670, - -1252, 995, 484, 1347, -745, 244, 262, -83, - -122, 1194, -653, -1111, -327, -325, 3579, -214, - -37, -412, -267, -377, -62, 131, 360, 203, - -5713, -42, 94, 279, 406, -355, 34, -144, - 156, -256, -48, -98, -1392, 1273, 202, -1249, - -3457, -710, 1007, 37, -1788, 86, -570, 535, - 17, -369, 1640, 816, -117, 128, -969, -1381, - 224, 1519, -996, -833, 931, 185, 804, 465, - 82, 69, -247, 3312, -430, -23, 173, -223, - 3080, 1848, -1187, -1494, -485, -1131, 496, -517, - -596, 320, -853, -1303, 240, -298, 159, 527, - -257, 412, 839, -1020, 706, -3499, -175, -1089, - -717, -325, 261, 310, -1740, -1035, -403, -229, - -861, -970, -62, -192, 535, -2154, -364, -1133, - 979, -3299, 353, 982, -517, 1144, -563, 675, - 285, 63, 17, -1957, 82, 28, -513, 501, - -1183, 1476, -813, -254, -1584, -1181, -426, -56, - -916, 203, -2693, 209, -1066, -1174, 279, 439, - 201, 1179, 797, 407, 851, 927, 316, -640, - 1398, -128, 2741, 563, -1789, 989, 932, 247, - 6, -617, 268, -691, 1112, -569, 883, 298, - 37, -362, -661, -17, -154, -574, 721, 4578, - 205, 507, 77, -90, -433, -1613, 270, -500, - -1061, 1634, -388, -432, -648, -1985, 629, 2887, - -201, -32, 223, 621, 143, 446, 1384, 1109, - 299, 329, -1002, -356, 1504, -77, 49, 952, - 4166, -544, -85, -412, -249, 474, 27, -107, -}; - -static const int16_t cb0808s1[] = { - 2632, 1511, 944, -180, -2377, 54, -470, -187, - -710, -998, -516, -916, -440, -842, 285, 22, - -282, -459, -299, -2769, -2285, -380, -2194, 801, - -595, -252, 504, -69, -752, 972, 639, 277, - 502, 117, -1072, -145, 1462, -528, 2165, 880, - -182, -2953, 750, -1090, 596, 105, 187, 555, - -153, -113, 830, 161, 308, -44, -250, -58, - -507, -406, -626, 1453, 1357, 116, -456, 3242, - -607, 94, 390, 393, 114, 1069, -2, 2, - 2497, 1405, -755, 1353, 192, 1288, -187, 262, - 1722, 91, 885, -622, -321, 246, -1835, 17, - 213, -80, -658, -1940, 275, 845, -365, 276, - 2142, -216, -3402, -646, 549, -78, -176, -52, - 785, -1335, 44, 163, -409, 1273, 679, -377, - 788, -1355, -1721, 332, 223, 1409, -104, 165, - 354, 322, 2414, -1611, 216, -6, -232, -1770, - -1931, 2496, -530, 228, -924, -173, -329, -575, - -1709, -900, 199, 223, 690, -636, 73, -367, - 460, -823, -5105, 435, 957, 224, 246, 406, - -673, 752, 412, -158, -267, 4, 694, 10, - -45, 219, 1040, 778, -1910, 1886, -691, 674, - 1085, -537, 376, 1048, 858, -161, 613, 376, - 535, -1349, -1913, -518, -850, 665, 772, -2985, - -66, -42, 2142, -848, -1151, 237, -211, -161, - -2753, 603, 507, 39, -575, -61, -1053, -273, - 290, -258, -162, 139, 95, -12, -201, -236, - 709, -328, -314, -130, -5337, 100, -18, -97, - -206, 1827, 1722, 302, 924, -203, 761, -715, - -24, 372, -600, 2115, 1197, -1406, 676, -2068, - -167, -221, -936, 1419, 353, -317, 245, -2890, - 623, 265, -622, 204, 2549, 596, 239, -25, - -672, 583, 117, -13, -2251, -1325, 1984, 1431, - -1335, -1268, 735, 245, 105, 593, -193, -614, - 909, -339, -1033, 383, 102, 363, 732, 1439, - 1028, 1275, 442, 987, -3901, -257, -36, 224, - -116, -402, 200, -596, -125, 372, -572, 398, - -543, 1024, 1746, -736, -1056, -1736, 953, 1026, - -965, 442, -1565, -448, -96, 1498, 30, -231, - -483, 73, -3185, 1765, 1313, -100, 477, -198, - 782, 316, 364, -107, -431, -1795, -244, 122, - -423, -385, 457, -872, -535, -1098, 80, -110, - 1420, 646, 33, -3226, 648, 861, 328, -1269, - -558, 495, 881, 112, 479, 170, -309, 1904, - -1412, -768, -1220, -34, 995, -649, 162, 1, - 153, 985, 762, -263, -188, 77, 760, -2346, - 3430, -450, 1677, 1090, 1771, 2109, -14, -119, - -995, 268, 141, 33, 35, 31, 537, 65, - -345, 69, 192, 763, -18, 1078, 3829, 274, - 442, -173, -412, 434, -695, 924, 2, 1551, - 566, -85, 217, 976, 2196, -503, -1401, 759, - 922, -3024, -963, -3, 600, -452, -193, -787, - 7, 186, 828, 515, 148, -225, -1250, -985, - 443, -511, 2037, 1560, 3230, 647, 1418, -165, - -261, -369, 224, 450, -100, -271, -122, -511, - -691, -1444, 906, -144, 248, 452, 957, -70, - -517, 116, -3559, -877, -399, 418, -1300, -415, - -177, 770, -2566, -371, -1673, -1042, -500, -290, - -708, -631, 193, 2494, 319, 545, 767, 102, - 231, -43, -139, -97, -700, -1592, 282, 1325, - -1419, -647, 449, 1995, -737, 661, 1617, 725, - -1464, 615, 906, 202, -154, -228, -2194, -231, - 299, 110, 1318, 1053, -312, 843, -937, -1697, - -592, -1224, -633, -50, 792, 1600, -1187, -171, - 211, -744, -306, 186, 1914, -3119, -904, -159, - 178, -596, -654, 817, 94, -242, -2376, -218, - -421, -365, -699, 177, -427, -32, 265, -33, - 245, -34, 5309, -307, -262, -299, 86, 278, - 33, -200, -180, -56, 337, 1034, -229, 4952, - 306, -609, 189, -22, 280, -160, -507, 135, - -1265, -252, 434, -427, 158, -546, -130, -2500, - 597, 908, 918, 706, 1227, 3390, 995, 298, - -558, 1307, 765, -144, -37, -286, 122, 215, - -1251, 1090, 85, -914, 522, 316, 1829, -701, - -365, -3311, 312, 22, 680, -1351, 220, 243, - 166, -36, 780, 2395, -64, 836, 1037, 735, - 966, 173, 1114, 192, 510, -1054, 1341, -616, - 1559, 897, 338, -3, -194, -214, -573, -265, - 328, -365, 433, -505, -86, 33, -156, -129, - -137, 119, 143, 5773, -76, 68, 820, 1215, - 1315, 713, 12, 1590, 131, -193, -881, -227, - 736, 581, 736, -37, -434, -449, -348, 4189, - 2180, -1360, -1663, -74, 1215, 278, 2092, -66, - 313, 388, -1373, 25, 599, 888, -87, 293, - 30, 367, 1010, -883, 818, -910, -1918, 864, - 482, -968, -1249, 222, 1100, 23, -87, 2493, - -248, -622, 240, 151, 873, -2735, 1325, -700, - -411, 282, -2361, -1843, -631, -208, 103, -411, - 831, -446, -292, 450, 184, -158, 484, -1964, - 4663, 123, 18, 174, 621, 158, -788, 233, - 302, 441, -339, 200, -62, -197, -9, -236, - 984, 584, -521, -373, -205, 910, 392, 850, - -2968, 68, -727, 1330, 578, 36, -385, 754, - -538, -36, 271, 418, -548, 1775, -1045, -879, - -1407, 524, -1085, -1479, 371, 19, 873, 171, - 2932, -216, 42, 71, -1187, -570, -524, 344, - -770, -4086, -735, -515, 1055, -551, 945, -1408, - 913, -1005, -222, -443, 60, -194, -734, 1908, - -534, -1351, 72, -938, -66, -2756, 1313, -169, - -1550, 450, -610, 893, 1100, -583, 87, -145, - -210, 281, 1402, 674, 0, -38, 874, -363, - 2436, 2156, -1659, -481, -130, -63, -669, -316, - -761, -413, 108, 2362, 354, 76, -1725, -924, - -1443, 1251, 871, -2058, 518, 955, -283, 680, - -85, -560, -464, 127, -216, -1382, 1908, 238, - -182, 459, -1227, 1144, 2266, -96, 595, -750, - 912, -198, 1786, -1423, -618, -450, 185, -1212, - 706, -689, -154, -365, -681, -1378, 914, -1200, - -253, -532, 3244, 444, 1, -96, -404, -64, - -412, -1400, -2830, -785, 940, -217, 358, 618, - 208, -2974, -365, -32, -63, -233, -868, -413, - 358, -451, 1310, -751, -1329, -2480, 63, 458, - -273, 1270, 316, 93, -453, -463, -1258, -57, - -1073, -2037, 46, -160, 4609, -1193, 192, -355, - -963, -92, 752, 593, 102, -80, -121, 166, - -606, -274, 28, 258, 45, -45, 928, -949, - -134, -268, -77, 242, 1623, -1290, 739, 109, - 285, 175, -92, -4053, -482, 366, 217, -126, - -843, 950, -1068, 777, 1818, 550, -891, -34, - -995, 1976, 2677, -764, 45, -40, -1800, 569, - -323, -102, -1064, 4000, -109, -423, -289, 738, - -872, 808, -977, 504, -901, 41, -45, -287, - -140, -444, 477, -271, -876, 301, -2421, 1633, - -918, -660, -149, -2542, -503, -265, -107, -623, - -447, -782, -858, -535, -220, 442, 661, -209, - 878, -1601, 3610, 149, -331, 190, 102, 270, - 1451, 237, 13, -1026, 178, 1290, -281, -217, - 11, -1728, 1043, -2992, -718, -776, 357, -615, - -231, 813, -473, 1634, 539, -513, 240, 1158, - 144, 57, 1249, 1479, -481, -733, 1663, -757, - 641, 680, -468, -2697, -29, -62, 1253, 1142, - 292, 245, -96, 295, -664, -264, -308, -670, - -705, 155, -4024, 330, 191, -77, -1502, 326, - 9, 295, -567, 34, -104, -123, -320, -255, - 1124, 320, 98, 1299, -436, 1491, -341, 908, - 11, 8, 988, -1921, 5, -1391, 859, -1291, - -581, 546, -95, 272, -441, 185, -256, 313, - 466, -393, -50, 4430, -940, 87, -224, 390, - -539, -290, -1046, 531, -2329, 1275, -586, -1046, - -1682, 1159, 908, 2023, 951, -273, -68, 713, - -556, 770, 783, 223, 60, -881, -97, 760, - 556, -237, -263, -246, -240, 165, 526, 832, - -4761, 432, -339, 186, 492, 81, -136, -827, - -390, -1026, -371, -292, 937, -243, -136, 6, - 49, -223, -600, -355, 5306, 140, 34, -84, -}; - -static const int16_t cb0808m0[] = { - -3555, -106, -131, -53, -156, 196, -206, -104, - 18, -2948, 122, 146, -520, 2, 294, -419, - -1, -25, -257, 9334, 87, -55, -42, 30, - 92, 35, 195, 31, 59, 88, 47, 47, - -220, 564, -1686, 426, 106, 396, 97, 1315, - 2331, 167, -1261, 1003, 732, -300, -342, 418, - 87, 236, -245, 2235, 11, 725, -24, -169, - -480, 2845, 96, -34, 67, 857, 28, 50, - 92, 2100, -84, -600, -1990, -2208, -163, 299, - 431, -825, -283, 299, -98, 391, -65, -92, - -200, -689, 2236, -82, -81, -52, 127, 86, - -137, -319, -2561, -90, 547, -198, 10, 195, - -366, -2688, -77, -234, -112, -245, 270, 199, - 2674, -57, -673, -9, 1029, -31, 311, -50, - -160, -175, 2371, 2711, 409, -19, 22, -244, - 312, -158, 270, -125, -247, 118, -91, -602, - 86, 174, -216, 18, 3048, -1953, 171, -1985, - -297, 295, -38, -198, -229, 363, -13, 127, - 13, -202, -117, 65, 74, 63, 125, -62, - -2, -543, -680, -4269, -130, 325, -49, -245, - -50, -509, -151, -19, 3, 152, -980, -129, - -234, 399, 349, 171, -196, 4952, -2, 36, - 288, 771, 2313, 231, -39, 572, -3012, 77, - -501, -215, -228, -444, 830, 200, -188, -157, - 3248, 279, -3319, 0, 76, 10, 160, -80, - 135, 102, -349, 174, -30, -88, -145, -205, - 10, -185, 177, -34, 25, 31, 218, -4, - 191, 172, 228, -136, -178, 268, 638, 3559, - 55, 198, 145, 342, -25, -1940, 2866, -334, - -921, 1941, -464, 273, -181, -506, -21, -410, - 116, -179, -49, -273, -22, -36, -1298, 274, - -1831, 321, -382, 238, -3464, -68, -194, 32, - -95, -506, 72, 64, -329, 19, -39, 347, - -302, 204, 145, -72, 855, -112, -3596, 989, - -2801, 386, -2623, -471, 101, -155, 257, 291, - 30, -153, 185, 172, 511, 20, 166, 274, - 29, -3023, 129, 33, -219, -205, 6, 47, - -407, 137, 563, -106, -2065, 76, 201, -99, - -170, -77, 170, -4536, -440, -96, -940, -1066, - 81, 205, 358, 435, -78, -148, -201, -85, - -307, -306, 14, -47, -101, -187, -136, 380, - -4, -32, -34, -54, 528, -58, 6389, 302, - -79, 52, -28, -65, -77, -12, 9024, -100, - 262, 20, -67, -31, 50, -33, -30, -140, - 326, -1170, -304, -136, -233, 170, 60, 314, - -166, -208, -105, -245, -169, -72, 137, -7173, - -2, 375, 152, 226, -206, -341, 303, 47, - 1010, -188, 577, -292, -3581, -12, -195, 20, - 2165, -206, -88, -83, -132, -40, -443, 236, - -333, 179, -211, -56, 318, -409, 3106, 95, - 11636, 340, 204, -323, 167, 76, 61, 65, - -157, 71, -21, 38, 66, 391, -52, 20, - -17, 11, 259, 45, -194, 440, 3432, 122, - 468, -595, -1856, 94, -427, -133, 149, -273, - 61, -6622, 48, 97, -162, 93, 402, -104, - -207, 64, -278, 92, 387, 3, 96, -2, - -27, -30, 84, 64, 35, -65, 98, 85, - -16, -248, 7930, 74, 4, -104, 83, -48, - 40, -2104, -86, -89, 99, -142, 65, -2713, - 63, -431, 523, 687, 212, -1515, 3, 59, - 55, -6, 22, -8, -148, 180, 78, 7833, - -63, -83, 13, -187, -116, 156, -29, -186, - -160, 148, -82, -303, -166, 112, -103, -39, - -165, 2827, -54, -26, 24, -3055, 78, 21, - 128, -81, -25, -122, 51, -54, -19, 188, - -18, -1, -140, -18, -8085, 124, -46, 45, - -574, 12, -150, 147, 65, -209, -396, -444, - -3882, -291, -231, 296, 244, 76, 180, 36, - -2575, 659, -63, 3277, -85, 48, -518, -353, - 130, 50, 13, 338, -343, -276, -16, 353, - -6036, -77, 18, 139, 43, 335, 294, 99, - 219, 442, -25, -53, 40, 271, 175, -282, - -91, 430, -4428, -15, -2857, -62, -27, -170, - 33, -681, -110, -76, 153, 42, -134, -145, - 222, -177, -39, 314, 2270, 526, 500, 2417, - 339, 1808, -17, 464, -525, -97, 124, -32, - 370, 48, -1675, -62, -169, 2642, 2511, -43, - -1037, -184, 54, -569, -504, -247, -40, 327, - 7, 82, -197, 2774, -34, -2931, -204, -112, - 194, -362, 187, 65, -166, 115, -125, 14, - 210, 144, -75, 57, -255, -151, -3566, -153, - 182, 89, -2530, 98, -265, -173, -133, 260, - -25, -1292, 35, 131, -98, -85, -237, 82, - 1353, 47, 3842, 148, 171, 183, 234, 89, - -93, 47, 102, -4, 90, 2980, 289, -231, - 353, 497, -109, 190, -2869, 697, 136, 90, - -244, 298, -119, -519, -50, 207, -43, -1376, - 356, 1934, 701, -2323, 671, 71, -56, -167, - -3793, -3749, -103, 134, -228, -13, 27, -45, - -105, 172, -77, -23, 53, 110, -118, -80, - -164, -192, -563, 393, -58, -428, -360, 3696, - 162, -173, 1683, -430, 452, -92, 107, -41, - 28, -85, 421, -66, 354, -88, 723, 2751, - -2955, -481, -134, -231, -145, 3, 65, -88, - 189, 187, 151, 174, -36, 240, -253, -235, - -194, -5410, -47, -98, 338, -487, -81, -35, - -82, -440, 31, 109, 217, 276, -1805, 278, - 273, -369, 629, -293, -525, -3832, 73, -56, - -363, 1709, 177, -2813, 796, -162, -341, 1176, - -75, 533, 854, 719, 242, -194, 90, -147, - 203, -136, -138, -764, 6, -2787, -13, 1104, - 1497, 1097, 90, -867, -718, -317, 119, 180, - 160, 257, 2532, -557, -62, 14, 665, 1520, - 456, 826, 394, -605, 908, 222, -140, 121, - 121, 232, 124, 96, -87, 48, -51, 41, - -7821, -37, 130, -11, -33, -137, 16, 42, - 1509, -8, 119, -83, -18, 64, 41, -178, - -28, 182, 532, 678, -75, 277, -230, -70, - -71, -8, -150, 321, -6298, -20, -131, -65, - 139, -215, -155, -27, -110, -257, 32, 201, - 215, 184, 8932, -106, -50, 66, 15, -44, - 203, -38, 19, -78, 65, 135, -123, 166, - 117, 76, 4, 34, -90, 5984, 59, -72, - 356, -64, 6, -62, 43, -86, -175, -106, - 10, 25, 3812, -135, -3313, 142, 348, -101, - -35, 378, -250, -106, -299, 237, 40, -32, - 236, -521, 63, -143, 538, -256, 43, -45, - 1642, 726, -3225, 109, -997, 3, -256, -27, - -182, -78, -4092, -9, 231, 34, 9, -6, - 155, 2842, 53, -130, -390, -146, 168, -74, - -2023, -955, 576, -629, -76, 70, 140, -287, - -401, 966, 359, 1185, -226, 713, 753, -739, - -4238, 3364, 75, -213, 27, -172, -34, 171, - -118, -46, -164, -13, -54, -203, -154, -12, - 65, -3777, -3452, 297, -104, -93, -81, 69, - -179, -321, 51, 47, 242, -15, -144, -43, - 2827, 67, -305, 54, -3044, 57, -15, -427, - 311, -205, 226, -490, 37, 363, -88, -408, -}; - -static const int16_t cb0808m1[] = { - 3329, 59, 195, -91, -70, 3262, -132, 360, - 157, -410, 184, -99, -138, 337, 289, 317, - 156, -589, -127, -204, 37, -175, -5661, -52, - 942, 156, -1, -197, 353, 90, 57, -287, - -218, 438, -4, -262, 9, 322, -167, 2904, - -12, -2647, -248, -203, -267, -116, -135, 333, - -220, -200, 40, 228, 2677, -462, -183, -129, - 2898, -728, 793, 422, 541, -350, 28, 222, - 2790, -231, -195, -191, 3002, 182, -610, 145, - -226, -102, 285, 344, -357, 217, -146, -98, - 18, -255, 96, -151, 266, 208, -459, -132, - -345, 4059, -371, 79, 44, -63, -233, 334, - 44, 3884, 49, -3303, 88, -23, -287, -461, - 57, 94, -53, -129, 104, 167, -25, -79, - -125, -630, -2352, 150, -419, 40, -63, 603, - 67, 209, 321, -1765, -200, 68, 473, 622, - 5, -2883, 112, 188, -189, -2765, 169, 397, - -330, -642, -798, 129, -110, -164, -20, 176, - -213, -5415, 39, 31, 13, 270, -477, 166, - 167, 4, 216, -12, -528, -75, -291, 396, - -499, -2011, -172, -265, 96, 83, -279, 114, - -166, 833, 30, 2493, 94, 130, -183, -659, - 1, -227, 75, 349, -2757, 82, -116, 9, - 952, -112, -2444, -333, -206, -406, 201, 15, - -768, 88, 1390, -33, -558, 97, -201, 29, - 3470, 50, -40, -271, -171, -26, 47, 485, - -250, 3318, 112, 639, -2911, 123, -264, 3, - 8, 379, 73, 54, 88, 227, 73, 58, - -572, 782, -183, 305, 49, -23, -2968, -41, - 291, -25, 157, 295, -2118, 125, 5, -193, - -159, -543, -75, 1181, -191, -547, -93, 117, - -1831, 265, -607, -30, 194, -3929, -70, 159, - 79, -1519, 38, 201, 14, -24, -76, -366, - 14, -2748, 0, -372, 405, 39, -170, 320, - -257, 2153, -12, 158, 322, -4013, 22, -101, - 217, 637, 273, -430, 228, -428, 102, -356, - -266, 82, -31, 14, -223, -2595, -360, 2094, - -379, 624, -192, 245, 294, 1484, -117, 156, - -53, 3668, -3573, -118, -213, 257, -211, 66, - -62, -173, -166, -123, 163, -81, -39, -74, - -21, 126, 722, -136, 2050, -206, 86, 275, - 76, -249, 55, -2508, 95, -60, -34, -360, - -9, 187, 34, -87, -30, 137, 48, 4761, - 109, 511, -496, 104, 399, -361, 162, 78, - -29, 159, -112, 182, 246, 52, 255, 338, - -35, -1, -68, 5, 182, 7675, -119, -14, - -1901, -111, -106, 22, -16, 81, 159, -2423, - -71, -24, -153, -520, 126, 370, -186, 230, - -51, -401, 206, -32, 52, -71, -79, 503, - -239, -231, 55, -133, 5226, -45, -165, 57, - 2314, -209, 302, 78, 154, -3092, -605, -498, - 410, 159, 336, -147, -120, 143, 36, 587, - -182, -182, 1457, 1008, 2524, -446, 2333, -497, - -761, -162, 125, 420, 225, -117, -324, 437, - -50, 190, 129, 259, 33, -2, -9, 32, - -24, 91, 97, 201, 19, 169, 3535, 485, - -144, 330, -193, -2715, 603, 303, 1124, 107, - -1386, -1437, -203, 180, -81, 303, 209, -21, - -65, 26, 91, 98, -1349, 196, 2103, 917, - -732, 834, 1456, -92, -455, -130, -732, -288, - 39, -85, -557, -39, 3213, 297, 392, -378, - -520, 795, -2407, 6, 7, 406, 203, -73, - -247, 317, -3336, 3166, 206, -36, 159, -279, - 442, 54, -324, -18, 544, -250, 142, -440, - 100, -145, -3772, -199, 139, -156, -11, 34, - -178, -233, -370, 601, -58, 1679, -170, 76, - 684, -35, -73, -52, -33, -3, -89, -5, - -82, 73, -11, 51, -48, -12, -376, 4348, - -203, -432, 189, -35, 144, 31, 181, -106, - -5112, 552, 480, 0, 63, 31, 33, 504, - 1055, -3007, -214, 154, -100, 246, 269, -423, - 579, 63, 1668, -296, 390, 109, 21, -6, - 71, 3321, 246, 197, 355, -198, 472, 135, - 437, -1734, 1299, 227, -618, -48, -199, 217, - -230, 70, 99, 2632, -203, 3105, -87, 149, - 303, 124, 362, -322, -44, 38, 104, -28, - 48, -175, -468, -410, -4451, -152, 2157, 26, - -281, -581, 36, -205, 101, 230, 192, -129, - 319, 20, 65, 4879, 123, -236, -178, -128, - -387, -124, 528, 142, -775, -301, -88, -380, - 120, -42, -17, 64, -1074, -3350, 1335, -1078, - -14, -462, -113, 253, 450, 36, -8, -346, - -54, -7, 52, -100, 74, 8266, -193, -36, - -51, 12, 59, -68, 190, -36, 89, 38, - -59, 13, 269, 109, -15, -141, -64, -60, - 238, 6, -4338, 381, 1252, 354, -41, 41, - 191, -236, 122, -2712, 352, -117, -121, -284, - 1516, 473, -332, -277, -1792, -335, 84, 64, - 9595, -246, -278, 446, -95, -32, 60, -146, - 104, -84, -3, 107, -116, -377, 101, -149, - -45, 364, 104, -193, -254, 2929, -164, -93, - 324, 749, -928, 435, 2357, 350, -40, -153, - -48, -626, 390, -48, -4248, -458, -930, -218, - -486, 1769, 335, 152, 165, 111, 118, -407, - -87, -373, -333, -134, 86, -32, -144, -18, - -16, -7549, -146, 49, -184, 116, -28, -51, - 190, 115, 80, 68, 129, 206, 294, 331, - 179, -270, 174, 2444, 55, -3271, 70, -124, - 228, 330, -21, -419, 62, -140, -2388, 7, - -2683, -129, -1050, -548, 811, 189, 359, -385, - -82, 9031, 95, 77, -69, 164, 261, 61, - -73, 230, -163, 141, -38, -43, -150, 164, - 28, 164, 59, -58, -312, -134, 102, -67, - 166, -163, 63, -6795, -103, -147, 81, 273, - 133, 122, -162, -207, 127, -60, 4628, -1, - 1315, 518, -163, -246, 54, 239, 154, -154, - 265, 2000, 25, 227, 42, 179, 88, -3446, - -214, 182, 438, 90, 196, -69, 134, -56, - -451, 716, -1120, -287, 118, 230, -37, 145, - 284, -250, 139, -947, 203, -3176, -57, 151, - 3201, 818, -87, 347, -486, -201, 1176, -325, - -966, -263, -184, 238, -156, -396, 152, 959, - -59, -33, -159, -3, 9394, -119, -81, -50, - 67, 9, 27, -62, -121, -210, 48, -211, - 5, 396, 633, 34, -16, 67, -247, -77, - 128, 441, 3896, 251, 970, 119, -387, -35, - 124, -64, -664, -6550, 101, -52, 19, 44, - -132, 79, 731, -155, -262, -140, -31, -191, - -110, 276, -162, -49, 81, -117, 15, -570, - 420, -1232, -125, 3737, -95, 544, -149, 463, - -129, -345, 350, 183, 173, 197, 464, 180, - -249, -365, -785, -9, -3411, -235, -124, 225, - -4516, 196, -150, -89, -89, 54, -110, 137, - -431, 272, -12, -7, 114, -201, 166, 1570, - -74, -88, 6019, 350, -75, 68, -29, -81, - -50, 57, -62, 103, 61, 276, 22, -131, - -134, -3347, -60, -3397, -311, -105, 90, -159, - -222, 151, 224, -210, 264, 192, 29, -84, -}; - -static const int16_t cb0808sl0[] = { - 24, -3148, -3111, 106, 45, -114, -85, -211, - 154, 172, 246, 368, -130, 58, -135, 70, - 102, -150, -76, -7, 13, -1, -29, 20, - -7, 112, -234, -115, -138, -40, 106, 178, - -7276, -537, 25, 856, 460, 3107, 146, -520, - -631, -118, 393, 179, 144, -86, 47, 82, - 3031, 28, 164, -308, -411, 72, 138, 378, - 242, 253, 12, 158, -28, -60, -29, -46, - -5, -11, 84, 2753, -113, -65, 3, 5, - 13, -5110, -74, -126, -129, -82, -58, 116, - 15, 68, 243, -32, 126, -48, 11, -7, - 75, 10, 166, -153, 8, -43, -38, 81, - -41, 13, 100, 27, 46, -441, -56, 35, - 4, 51, 7528, 52, -141, -153, 39, -36, - -86, 80, -35, 50, -46, 23, 178, -3986, - -3350, 59, -278, 37, -2, 14, -157, -208, - -317, 218, 15, -296, -32, -51, 36, -27, - -2062, 28, -37, 322, 2286, 214, -196, -171, - -64, -163, 265, -50, 3, -177, -22, 68, - 124, 37, -15, -2202, 60, 133, 4, 371, - 2753, -111, 480, -446, 484, 43, 150, -331, - 1410, -791, 123, -136, -192, 267, 0, -89, - -105, 421, 68, -126, 79, 279, 202, -132, - -208, -3345, -105, 59, 118, -647, -48, -12, - 145, -403, 200, 7, -4, -3192, -223, 64, - 0, 415, 366, 136, 49, -7611, 79, -105, - 127, -69, -43, 103, -95, -93, -10, -30, - 94, 108, -109, 0, -87, -70, 300, -93, - 113, 25, -17, 2263, 41, 192, 18, 73, - 179, 129, 149, -81, -1, 0, 201, 184, - 651, 8, 18, 114, 2820, 383, -71, 376, - -2281, -1190, -143, 121, -45, -2157, -410, 81, - -14, 1537, -833, 29, 1150, -494, -8, -14, - 210, 188, 3073, -1775, -123, 80, -103, 227, - 296, 111, 1637, -197, 1349, 174, 3276, 49, - -98, 74, 660, 3, -252, -356, -9, 527, - -63, -7995, -16, 85, 249, 74, 26, 2, - 3, 26, -124, -61, -26, -144, 4, -52, - 6, -517, -95, 2566, -26, -190, -196, -509, - -2982, 4, -178, -9, -67, -25, 1, 193, - -68, -46, -82, -3734, -14, -339, -44, -151, - 55, 230, -3, 100, -47, -69, 35, 107, - 127, -175, -11, -10, -158, -140, 2934, -132, - 2571, -158, -217, 106, 137, -222, 74, -42, - 64, 559, 122, 73, -112, -2964, 2502, 13, - 301, -41, 203, -382, -151, -221, -147, -24, - 83, 37, -45, 56, 89, 71, 109, -14, - -43, -130, -108, -18, 74, -23, -34, 79, - 7662, -88, 70, 21, -110, 147, 26, 250, - 74, 165, 49, 43, 45, -22, -14, 293, - 5275, 57, -72, 93, 40, 115, -139, -332, - 95, 92, -26, 26, 169, -94, 332, 71, - -482, 137, 190, 114, 14, 151, 3125, 6, - 109, 6, 7, 1543, 282, -24, 24, 142, - 33, 123, 41, -72, -253, -33, 309, -107, - -64, -131, 56, -3528, 82, -17, 417, -47, - -588, 274, 155, 158, -245, 186, 147, -7, - -50, -218, 12, 118, -62, 652, 145, 64, - 2473, -146, 220, -2973, 97, 284, 29, 268, - 29, -208, -40, -251, -175, -16, -58, -65, - 28, 26, 55, 74, -12, 1911, 43, -82, - -150, -13, -119, 8, 119, 156, 1550, -88, - -102, 46, 226, -132, 95, 100, 87, 7, - -46, 8, -32, -16, -12, 317, -33, -27, - 291, -88, 169, 1, -101, -61, 161, 162, - -33, -1, 11, 5097, -34, 142, 31, 94, - 3619, -94, 67, 3379, -65, 28, 254, 189, - 110, 138, -41, 52, 32, -104, 154, 172, - -2365, -464, 281, 207, -66, -190, 399, -158, - 13, -155, -223, 92, -108, -25, 468, 189, - -4359, 42, -135, 138, 36, -1403, -264, -336, - -164, -49, 54, -125, -61, 62, 16, 172, - 182, 3134, -1373, 63, -227, -106, -133, -165, - -69, -57, -184, -46, 9, -57, 50, -3, - -62, -15, -123, 108, 111, 91, -161, 23, - -81, 7, 208, -5385, -244, 24, 95, 12, - -264, 62, -44, 21, -240, -299, -12, 117, - -61, -2551, 389, 2816, -179, 203, -421, 899, - -7, 174, -200, 98, 1036, -166, 11, -137, - 78, -7, -121, 245, -77, 124, 102, 51, - 3136, 74, -310, 40, 212, -239, -373, -154, - 398, 2967, 654, 488, 103, -230, -330, 831, - -63, -473, 152, -556, -2186, -371, 4, 86, - -12, -141, 5503, -87, -123, -17, -15, 154, - 192, -86, 97, 165, 352, 56, 154, 43, - -331, 1004, -52, -131, -3311, 3, 110, -153, - -70, 137, -168, -20, 115, 140, -25, -54, - -13, -300, 57, -131, 214, 261, -92, 618, - -2752, -3146, 61, -51, 210, -230, 87, -184, - 330, 22, -19, -107, -477, -39, 1, 127, - 178, -73, 425, 56, -25, -41, 135, 2423, - 59, -46, -10, 49, -116, -51, -2239, -228, - -75, 48, 3, 181, 161, -133, -355, 81, - 5, 84, -222, -83, 92, 33, -7558, -38, - -3, 159, 33, -58, -37, -107, 16, -61, - -94, 93, 97, 49, -275, 29, -198, -4, - -68, 87, 116, -7039, 46, 81, -25, 0, - -7, -46, 152, 64, -40, -143, -56, 147, - 403, 257, 2380, -538, -400, -132, -89, -29, - -2878, 457, -552, -12, -189, -370, -357, -3679, - 422, 63, 200, 116, -9, -229, -72, -100, - 3346, 88, -18, 28, -47, 159, 108, -160, - 253, 58, 2938, 55, 366, -33, -3209, 31, - -148, -10, -40, -443, 127, 120, 106, 9, - 4, -240, 200, 129, 328, -102, 187, 182, - 112, 2757, -3260, 314, -163, -3, -185, 354, - -97, -69, -199, 41, -143, 19, 108, -22, - -32, -18, -149, 35, 31, -5, -5083, 52, - 9, 5, -44, -52, 76, 7, -100, 7, - -79, 0, -33, 110, -208, 20, -159, -76, - 2, -8192, 156, 118, -306, -88, 136, -293, - -176, 163, 8, 1871, -112, 229, 311, -95, - -75, 17, 217, 152, 62, 17, -246, 3579, - 5, -87, -21, 92, 114, -185, 118, 8, - 196, -124, -220, 175, 104, 54, 104, -40, - -45, -152, 392, 216, -24, -28, 2024, -6, - 42, -91, -201, -9, -192, 35, -43, 1661, - -356, 1207, -1322, 340, -2937, -16, 163, -801, - -423, 197, -512, -70, 229, -412, 291, 511, - -36, -179, -98, -54, 93, 87, 263, -44, - 167, 77, -4, 7278, -101, -193, 91, -251, - -131, 269, 15, -168, -22, -26, 44, 24, - 154, 115, -11, -124, 28, 37, -14, -46, - -67, -8192, -51, -169, 41, -302, -81, 1991, - -11, 136, -175, 71, -104, 89, 60, 137, - 17, 106, 96, -238, -83, -52, -113, 53, - 2903, -47, 9, -227, -2784, -245, 146, -196, - -216, 41, -6, -128, -53, 1, -128, -145, - 149, 32, 25, -57, -14, 72, -135, 10, - -1946, -67, 74, -127, 141, -299, 55, 8, - 947, -2239, -271, 74, -227, -81, 31, 291, - -86, -2914, 22, -7, 293, 2, -25, 9, - -2997, 89, 3158, 192, -46, -246, -140, 46, - 287, 133, -110, 308, -114, -33, -106, 9, - -89, 105, 364, -172, 185, -61, 4464, -92, - -264, -66, -161, 102, -178, -264, -21, 114, -}; - -static const int16_t cb0808sl1[] = { - 246, -6, -180, 90, 127, 3322, 598, 182, - 81, 82, 67, -39, 87, -60, -8, -89, - 185, 99, -25, 27, 9, -59, -7421, 49, - -17, 116, -85, 6, -305, 88, -164, 99, - 61, -415, -114, -288, 1, -165, -12, 5, - -143, -142, -521, -245, -53, 38, -99, 3709, - -52, 0, -41, -135, 147, -217, 62, -2144, - 255, 132, 264, 65, -37, 204, -338, -280, - 192, -184, -158, -3685, -26, 203, 430, -29, - -16, 77, 230, -311, 597, 2553, -1126, -63, - 154, -431, -161, 315, 286, -147, 177, -3, - 93, 449, 253, -37, 101, -244, -77, 42, - -384, 22, 36, 235, -4973, 243, -120, -105, - -226, -114, -455, -404, 164, -505, 476, -124, - -2837, -82, -2920, -3, 0, 134, -94, 264, - -53, -53, 108, -3, -845, -2813, 228, -179, - -60, -2, 65, 33, -153, -16, -149, -2135, - 209, -929, -288, 227, 2656, -125, -42, 17, - 30, 3375, -367, 53, -262, -351, 108, -270, - 11, -57, -182, -51, -149, -287, -115, -24, - 99, -76, 6954, -75, -4, 38, -168, 138, - 109, -239, -45, 49, 28, -1376, 49, 66, - -83, -129, -61, -99, 135, 14, -93, 111, - 37, -16, 2, -76, 360, -77, 82, 161, - 149, -1660, 18, 98, -34, -12, -36, -65, - 126, -57, 28, 519, 2044, 297, 73, -218, - 51, 17, 21, -70, -32, -73, -39, -38, - -11, 60, 38, -129, -105, -173, 200, 7, - 124, -74, -2780, 2608, -57, -213, 54, -200, - 134, 208, -34, 236, 143, 101, 327, 558, - 75, 317, 3090, -188, 544, -186, 15, 116, - 237, 76, -105, 29, -300, -27, -211, 71, - -144, 183, -77, 38, -16, 39, 56, -7308, - -113, -116, -32, 222, 60, 76, -21, 59, - 52, 104, 383, 73, 149, 88, 127, 34, - -1819, -46, 50, 11, -159, -223, -163, -149, - 95, -163, -2168, -19, -937, -183, 66, -465, - -257, 341, -70, 111, 228, 52, 83, 63, - -52, -187, 16, -2539, -51, 3240, -81, 87, - -116, -183, -182, 96, -22, -191, -107, 217, - -10, -215, 9, -7, -97, -331, -55, 513, - -398, 1378, 2627, -2129, 563, 1462, -369, 498, - 1176, -469, 220, -953, -122, -236, -306, -276, - 31, 35, -167, 558, -134, 45, -54, 16, - 36, 18, 300, 2438, 62, -177, 77, 2638, - -108, -115, 3392, 274, -123, -66, 201, -400, - 170, 142, 151, 332, 53, -507, 81, -653, - -93, -3204, -5, 10, -43, 79, 3879, 77, - 191, 24, 23, -208, 6, -109, -97, 126, - -306, 629, 26, -516, 79, 21, 131, 43, - -253, -3463, 840, 653, -95, -48, 300, -1026, - -324, -909, -383, 195, 342, -136, -192, 422, - 262, -13, 534, 3125, 8, 1672, 176, -293, - 211, -1213, 537, 637, -10, -116, -149, 44, - 53, 105, 7, -97, 3, 17, 8, -21, - -7, -41, -38, -4959, -81, 1, 165, 196, - 98, 35, -35, 8, -28, 113, -20, 108, - -130, -65, 172, 2858, 41, -3295, 138, 10, - -95, -30, -173, 85, 42, 30, -119, 161, - 195, 125, -32, 136, 319, -33, 5142, 50, - 100, 128, -90, -53, -67, -203, 28, 19, - 37, -137, -124, -105, -25, -3405, -250, 294, - 409, -99, -1072, -383, -12, 212, -276, 3389, - -101, 171, -41, -554, -295, -437, 86, 158, - -242, 167, 135, 7, -149, 48, -4, -84, - 4911, 283, 5, -14, 105, -107, -384, 102, - 183, 47, 67, -5105, -5, 16, -155, 181, - 110, 24, -77, -32, 120, 1, 22, 167, - -90, -150, -5, 163, -44, -28, 54, -3058, - -174, 58, 152, -31, -179, -122, -57, 232, - -395, -4961, 61, -115, 31, 14, 82, -109, - -39, 59, -49, -133, 52, 17, 57, 52, - -63, 275, 146, 104, 53, 47, -55, 311, - 4871, -26, 48, -94, -11, -58, 63, 140, - -74, -94, -269, -77, 3372, -3116, 16, -47, - -74, -161, 115, 58, -247, -119, 399, 42, - -181, 154, -218, -24, -237, 58, -275, 2979, - 187, -124, 312, 301, 2767, -8, 40, -23, - -6, -38, -52, -363, -265, -78, -230, 286, - -135, -337, -81, 170, -13, -58, -117, 519, - -4784, 157, -193, 9, 62, -21, 180, 128, - 326, 213, 2440, 62, -601, -55, 2, -18, - -342, 142, 358, -632, -377, 3590, -248, -278, - -235, -28, 242, -133, 144, 26, -261, 113, - 45, -23, -1984, -77, 128, 249, -8, -266, - -38, -6, -1672, -45, -84, -377, 154, 17, - -83, -44, 156, -137, 43, 91, 253, 17, - -71, -92, 178, 12, 18, -8, -105, 101, - 7068, 71, -81, 84, -33, 79, 53, -7, - -85, -265, 117, 317, 114, 72, -482, -418, - -185, -97, 268, -1543, -79, -146, -48, -45, - -3259, -212, 1149, -165, 177, -158, -77, 100, - 86, -69, 107, 219, -512, -253, -418, -45, - 16, 5501, -184, 207, 67, 46, 109, -28, - -9, 33, 63, -16, 39, 92, 27, 23, - -10, -8192, 0, 50, -57, 68, -444, 1082, - 247, -138, 120, 472, -692, 212, -1576, 66, - 3061, 402, -160, 337, -685, -519, 227, -279, - 92, -4135, -393, -44, 6, -129, 59, 239, - 151, 153, -39, 116, 134, -40, 171, 118, - 207, 2615, 38, -167, -1671, 85, -135, -182, - -88, 246, 53, 29, -2, 16, 232, 544, - -46, -138, 122, -52, 1312, 9, 92, 13, - 4, 66, -35, -134, -56, 85, -43, -31, - 28, -3187, 100, -103, 70, -3, 186, -43, - 122, -3040, -27, -46, -121, 1, 37, 0, - -60, 2, -100, -152, -218, 175, -406, 175, - -193, 68, -208, -23, -230, 221, 3397, 45, - 48, 37, 337, 11, 15, -69, -4, -82, - 53, 33, -56, 75, -98, -69, -11, -19, - -12, 81, -52, 5428, 121, 82, 465, 10, - -229, 126, 32, 119, 439, 126, 1996, -85, - -81, -57, 88, 232, 108, -22, -24, 27, - -136, 91, -32, 18, 226, -33, 15, 117, - 145, -7737, 9, 58, -102, -113, 26, -2174, - 28, -421, -11, -70, -23, -70, -119, -96, - -133, 208, 20, -3750, -14, 23, 41, -180, - 2097, -103, -599, 146, 251, -77, -557, -76, - -96, 69, 266, 316, 74, -17, -227, 223, - 33, -261, 135, 8126, 250, -5, -57, 35, - 382, -44, 136, 81, 42, -80, 179, -73, - -75, -57, 274, -15, -3140, 3236, 196, 150, - -51, 222, -190, 13, 83, -313, -149, 89, - -281, -12, -42, 293, 567, 19, -43, 146, - 102, -39, 3666, 95, 76, -1, 12, 27, - 7, -5, 261, 132, -215, -295, -51, 496, - 77, 100, 16, -285, 649, -95, 280, 77, - 121, -2676, 25, -1148, 2912, -341, -91, 2380, - -80, -6, 269, -34, -686, -208, 19, 228, - 24, -5, -150, 11, 214, -316, 1187, 599, - -62, -2274, -240, 48, -86, 87, 86, 477, - 3832, 67, 135, 68, 747, 339, 385, -255, - -224, 184, 70, 171, -134, 2604, -231, 72, - 170, 51, -2785, -580, -86, -393, -63, -79, - -151, 334, 78, 329, -278, 102, -26, -55, - -3531, -378, -247, 176, -202, 147, 169, 87, -}; - -static const int16_t cb0808ss0[] = { - -1872, -332, -1311, -512, -934, -11, 112, 389, - -189, -1513, 1508, -1081, 185, -87, 3092, 529, - -166, -171, -1648, 2544, 2144, -259, -688, -1113, - -71, 387, 1194, -733, 175, 856, -976, 268, - 589, -1773, -426, -109, 1210, -486, 297, 195, - -991, -1543, -432, 1190, -1089, -531, -421, 80, - -225, 354, -231, -670, -299, -3694, -510, -882, - 31, 2804, 476, -478, 1897, 686, -1066, -1222, - -882, -374, -427, -1464, 957, 549, -1211, -204, - -218, -1412, -545, -968, 943, -342, 80, -281, - -249, -968, 3424, -2342, -212, 949, -167, -271, - 607, -838, -418, -891, -398, -877, 138, 1653, - -1034, -2515, -1363, -1535, -364, 432, -324, -1120, - 1531, 407, -698, 396, 325, 1432, 646, 2777, - 174, -836, -605, 2257, 1086, -888, 348, 36, - 513, 2229, 1543, 1293, 94, 2444, -574, -1030, - 933, -9, -668, 555, 346, 511, 715, -4033, - 409, -299, -166, 700, -560, 950, -1265, -245, - 1418, -1362, -20, 870, 152, 942, -331, -66, - 227, -186, 251, -3632, -1057, -989, -1798, 923, - 542, -630, 2889, -128, 1475, -97, -964, -860, - 534, -217, -746, 181, 321, -1007, 2595, -411, - 1298, 635, 310, 1955, -17, 846, -824, -11, - -952, 208, 328, -547, -1086, 1481, -264, -1574, - 3579, 500, 242, 1038, -1030, 353, -75, -2100, - -347, 2662, -2378, 261, 210, -1151, 525, 291, - 368, -200, -702, 105, -140, -81, 663, -716, - 334, 1220, 239, 21, 114, 301, -1898, 3647, - -302, 550, -489, -484, -853, -274, 1509, -419, - -330, -1121, -2666, 2507, -621, -818, 1188, -69, - -885, 231, 316, 1837, -740, -187, -102, 1148, - 1219, -123, 852, 1154, 27, 139, -344, -404, - -1133, 425, 353, 145, -123, 179, 49, -5836, - -571, 39, 274, -38, -457, 172, -80, 593, - -1977, -331, -421, 1965, 1768, -113, 64, 2272, - 475, 2165, 210, 873, -819, 757, -119, -530, - -1431, -2167, -1517, -864, 1060, -752, -1366, 2349, - -671, 1180, -179, 10, -450, 781, -799, -1303, - -393, -61, -113, 2053, -550, -843, 1028, -2044, - -2631, -1388, 1078, 171, 517, 496, -928, -1695, - 298, 708, -557, 122, -917, -197, -423, 1142, - 116, -528, -585, -470, 480, 400, 4605, 384, - -142, 57, -2340, -1507, -67, 907, 8192, 356, - -18, -704, 528, -32, -379, -611, 418, 703, - -396, 531, 155, 642, 678, -427, 85, 814, - 212, 845, -579, -590, -456, 103, -624, -4541, - -306, 638, -760, 36, -149, 1929, 1229, -717, - -543, 530, -694, 169, -2996, 423, -346, -897, - 1077, 255, -1054, -63, -1773, -479, 479, -701, - 1547, -1683, -342, -926, 112, -663, 1638, -9, - 2587, 311, -561, -932, -539, -335, 589, 779, - 2345, -432, 788, -967, 319, -4, 192, -588, - -103, 357, -3508, -257, 707, -473, 1521, -9, - 130, 3290, 274, -296, -802, -139, -814, -19, - 971, 849, 253, 486, 40, -1216, 1179, -1772, - -996, 1400, 838, 1955, -1432, -1925, 2324, 767, - 896, 1314, 3407, -1003, -552, -967, -166, -26, - 1099, -1965, 9, 239, -10, -243, 864, 1251, - 91, -2279, -691, -542, -473, -1908, -1208, -1447, - -891, -311, -1136, 1638, 1150, 586, 1656, 260, - 538, -1746, 1460, -478, -860, 297, -605, -139, - 822, -3718, -194, 307, 609, 30, 3418, 226, - -338, 161, -387, -344, -472, 354, -170, -421, - 433, 601, -1446, 821, -48, -31, 493, 916, - -347, -3740, -899, 1389, -355, 71, 382, -644, - 485, 218, 975, -542, -3191, 742, -102, -783, - -1607, 473, 196, 1692, -71, 258, 2446, 1507, - -968, -1025, -1087, 637, -921, -1405, 1192, -88, - 2044, -1813, 922, 156, -1096, 1007, -695, -485, - -1015, -468, -316, 1825, 190, 2132, -205, -218, - -3556, -286, -1350, -212, -634, 120, 417, -311, - -90, 219, 870, -334, -1304, 523, 999, -144, - 98, 2157, 205, 45, -247, 1401, 2423, 278, - -766, -66, 309, -121, 316, -543, -3418, 932, - -803, 637, 436, -2341, 2016, 928, -836, -1212, - 702, -1179, -544, 6, -1429, 1014, 464, 1166, - 581, -291, 136, 0, 983, -799, 693, -230, - -727, -186, -310, -76, 698, -6, -660, 762, - 814, 451, -328, 4469, -454, 14, -423, -116, - -134, -568, 1535, -562, -629, -269, 826, 380, - 68, 282, -409, 640, -384, 218, -5702, -280, - -638, -2586, -557, -877, 49, 648, 434, 1178, - 3442, 883, -78, 2024, -253, -210, -1090, 198, - -67, -52, 3226, -671, -1606, 49, 1775, -422, - -173, 309, -720, -667, -505, 2073, -678, -1152, - -231, -519, -719, 422, -2614, -394, 543, -993, - 1449, 437, -463, -1286, 1191, -1274, -710, -463, - 659, 1493, 45, -832, -414, 306, 94, 1284, - -669, -1312, 1082, -917, 2489, -494, 547, 738, - -1696, -174, 282, -1442, -1455, 1633, 912, -428, - 964, 12, -2404, -485, 631, -311, 1810, 2912, - -16, 576, 50, -927, -175, 37, 673, -201, - 995, 684, -244, -251, -1444, 3195, 1863, -88, - -1183, -966, 1769, 36, -825, 766, 489, -86, - -365, -106, -1477, -330, 125, -253, -250, -523, - -731, -5130, 653, 395, 99, -845, -721, 127, - -287, 850, 479, 25, -30, 36, -782, 611, - 448, 99, 933, -20, -853, -949, -286, -379, - -654, -385, 1298, 547, 235, 1242, -583, -4147, - 81, -547, -1142, 1280, -223, -1712, -1501, 458, - -142, 2065, 208, 855, -1115, -187, 861, 1090, - -760, -2551, 2326, -378, -1205, 488, -241, 893, - 113, 176, 4060, -225, -41, -717, -26, -442, - -445, -312, 813, 494, 314, -210, -98, -788, - 255, 632, -506, 166, -704, -334, -214, -860, - -5281, 60, -34, -238, -147, 643, 520, 2038, - 28, 2433, -1694, -1316, -615, 572, -150, -107, - 349, -1763, -307, 78, -1124, -631, 1162, -326, - -277, -591, 558, 1016, -4668, -324, -815, -251, - -1284, 52, 294, -1283, 598, 630, -345, 641, - -34, 1085, 4247, 637, 1695, -858, 212, -243, - -64, 327, 557, 426, -321, 363, -652, 372, - 777, -567, -749, -1704, 414, 5299, 389, 242, - 39, 31, -315, 179, -102, 11, 62, 248, - 557, 706, 359, -85, 303, -403, 1531, 409, - -2092, 144, -1354, 54, -48, 51, -1787, 1278, - 942, 1264, -1495, 1671, 92, -899, -1149, 1908, - -903, -596, 342, 1749, -825, -13, 509, -1163, - 1065, 2405, -253, -741, 1099, -528, 2971, -412, - -235, -869, -136, -352, -489, -384, 745, -398, - -4197, 84, 1152, -497, 955, -161, 461, -16, - -871, 801, -93, -15, -352, 1826, -490, -536, - -2853, -633, 128, -1537, -1670, 538, 788, 1276, - 554, -340, 565, 1216, -1758, 384, -1313, -628, - 24, 835, -862, -927, 1792, -1042, 209, -784, - 807, -383, -1399, 3531, 52, -537, 205, -271, - 3071, 1678, -694, -2313, -1279, -1656, -428, -1063, - -1576, -323, -342, -257, -227, -716, -458, 1161, - -180, -71, -40, -1276, 1778, -3123, -378, -1363, - -827, 880, 275, -274, -581, -186, -8, 661, - -1114, -199, -171, 379, 429, -1551, 1645, -857, - -163, -2623, 1217, 1458, -596, -68, 383, 973, - -485, -354, -597, -2875, -516, 234, -83, 340, - -396, 1365, -574, -816, -2086, -1059, -1589, -593, - -779, 334, -546, 49, -1065, -1959, 1736, 1134, - 187, 1833, 17, -82, 68, 803, -456, -89, - 1760, 836, 1570, 122, -985, 2549, 1616, 82, - 1102, 227, 222, -1236, -155, -1012, 633, 467, - 163, 445, 166, 766, -253, -347, 1041, 5121, - -21, 792, 81, -478, 128, -158, 316, -1180, - -372, 1692, -828, -31, 1122, -2583, 1346, 2483, - 195, 72, 549, 424, 947, -470, 1940, -75, - 505, 1377, 550, 58, 1785, 343, -817, 874, - 3483, -307, -576, 240, 35, 837, -717, -247, -}; - -static const int16_t cb0808ss1[] = { - 2328, 183, 1652, -907, -3005, 1329, -61, -465, - 0, -453, -1621, 223, 232, -59, 254, -312, - -117, -59, -477, -2648, -1176, -227, -1937, 962, - 141, -1489, 849, 93, -1284, 1000, 295, 192, - -139, -468, -736, -436, 2155, 371, 2475, -348, - 856, -1985, 38, 94, 496, 758, 954, -243, - 134, -1759, 491, -1406, 1114, -2554, -447, -692, - -2128, 44, -923, 1610, 787, 150, -500, 3442, - -698, 276, -517, -1555, 379, -72, 810, -1373, - 2897, 936, -586, -438, 925, 1881, -419, 211, - 1724, 721, 885, 614, 253, 613, -1440, 509, - 842, -2407, -216, -1765, 451, 1419, 599, 689, - 1473, -175, -2974, -1015, 1983, -68, 640, 21, - 140, -1295, -556, -89, -836, 718, -343, -1903, - 443, 502, -1064, 1328, 86, 2049, 1235, 130, - 892, 1105, 692, -2968, -755, 473, 423, -1371, - -2032, 1885, -29, -516, -1118, 285, 482, 164, - -1932, -685, -819, 695, 715, -1520, 1300, -1188, - -121, -197, -4233, -141, 1279, 299, 208, 1071, - 20, 772, 692, 531, 257, 428, 78, 202, - -399, -27, 793, 1150, -736, 388, -1922, 155, - -410, 85, 1135, 835, 133, -88, 65, 62, - -534, -136, -4590, -162, -968, 1378, -445, -2825, - -93, -519, 402, 12, -1110, -637, -765, 210, - -2305, 654, 447, 26, -265, -91, 71, -886, - 126, -109, 7, 346, 19, -713, -257, 774, - 1080, -579, 185, 200, -5691, 541, 228, 424, - 37, 512, -78, -201, 848, -369, 1099, -1001, - 214, -336, 266, 2502, 1583, -2131, -654, -2476, - -97, -787, -738, 1056, 1385, 124, 944, -3421, - 1172, -547, -226, 1249, 1552, 1194, -308, 489, - -1152, 751, -92, -168, -3112, -1451, 2038, 35, - 371, -1585, 535, 308, 5, -53, 523, -169, - 591, -175, -1028, 91, 743, -144, 230, 1831, - -177, 509, 1291, 1808, -3322, -815, -227, -475, - -1064, -647, 79, 1223, 174, -10, -412, 393, - -305, 1224, 1310, 12, -521, -1267, 1911, 2245, - 407, 724, -1232, -2017, 566, 506, -467, 813, - 660, -196, -3643, 2495, 870, -561, 289, 662, - 654, -508, -734, -325, 622, 220, -309, -307, - -181, -445, 131, -1655, -835, -631, 883, 211, - 737, 552, -881, -3103, -766, 595, 112, 151, - -1177, 601, 479, -14, 37, -926, -505, 1062, - -1755, -799, -178, -555, 2509, -694, -792, 662, - 737, 847, 1611, 397, -67, -134, 474, -2251, - 2698, -245, 2054, 1603, 1291, 1188, 40, 763, - -216, 1554, -297, -1769, 410, 1270, 1089, 440, - -967, 294, -37, 270, 471, 1287, 3773, -108, - -610, -275, -298, 270, -384, 2072, -675, 1002, - 174, 18, 171, 704, 3311, -105, -1774, 108, - 511, -3001, -69, 543, -227, -1196, 1431, -63, - 6, 1279, -1, 671, 239, -2127, -1924, -934, - 168, -300, 1075, 1071, 3088, -590, 1439, 329, - 1073, 127, 762, -131, 274, 837, -134, -610, - -399, -1415, 1047, -156, 415, 765, 698, 428, - -748, 241, -4226, 152, -829, 1040, -937, 145, - -852, -85, -2957, -130, -406, 726, 168, -37, - -1321, -1069, -1255, 1159, 1575, 552, 649, -1953, - -17, 1027, 1078, -385, -2761, -553, -201, 58, - -1900, -24, 283, 1248, -90, 419, 1122, 902, - -1548, -32, 34, -360, 707, 45, -3458, -246, - 287, 308, 397, 393, 822, 1323, -565, 505, - -1553, -1902, -677, 625, 1079, -135, -2132, -187, - -163, -1001, -1479, -932, 1131, -2588, -316, 53, - 1270, -747, -966, 980, 242, -266, -1575, -1146, - -605, -523, -221, 585, -787, 1365, -286, -183, - 411, 546, 4779, -286, -578, -101, 309, 896, - 34, 451, -1022, -699, 170, 935, 458, 4143, - 229, -572, -912, -397, -40, -132, -198, 98, - -1858, 612, 101, -98, -18, -349, 322, -1626, - 1304, 273, -235, 418, -509, 3961, -493, 1040, - -416, 1808, 161, 1443, 1052, -460, 55, -67, - 41, 514, 1305, -836, -1636, 1353, 379, 147, - 398, -3814, -679, 235, 327, -2293, -716, 1234, - -728, -323, 698, 1992, 4, -275, 944, 895, - 212, 334, 285, -710, -891, -1325, 3107, 3, - 367, -1779, 300, -868, -59, -644, -326, 111, - 267, -43, 421, 976, 57, 1461, -172, 245, - -188, 296, -215, 5269, -46, 177, 199, -539, - 92, -542, 251, 951, -231, 117, -580, -898, - 402, 847, 4, 384, -215, 161, -1991, 4422, - 2461, -1219, -751, 1843, 1483, 1072, 2621, -16, - -1157, 243, -557, 651, 953, 476, -417, -533, - 505, -590, 713, 153, 1268, -312, -217, -124, - 870, -484, -751, -161, 897, 755, -823, 4117, - -1311, -729, 447, -642, 929, -2408, -338, -967, - -104, -1048, -2216, -1722, -124, -204, -196, -1156, - 1460, 391, -543, 120, 70, 204, 1185, -2490, - 2950, -507, -615, 1243, -150, -363, -475, -531, - 783, 671, -205, -591, 217, -523, 263, -14, - 71, 958, -1185, -1029, -330, 327, -705, 1229, - -2925, 131, -495, 1756, 2101, 441, -11, 133, - 1274, 1253, -154, 772, 522, 1725, -277, -1012, - -726, 1339, -1200, -241, 1676, 974, 2256, 347, - 2743, 1482, -738, -241, -868, -1294, -664, 855, - -1329, -4174, -1647, -104, 101, 307, -647, -823, - 347, 4, -120, -1112, 334, 27, 265, 990, - 319, -1414, 313, -603, 52, -3138, 1552, -612, - -854, 626, 212, 773, 2334, 662, 614, 560, - 589, -533, 1337, 229, 557, -26, 1458, -626, - 1890, 2392, -1525, 1023, 667, -431, 72, 1691, - 1015, -97, -515, 1380, 796, 1192, -39, 162, - -2821, 2960, 1558, -1058, 1327, 793, 1231, -743, - -1190, -245, 29, 486, -494, -1371, 1633, -66, - -1806, 231, -664, -147, 2402, -584, 473, -527, - 1272, 464, 1991, -1007, -235, 357, 201, -1176, - -341, 223, -47, -2089, 815, 49, 192, -719, - -1041, -248, 3046, -40, -501, -346, -1347, -401, - 57, -1588, -1039, 443, 590, -1089, -182, -1365, - -1013, -3917, -382, -98, 1025, -51, 698, -197, - 848, -75, 1596, -408, -1796, -3191, 1155, 234, - -100, 698, 571, -1233, -315, -1502, -647, -571, - -322, 842, -1048, -1115, 8192, -784, -472, 17, - -718, 37, 1190, -393, 146, -547, 90, -433, - -321, -1143, -501, 468, 235, -486, -64, -2214, - -330, -837, 1214, -127, 709, -3, 623, -384, - 221, 297, -783, -3802, -408, -11, -707, 92, - -275, -268, -117, 1580, 1466, 710, -1300, 142, - -746, 1647, 2399, -1231, 114, 1220, -1112, 882, - 467, -973, -976, 3855, -647, -150, -1244, 973, - -364, -154, 473, -675, -817, -346, -266, -769, - -613, -476, 1181, -8, -1054, 405, -768, 1385, - -1598, -892, 672, -2185, 83, -27, 582, -434, - -944, 99, -888, -1658, -1516, 2392, 726, -222, - 284, 324, 4848, -67, -782, -45, 424, -203, - -194, -1229, -114, -189, -216, 275, -935, -93, - 117, -1725, 360, -2561, -1555, -1199, -769, -285, - 74, 1267, -387, 1368, 179, -113, 952, 1025, - 725, -542, -186, 1258, -1396, -747, 572, 603, - 1965, -668, -12, -2512, 1337, -255, 254, 2285, - 1136, 1397, 557, -671, -1149, -614, -462, -913, - -452, 1206, -2922, 485, -882, 270, -1309, -605, - -21, -580, -1284, -194, 169, -2314, -216, -229, - 1124, 103, -1205, 1500, 1118, 1456, -1149, 780, - -467, -385, 585, -1062, 289, -3356, 198, -309, - -310, 91, 44, -377, -632, -737, -516, 30, - -779, 73, -482, 4661, -275, 38, -632, 479, - -345, -406, 76, -208, -230, 80, -220, -313, - 203, -3, 1740, -131, 773, -30, 372, 767, - 1673, -770, 3326, 1586, 234, 408, -257, 474, - -584, -990, 1378, 696, 47, -612, -313, 189, - -3964, 795, -289, 202, -437, -1648, 373, -780, - -24, -952, 123, 438, 797, 539, -481, 191, - 291, 37, -790, -321, 4520, -49, -281, 211, -}; - -static const int16_t cb0808sm0[] = { - -4664, -115, 59, -280, -199, -25, 213, -937, - 344, -2137, -841, -370, 256, 512, 1098, -130, - 58, -121, -414, 8192, 489, -296, -33, 98, - 49, -217, 721, -42, -418, -227, -8, 205, - -276, 407, -1218, -146, -292, -143, 113, 978, - 2693, -9, -1032, 1781, 1777, -215, -978, -824, - 68, -162, 55, 2991, -844, 682, 497, 406, - -922, 2471, 599, 774, -129, 1292, -1004, 777, - 42, 314, -102, -963, -2794, -2620, 510, 355, - 372, -248, -391, -163, -298, 561, 117, 1183, - 38, 182, 1811, -4, 328, -13, -456, 305, - 368, -1691, -2818, -1074, 1029, 261, -1446, 343, - 12, -2757, 1021, -375, -3, -155, 116, 195, - 3420, 64, 139, 780, 187, -464, 261, -313, - -128, 185, 3703, 3160, 960, 706, 41, 405, - 10, 1191, 353, -549, 131, 164, 105, 1, - 23, 386, 73, -509, 2651, -1441, -834, -1657, - -645, 1005, -777, 695, 212, 1420, 65, 701, - 25, 335, 136, 359, -112, -150, 191, 392, - -258, -1140, 651, -4551, 411, 251, -169, 804, - -83, -208, -363, 81, 152, 75, -1194, -203, - -9, 157, 413, -62, -210, 5393, -22, -407, - 132, -288, 2360, 131, -1535, 553, -2524, -140, - 250, 1259, -30, -1, 1766, 99, -529, 91, - 3948, -262, -3752, -382, -339, -701, -140, -787, - 67, -11, 331, -828, -443, 596, 47, 1634, - 31, -318, 39, 147, -670, -776, 707, -921, - 172, 971, 1163, 48, -81, -1357, -181, 2872, - -152, 898, 1075, 529, 91, -2279, 2925, -848, - 589, 1910, 549, 1088, 743, -631, 42, -1528, - 23, 380, -5, 389, -1147, -209, -2041, 224, - -1998, 520, -776, 193, -2648, -78, -34, -131, - 22, -200, -28, 18, 328, 215, 67, 61, - 50, -72, 301, -207, 413, 720, -6194, 967, - -3275, 149, -2444, -521, -772, -278, 137, -159, - 932, -111, 1219, 525, 17, -684, -1229, -1776, - 66, -2307, -195, -527, 272, -470, -356, -7, - -338, 146, 1021, -893, -2980, 591, 129, -257, - 209, -58, 538, -3973, 576, -905, -642, -2092, - 153, 737, -596, 573, 236, -887, -1692, -370, - -189, -216, -58, 714, 10, -582, 517, -86, - 450, -147, -310, 162, 1747, -656, 3577, 700, - 190, -685, -170, 241, 91, -126, 5567, 441, - -50, -688, -73, 938, 320, -130, -839, 1154, - 149, -446, -10, -11, 12, -659, -138, 637, - -470, 933, -431, 235, -86, -2, -407, -5851, - -250, 1414, 525, 110, 421, 255, -149, 86, - 378, -321, 1380, 118, -2849, -1138, 180, 1175, - 1932, 32, -488, -121, -412, -441, 397, 249, - -172, -95, 420, 375, -132, -215, -167, -206, - 8192, -116, -61, -311, 269, 615, -353, -115, - -383, 366, -651, -196, -98, 85, 861, 543, - -231, 237, 493, 380, -766, -168, 3227, 659, - 701, 181, -3004, -7, 154, 298, 298, -257, - -32, -5713, 48, 102, -776, -148, -110, 316, - -645, 212, 213, 575, -69, 31, 553, -673, - -5, -48, -148, -133, 11, 143, 10, 159, - 319, 43, 7462, 162, 228, -90, 75, 151, - 103, -2542, -13, -338, 11, -442, 123, -3039, - -452, 7, 106, 502, 227, -2034, 90, 500, - -28, -646, -262, -62, -78, 40, 419, 6761, - -11, 40, 209, 61, -151, -68, -245, -401, - 26, -123, 189, -57, 611, 6, -1285, -99, - -890, 3609, -302, -808, 639, -3245, -226, 107, - 54, -108, -316, -61, -56, 228, -16, 195, - 275, 214, -60, 77, -7157, 130, 8, 244, - -2160, -760, 450, -186, -378, 32, -797, 214, - -3569, -450, 307, -17, -141, 16, 1024, 404, - -2063, -288, -160, 4056, 877, -346, -970, -87, - 336, 961, 666, 585, -465, -1329, 350, -338, - -5421, -173, -295, 72, -201, 533, 462, -133, - -937, 1891, 264, 71, -935, 640, 687, 852, - -386, -85, -5644, 306, 240, 640, 67, 94, - -902, -351, -417, -3, 284, 38, -156, 359, - 53, 139, 185, 274, 2613, 213, 1282, 2867, - 30, 1234, -911, 343, -93, -1671, 57, -814, - -19, 326, -256, -113, 72, 3177, 3393, -125, - 460, -261, -503, -1019, -681, -253, -957, -157, - -117, -231, -212, 1446, 225, -3009, 313, -435, - 387, -928, 696, -857, -452, 66, -2063, 782, - 14, -94, 51, 242, -422, 236, -3825, -666, - 348, 196, -2770, 429, -416, -266, -1215, -586, - 84, 328, -302, 219, -457, -532, -764, 85, - 2008, -806, 2906, -1405, 367, 835, 715, -986, - -217, 88, -328, 569, -586, 3096, 249, -615, - 453, 176, -540, 792, -2472, 2189, 876, -353, - 111, 212, -7, 597, -154, 818, -401, -1408, - 748, 2502, 1426, -2897, 1069, 326, -605, 120, - -4149, -3087, 729, 82, 224, 320, 353, -77, - -163, -322, 220, -1073, 10, 545, -518, -453, - 50, -386, -2002, 614, -705, -806, -928, 2941, - -520, -35, 1208, 413, 900, 138, -414, -289, - -15, -75, 185, -373, 649, -251, 666, 2708, - -2817, -749, -159, -112, 454, -385, 1037, -46, - -25, -14, 66, 552, 160, -40, -552, -156, - 151, -5287, 541, -242, -82, -1164, 849, -773, - -136, -162, -76, 23, -371, -222, -2245, 468, - 425, -356, 418, -3, -322, -3573, 148, 260, - -155, 3301, -165, -3186, -709, -458, 870, 386, - 59, -161, 533, -150, 598, 384, 900, -1233, - -74, -464, -519, -661, -55, -2562, 290, 1489, - 1739, 2277, 874, -1483, -447, 93, 309, 311, - -203, -19, 2271, -1280, -125, -443, -538, 2650, - -42, 290, 245, -149, 24, 38, -133, 1638, - 210, -239, -180, 516, -12, -719, -19, -517, - -6190, -181, -89, 318, 485, 631, 11, -205, - -57, 257, 573, -72, 273, -579, 107, -5, - 112, 425, 2449, 2741, 758, 656, -663, -282, - -48, -45, -294, -448, -5562, 61, -1, -464, - -263, -688, -115, -15, -108, -569, -448, -48, - -180, -105, 14, -180, 490, 274, 625, -588, - -120, -196, -305, -126, 435, -2490, -2693, -3414, - 31, 97, -167, -114, 247, 7695, -189, -580, - 219, 241, 188, 327, 179, -193, 135, -176, - 127, 479, 529, 234, 112, 234, -358, -286, - 1109, 2940, -610, -13, -2650, 495, 1355, -574, - -43, -1497, -292, -503, 564, -363, 24, -313, - 1387, 221, -3612, 783, 637, 43, 1351, 217, - -21, 149, -3104, 190, -259, -201, -342, -201, - 166, 2411, -1082, 283, -382, -725, 157, 155, - -1609, -592, 527, -2959, 9, 216, 526, 79, - 54, -132, 202, 785, 929, 1755, -663, 366, - -3735, 3282, 305, 572, -36, -111, -231, 119, - 603, 1357, -153, 553, 363, -760, -1188, 890, - 147, -3844, -3788, 150, 257, -588, -234, 497, - 361, -543, 255, -175, -377, 49, -616, -200, - 4115, -541, 130, 678, -3458, -506, -218, -1317, - 889, 29, -104, -2, 532, -393, 513, -792, -}; - -static const int16_t cb0808sm1[] = { - 4123, -74, 639, 326, -110, 1896, 826, -855, - -299, -452, 536, -323, 262, 79, 486, 144, - 270, -64, 277, 154, 399, 50, -7270, -61, - 14, -8, 19, -104, 333, 119, 374, 389, - -196, 77, -322, 261, 75, 386, 162, 2360, - 644, -2785, 355, 277, -121, -148, 156, 2136, - 112, -453, 429, 171, 2405, -1245, -775, -181, - 2110, -583, 127, 889, -290, -550, -165, 1027, - 2155, -351, -936, 432, 2689, 217, -20, 646, - -785, 908, 654, 970, -294, -41, 466, -245, - 138, 50, -108, -366, 177, 481, -2118, 968, - -594, 3892, 528, 188, -613, 18, 283, 733, - -35, 1598, 387, 1, 156, -206, -437, 203, - -244, -347, 325, 296, 100, 1171, 49, 920, - -418, -54, -2756, 24, 123, 1018, 303, -501, - 901, -447, 322, -2361, 1039, -1067, 877, 1329, - -143, -2773, 269, 1560, 398, -3193, 102, 990, - 279, 379, -204, -144, -174, 139, 411, -234, - 21, -5064, -188, 365, 278, 353, -189, 94, - 593, -402, -353, -257, -788, 383, -1036, 569, - -72, -1764, 571, 1003, 629, 670, -1400, 0, - -435, 64, 189, 2874, 239, 1128, 992, 1213, - 69, -128, 207, 713, -2436, -931, -387, -111, - 1064, -170, -2853, -1072, -367, -1048, -238, -60, - -49, 340, 2382, 370, -245, 351, 248, -64, - 2331, 458, -484, -34, 281, 689, 483, 636, - 199, 3153, 607, -124, -3296, 953, -407, 49, - 455, 1083, 690, -169, -725, 311, -493, -1761, - -3054, 376, -544, 479, 91, 159, -2837, -1257, - -830, -948, -254, 289, -1039, 856, 86, 1123, - 203, -768, 1089, 73, -866, 308, 437, 674, - -2067, -240, -1079, 33, -1069, -3502, 756, -676, - 45, -2544, 378, -365, -275, -293, -394, -649, - -507, -2850, 672, 370, 186, -417, 682, 185, - -15, 2863, 21, -165, 356, -3776, -103, 535, - -416, -345, -31, 24, -90, -205, 96, -966, - 94, 424, -5, -188, 149, -2193, -183, 2342, - 425, -647, -1697, -627, -444, 1248, -967, -702, - -48, 3616, -3484, 774, -299, 94, 421, 472, - 71, -144, -523, 114, -172, 349, -285, -106, - 101, 59, 429, 512, 3362, -38, -62, 50, - -225, -1408, 780, -2747, -404, 489, -975, 840, - 357, 982, 488, -275, -109, 393, 375, 4794, - 183, -110, 922, -760, 61, -1067, -8, 322, - 74, -101, 554, -350, -486, 66, 384, 748, - 14, 223, -45, -386, 69, 6231, 247, 325, - -320, -47, -50, -165, 153, -380, 589, -3243, - -173, -140, 341, -747, -1559, 639, -1658, 356, - 110, -150, -273, 76, -632, -425, -227, 640, - 211, 192, -747, -165, 4608, 290, -160, 1268, - 2754, -3, 578, 189, -485, -2747, -123, -1309, - 662, 601, 43, -136, 84, 1625, -1113, 1400, - 75, -126, 3581, -243, 2339, -514, 2203, -400, - -483, 521, 30, -246, -76, 359, 101, 663, - -40, 57, 52, 360, -447, -290, 254, 104, - 102, 113, 215, -163, -388, 299, 4570, 31, - 108, -41, 41, -2633, 2891, 1188, -505, 1061, - -349, -604, -449, -374, -320, 969, -304, -192, - 246, -152, 441, -46, -1416, 137, 1987, 495, - -63, 1087, 875, 699, 201, 211, -3157, -273, - -60, 195, -2813, -239, 2486, -55, 294, 315, - -133, 448, -1849, 363, 1063, 76, -928, -574, - -72, -57, 168, 5673, -156, -116, 400, -124, - 82, 218, -487, 37, 112, 53, -544, 178, - 99, 480, -7179, -196, 271, -160, 308, -62, - 393, 394, -220, -740, -14, 92, 408, -364, - 299, -305, 76, -239, 26, -312, -234, 34, - -189, 871, -297, 364, 282, -321, -927, 4511, - 2, 6, 308, -82, 87, -128, 518, 82, - -4509, 1145, 960, -109, -186, 83, -144, 752, - 84, -2876, -162, 877, -249, 317, 510, 338, - 298, 744, 2892, -791, 363, 1088, 630, -2506, - -1, 3150, 219, 130, 119, 313, -822, -668, - 1201, -2948, -237, -106, -711, 405, 276, -255, - 0, 440, 161, 2587, -734, 3376, 276, 154, - 287, -200, 594, -29, 198, -237, -608, -445, - -286, 202, -783, 112, -3879, 78, 2809, -337, - -606, -684, -434, 559, 273, 201, 331, 903, - -53, 346, 700, 2599, 302, -590, -2551, -498, - -26, -667, 576, -546, 457, -289, -1408, -1021, - -63, 78, 153, -83, -696, -3105, 2498, -1502, - -1249, -238, 254, -287, 215, 313, 279, -517, - 67, -58, -148, -1111, 58, 5151, 346, 283, - -367, -900, 542, 209, -438, -128, -135, 54, - 7, 869, 291, -1073, 775, -61, -145, 457, - 562, 1332, -4589, 99, 1366, 184, 980, -920, - 80, -266, -152, -1877, -266, 364, -1432, 272, - 2275, 567, 60, 50, -2504, -386, -700, 373, - 6775, -15, -434, 347, 215, -369, -20, -281, - -243, -325, 227, -283, -665, -74, 336, -674, - -112, -369, -53, -396, 328, 3588, -541, -557, - -164, 1305, -817, -462, 1986, 1249, -574, 130, - 152, -2375, -425, 442, -3827, 322, -728, 563, - -179, 534, 620, -937, 590, -1, -59, 584, - 175, -193, -168, -5, -150, 156, -175, -178, - -245, -7481, -273, 212, -35, 318, -178, 446, - -55, -26, 42, -46, -265, 767, 330, 295, - 910, -54, 490, 2952, 598, -2578, -644, 403, - 149, -88, 549, -510, 596, -225, -2341, -286, - -2724, 5, -1960, -262, 922, 537, 646, -62, - -18, 8192, 484, 112, -222, -211, -224, 317, - 112, 82, -853, 1, 176, -475, -162, 200, - -193, 166, -228, -214, 72, 417, -27, -16, - 4, 395, -515, -6832, 28, -47, 626, -173, - 63, 90, 141, 217, 1037, 335, 4520, -896, - 111, 91, -656, -103, -729, -29, 653, -599, - -11, 2734, -378, -291, 60, 228, 47, -3670, - -192, 653, 733, -597, 898, -420, 1572, -133, - -154, 329, -259, -225, 218, -82, 117, 300, - -479, 277, 787, -1719, 136, -3603, 702, 1357, - 3340, 362, -438, 131, -1463, 367, -467, 1722, - -2186, 343, -379, 1221, -562, -260, 1157, 2692, - 37, -89, -322, -322, 8192, -284, 235, -528, - 113, -359, 44, 74, 119, -917, 403, 410, - -150, 157, 514, 168, 407, -246, -31, 510, - 105, 449, 4612, 635, -90, -1260, 774, -284, - -80, 456, 7, -3000, -324, -212, -104, -374, - -440, 1268, 2736, 53, -1178, -403, -438, -534, - 121, 261, -497, -73, 10, -262, 17, -1870, - 178, -1339, 224, 3115, -436, -448, 385, 894, - -1, 105, -18, 268, 342, 270, 891, 367, - 121, -325, -1610, -75, -3233, -189, -1050, 961, - -2833, -304, -51, 400, -284, -810, 824, -71, - -135, 194, 297, -297, 1129, 660, 518, 2426, - -225, 251, 4677, -176, -464, 296, -1208, -423, - -875, -581, -707, -1150, 499, -778, 28, 29, - 101, -4213, -127, -3681, 425, 481, -529, -679, - 11, 266, 127, -445, 527, -577, 310, 1465, -}; - -static const int16_t cb1110l0[] = { - -3748, -3820, -105, 16, -22, -7, 112, -14, - 52, 28, -42, -113, 132, -81, -8, -112, - 19, 33, -251, 117, -33, -9, -13, -28, - 60, -30, 29, 27, -58, -7, 4, 43, - -10108, -38, -3, 48, 3, -23, 202, -175, - -202, 71, -2143, 3, -82, -38, -113, 141, - 38, -66, -118, -38, -14, 148, -264, 143, - -13, -56, -9, -21, -28, 8930, -23, 53, - -40, 30, 72, -46, 26, 66, 22, 32, - 44, 22, -50, -66, -115, -141, 24, -3013, - -3460, 492, 207, -62, -567, 134, -26, -64, - 287, 343, -213, 42, -274, -144, -144, -77, - -26, -39, 4, -4, 42, 43, 30, -16, - 34, 113, 9291, -171, -17, 24, -53, -27, - 45, 42, 533, 146, -65, 32, 156, -144, - 2821, 889, -7, 614, 11, 1, -473, 434, - 659, -323, -2448, 23, -138, -582, 436, -152, - -30, 29, -290, -302, 3127, 496, 14, -346, - -70, 457, -1976, -229, 53, -2077, -313, 58, - 33, -91, -175, 141, 2728, 3232, -2150, 245, - -142, 13, -318, 70, -152, -64, 132, -322, - 44, 30, -70, -184, 433, -25, -97, -2035, - 145, 47, 640, 179, -441, 48, -108, 1742, - -280, 33, -3259, 79, -147, 324, -80, 65, - 48, 90, -7, -21, 22, 3, 56, -30, - 14, -2, -111, 22, -8, -8252, -103, -36, - 57, -203, 287, -2761, -220, 143, 11, -3597, - 21, -81, 62, -99, 41, -172, 108, 29, - 351, -370, 15, -122, -207, 275, -93, -2760, - 400, -212, 225, 230, -239, -3530, -73, 211, - 288, 85, -6, -634, 57, -78, 361, -149, - -1843, -23, 17, -37, -71, -174, -237, 42, - -22, -243, 63, -101, 131, 35, 136, -4025, - 41, -262, -57, 197, -290, 307, 35, -16, - 3, -5, 45, -7, 1, -47, 41, -19, - 79, 78, 42, -85, 74, -414, 1696, 703, - 297, -3296, 108, -546, 1129, 44, 447, -433, - 315, -1012, 133, 141, 1051, 601, -18, -532, - -30, 712, -127, -210, 10, 2442, -95, -46, - -14, 77, 32, -11, 10, -103, -15, 637, - -60, 352, 694, -202, 284, -5524, 92, -82, - 5, 140, -54, -115, 45, 287, -14, -307, - -342, 10, -181, 50, -30, -6, 10144, 77, - 42, 13, 26, -20, 34, 10, 37, -37, - -47, 90, -5, -44, -85, -64, -51, -1, - 16, -152, -91, 212, 4, -25, -237, -6124, - 22, -120, -1, 171, -17, -43, 141, -13, - -57, -185, 80, 273, -493, 178, 45, 11, - -57, 16, -23, -30, -37, 82, 4, -13, - -130, 98, 272, -450, -161, 133, 5104, 14, - 4576, -193, 11, 55, -30, 1, 123, -265, - -84, -340, -18, 152, -24, -266, 33, -90, - -108, -639, 1662, 299, -14, -389, 4679, -226, - 21, 311, -294, 159, -209, 172, 184, 292, - -373, 169, 84, 55, -269, 1453, -50, 41, - 68, -9, -62, 35, 23, -132, 96, 58, - -122, -3956, -318, 210, -117, 678, -104, 378, - -842, 61, 2549, 37, 149, -512, 70, -2971, - 225, -411, 230, -214, 697, -58, -871, -281, - -128, -204, -37, -128, 51, -174, -405, 497, - -4455, -219, 124, -120, 63, 135, 201, -122, - -435, -677, 221, 138, 486, 535, 3153, 165, - 11, -275, 94, -100, 69, 52, -67, -742, - 212, 16, -93, -428, 863, -17, -2465, 767, - -35, -130, 97, 1387, 34, 72, -23, -17, - 2845, -90, -71, 213, 291, 87, 826, -63, - 189, 641, -256, 832, 2087, -199, -170, -193, - -62, -7, 37, -60, -4277, -43, 24, -69, - 574, -163, -113, 263, -86, 45, 171, 1075, - -154, -39, 121, 74, -132, 182, 34, 13, - -278, -41, 96, 716, -221, -626, 1205, 244, - -351, 3914, -78, -32, 2833, -150, -37, 95, - -227, -84, -3432, 57, 238, -143, -365, 39, - 27, -238, -307, -170, 124, 66, -133, 40, - 62, -19, 42, -66, 2, -80, -2, 60, - 7, 10, 263, -4987, -69, -389, 62, -53, - -66, 24, -87, 13, 34, -15, -25, -20, - 197, 9, 101, -83, -79, -156, -100, 2, - -108, 5687, -157, 878, -1728, 32, 72, -66, - 70, -2, -46, -163, 206, 17, 247, 2974, - -66, 1354, 335, 238, -249, -410, -553, 354, - -41, 132, -96, 68, 2174, -329, -58, -76, - 6, 3089, 284, -274, -398, 471, 283, 427, - -220, 81, 2676, 40, -23, -46, 251, 109, - -3059, 50, -25, -551, 124, -389, 228, 95, - 56, -1320, -79, 1027, -4938, -105, -82, 13, - -159, 52, -101, 23, -220, -77, -153, 113, - -282, 42, 185, -144, -402, 46, -144, -99, - -2862, -3432, -2, 16, -32, 23, -25, -145, - 181, 49, 6, -236, -226, -28, 234, -26, - -89, -14, -355, 146, 117, -50, 76, -10, - 441, -95, -2, 346, -242, -3745, 884, -305, - -184, 350, 18, -293, -328, 257, 109, 49, - 157, -44, -70, 35, 6, 89, -4085, -167, - -263, -59, 35, -13, 430, -212, 17, -618, - -5, -8968, 114, 41, 73, -85, 122, 5, - 38, 19, -60, 14, -36, -42, -89, 20, - 85, -17, 20, 282, -3396, -25, 3722, 151, - -183, 100, -150, 19, -221, 126, 34, -21, - 72, 28, 138, -90, 30, 162, 46, 40, - 27, 15, -55, -21, 38, 55, 32, 83, - 9675, 31, 26, -2, 4, 96, -51, 120, - -132, 213, 2106, 39, -251, 98, -2572, -429, - -331, 1436, 2078, 335, -381, 371, 299, 339, - 300, -141, -99, -303, 2952, 49, 93, 40, - -3949, -45, 50, -215, 73, -39, -165, -283, - 46, -123, -347, 23, -158, 41, 20, 41, - -46, 19, 34, 86, -8770, 40, 20, -32, - -30, -16, 77, 72, -4, 92, -34, 103, - -77, 128, -532, -314, 24, 728, 49, -36, - -178, 76, 22, -14, -164, -194, 69, 3133, - 1007, -130, -280, 2502, 482, -2, 45, -62, - -7, -94, 17, 23, -4, 9516, -27, 11, - 22, 54, -13, 2, -2, 6, -22, -63, - 67, -686, 130, -2180, -124, 57, -61, -158, - 3364, 518, 4, 315, -367, -103, -295, 259, - -597, 56, -6, 72, -86, -45, -13, -47, - -13, -27, -3, 48, -12, -52, -6, -14, - -26, -16, -34, 9554, 80, 91, -270, 1, - -121, 117, 33, 8, 40, -99, -79, 43, - -3451, -92, -70, -57, 43, 68, 64, 284, - -639, 458, 118, -54, -2755, 370, -66, 54, - 27, -198, 331, 115, -40, -209, -312, 82, - -16, 8, 230, 212, 1853, -94, 1957, -118, - 153, -13, -73, 71, 116, -72, -3285, 106, - 19, -121, 177, -300, 455, -29, 94, 190, - -21, -8, 201, 16, 2, 83, -6280, 32, - -18, 59, -18, -41, -132, 22, 1, -39, - -212, -198, 186, 3154, -102, 3463, -280, -118, - -132, -132, 63, -19, 353, -24, -77, 224, - 82, 143, -65, 165, -16, -3774, 3543, -28, - -44, 93, -45, -13, -24, -5, -40, 58, - 3, 89, 71, 113, 46, 62, 44, 160, - -77, -8, -59, -6505, 134, -42, -73, 0, - 85, 2, 16, 34, 157, -34, -60, 78, - 24, 64, 96, 478, 231, -125, -217, 13, - 21, 44, 83, 198, -69, 21, -167, -52, - 4085, -234, -393, 17, -446, -354, -28, 42, - 53, -37, 28, 15, -16, -10, -85, 9471, - -16, -89, -87, -56, 52, -97, 86, -7, - -103, -12, 71, -39, 17, -40, 23, 63, - 65, -19, -14, -106, 29, 9707, -1, -12, - 1, -86, 100, 7, 1097, 266, 252, 197, - -64, -214, -197, -28, 3843, -1577, 310, -117, - 594, 13, 90, -309, -384, 134, -90, -194, - -316, 2884, 156, -185, 196, -103, 75, 1009, - 69, 768, -75, -605, -1488, 389, 242, 368, - 278, -122, -2500, 121, 7, -303, 91, -10, - 3642, 23, -109, -13, 138, -405, 18, -43, - 3, 42, 194, -112, 237, -2241, 23, 296, - -83, -14, -58, -163, -8, -174, -239, 85, - -108, -82, -79, 344, 236, -427, 127, 52, -}; - -static const int16_t cb1110l1[] = { - -64, 11, -74, -96, 39, 6072, 16, 46, - -215, 137, 77, 128, -195, -192, -87, 96, - 379, -73, 367, 437, -366, 84, -155, -29, - -69, -61, -34, -129, 260, -177, 3738, 739, - -221, -14, -40, 2, -483, -269, 2664, 166, - 29, -256, 30, 92, 51, 111, -45, 3893, - 90, -30, -99, 12, 74, 201, -52, -96, - -196, -85, -36, 123, -44, -68, 2, 8666, - 33, -41, 24, -12, -52, 69, 59, -27, - 38, -148, -55, -20, -60, 50, 3363, 30, - 3749, -92, 228, 173, -239, -167, -75, -79, - -86, -217, 32, 34, -137, -13, 17, -128, - -1462, -170, -224, -393, -3383, -1243, -47, 24, - -223, 26, 311, -343, -47, 784, 459, -548, - 558, 983, 103, 269, 32, 13, 19, -84, - -37, -29, -47, -6286, 7, 48, -100, 13, - 11, -271, -86, 115, -17, 183, 3247, -3336, - 57, -67, -117, -87, 19, 74, -271, 237, - -24, 242, 49, -179, 298, 85, -69, 328, - -238, -34, 103, -50, 79, 2, -27, -16, - -103, -61, 5868, -105, -262, 74, -74, -158, - 263, -110, 154, 212, -3, -84, -126, 25, - -67, -2501, -12, -35, 139, 259, -95, -141, - 137, 90, 12, -244, -142, 314, 15, -124, - 1, -25, -27, -2, -6, 28, -48, -17, - -2, 43, 67, 42, 9023, -25, 19, -13, - -23, -43, 73, -30, 143, -1, 2884, -142, - -4, 3549, -49, -366, 110, 314, 19, -55, - 363, 204, 469, 189, 217, -181, 119, 41, - -133, 29, -55, -94, 71, -49, 41, 85, - -14, 6140, 71, -142, 10, 18, 169, 136, - 282, -49, 36, 446, -99, 263, 92, 2201, - -127, 43, -143, -350, 36, 389, -208, 15, - -3610, -275, 383, 1599, -179, -177, -1100, -4, - 67, -38, 2, 278, 39, 107, -120, 465, - 204, -397, 305, 416, 7, -262, 68, 2341, - 189, -75, -23, 25, -20, -74, 56, -43, - -125, 170, 509, 63, 26, 263, -741, -31, - 8, -296, 101, 20, -149, 2846, -218, 379, - -310, 151, 901, 84, -85, -83, -387, 161, - -3102, -158, -438, 38, 191, -58, -202, 127, - 126, -88, -430, -3077, -1829, -332, 61, -152, - -14, -32, -156, -5, -375, -1083, -5130, 110, - 77, -201, -15, 4, 13, 86, 119, 67, - 149, 80, 264, -253, -121, 63, 193, -103, - -129, 63, 120, -226, -100, 3196, 72, -11, - 8, -56, 279, -73, -192, 47, -87, 125, - -43, -108, 277, 188, -107, 289, 5966, -20, - -303, -78, -21, 40, -139, 44, 28, 6, - -254, -244, 47, -1, -151, 29, -344, -2318, - 30, -3767, 114, 84, -155, 85, -90, 155, - 111, -506, 6, 453, -241, 215, 131, -802, - 15, -343, 176, -430, 251, -74, 6, -41, - -44, -131, -105, -248, 346, 39, -4524, 93, - -120, -79, -777, -416, -570, -221, 21, 28, - -52, 56, 71, -187, 2949, -2531, 666, 799, - -137, 970, 243, -695, -148, -281, 326, 450, - -734, -99, -2078, 112, -83, -90, -78, 262, - -138, -31, -5, -74, -171, -99, 344, 143, - 4035, 56, -121, -921, -8, 46, 4576, 97, - -219, -34, 123, -44, -1, 85, -36, 399, - -260, -231, 132, -318, 55, -181, 156, -3093, - 142, -9, -3418, -31, 43, 126, 136, 309, - -50, -20, 170, -90, 188, -173, 175, 50, - 144, -244, 22, 64, -476, -22, -66, 272, - 3839, 715, -188, -82, -250, -587, 10, 368, - -507, 242, -40, -531, 451, 35, 560, -107, - 138, 15, 113, 56, 242, 33, -23, -27, - 81, -157, 301, -327, 359, 3648, 62, -1489, - -167, 136, -39, 183, 53, -151, -16, -60, - -65, -5182, -17, -257, -10, 56, -104, 713, - -2, 328, 72, 353, 43, -51, -5949, 40, - 32, -82, -36, -22, 57, 56, 55, 112, - -104, 76, 5, 80, -29, 173, -360, -113, - 42, -119, 180, -26, 120, 250, -3024, 198, - 115, -140, 22, 136, 275, 698, -149, 699, - 426, -220, 279, 63, 55, -63, -108, -51, - -70, -70, 419, -156, 5870, 33, -57, -114, - -388, -213, -164, 1543, 117, 165, 1944, 223, - -83, 46, 201, 12, -103, 228, 139, -207, - 136, -1218, -544, -723, 90, -652, 793, -1, - -100, -32, -236, 49, 164, 138, 16, 82, - -3221, -62, -168, 62, -313, 98, -652, -484, - 684, -91, 33, -2926, -3453, 566, 34, 35, - 104, 13, 189, 235, -49, -324, 126, 226, - -102, 123, -253, -403, 38, 160, -5, 100, - -30, 16, -19, -44, 2, -70, -30, 82, - 118, 6, 132, -15, -36, 59, -8835, -448, - 3707, 324, 87, 67, -110, 114, -76, 294, - 354, 7, 140, 11, 340, -117, -559, 67, - 129, 201, -314, 328, -209, 102, -121, 378, - -5010, 140, 53, 15, -253, -14, 414, -183, - -70, -25, -51, 34, -347, -171, 146, -98, - -101, -3, -99, 96, 66, 50, -5, -115, - -23, -45, -351, -4202, 143, 480, -46, 140, - 17, -6312, -110, -23, 150, 60, -39, -9, - -48, -60, -8, -20, 37, 57, -162, 60, - -137, 55, -101, 65, 100, -8952, 3, -49, - -3, -9, 28, 15, -89, -136, 59, 125, - -73, -35, -111, -69, -28, 111, -16, 48, - 27, 9272, 55, 34, -92, 66, 3, 3, - -38, 12, 59, 95, -100, 3, 51, 121, - 146, -200, 142, -254, 65, 3, -169, -8, - -65, 44, 10, 15, -99, 56, -6, -108, - -20, -5461, -89, 395, 2085, 486, -48, 324, - 422, -3703, 468, 198, 239, 0, -277, -115, - -227, 227, -29, 159, -128, -447, -291, -1953, - -110, 25, 2274, 141, 177, 204, 38, -258, - 90, -8, -131, -2636, 55, 561, -99, -220, - -33, 142, -334, -160, -117, -12, -33, 6, - 72, -3, -11, 50, 1, -45, 8, 23, - -15, -33, -15, 30, -32, 107, 145, 14, - 60, 114, 45, 24, 8811, -9, 61, 192, - 16, 124, 46, -54, -31, 89, -147, -112, - 3341, -395, 91, -323, 45, -156, 25, -18, - 34, -534, 118, 83, -187, -92, 180, 34, - 659, 135, 103, -2342, 54, 6, 179, 40, - 143, 232, -3858, -201, 179, 32, -56, 406, - -236, 541, -70, -88, -121, 447, 3028, -223, - 138, -557, 230, 3457, 96, -4, -22, -13, - -136, -45, -123, -8, 107, 270, 132, -64, - -32, 464, -33, -44, -2544, -251, -246, -71, - -4063, 40, 107, 384, -22, -197, 64, 166, - -137, -44, 98, -35, 193, 4, -2103, 57, - -109, 245, 3487, -55, -60, 21, 187, -267, - 279, 3, 166, -78, 108, -135, 126, -122, - 171, -133, -21, -134, 183, 25, -56, -6210, - 107, 109, 22, -93, 39, 95, 43, -11, - -44, -5, -82, 6, -54, -27, -116, -16, - 84, 44, 22, -68, -1, -57, 78, 35, - 83, 4664, 46, 1, -164, 3301, -358, -3757, - 236, 104, -81, -121, -278, -112, -20, 89, - -123, 35, 113, 17, -331, 273, -172, 125, - -73, 77, 2515, -3944, -170, -87, 174, 84, - 142, 138, 13, 227, 127, 146, 141, 196, - 38, -40, -112, 136, 2311, 328, 87, -22, - -77, -34, -195, 58, -333, 337, -159, 626, - -3008, 408, 523, -316, 539, -587, -81, -2824, - 98, 200, 613, -107, -170, -1190, 1121, 521, - 229, -217, 143, 144, -1248, -384, 1535, 470, - -655, 492, -429, -26, -132, -180, 52, 97, - 10, -35, -60, 7, -5422, -26, 154, -132, - -221, 124, 136, -17, -68, 25, 29, 4, - 5, -15, 9, 69, -16, -47, -76, 5, - 41, 6, -22, 63, -8, 9709, -33, 650, - -545, -159, 81, -75, 54, -92, -49, -80, - 14, -78, -145, -399, -3935, 186, -1144, 207, - 60, 286, 2642, 44, 117, 3758, -154, 426, - 331, -615, -216, 271, -121, -109, 495, 42, - 813, -19, 545, -149, 633, -2424, -2089, 265, - -136, -58, 4, -28, 147, 2, -123, -93, - 14, -50, 317, 131, -130, -152, 322, 1023, -}; - -static const int16_t cb1110s0[] = { - -6433, 495, -277, -630, 411, 1241, -326, -425, - 523, 114, -225, -53, -538, -702, -260, -417, - -401, -222, -263, -416, 163, -1256, 590, -1176, - 1865, 1483, -927, -65, -674, 1303, -147, -750, - -132, 407, -283, 852, 1788, -2257, 210, -450, - 303, -272, -2536, 94, 2010, 428, -921, -3, - -71, -875, 156, -681, 521, 49, 51, -523, - 1532, 1619, -690, 402, -923, 318, 865, 193, - -2187, -662, 553, -1104, -70, -1313, 462, -1045, - 320, 937, -1453, -514, 404, -231, -1748, -1592, - -2039, -217, -364, -1313, -428, 2419, 1257, -1292, - 19, 2867, -278, -1832, -239, -691, -383, 62, - 185, -455, -1589, 116, 419, -319, -418, 537, - -280, -1834, 2681, -857, -210, -156, -1143, -104, - -1774, 1702, 184, 1017, -135, -610, 525, 335, - -355, -494, -231, -154, 986, 434, 1134, 1213, - 914, 1457, -258, -1086, 477, -2247, 498, -1741, - -975, -262, 812, 108, 834, -412, 120, -1032, - -533, -456, 139, -301, -387, -690, 798, 3, - -1556, 1261, 745, -4486, 8, 213, 977, -151, - -269, -344, 13, 544, -270, -166, -706, 672, - 184, -943, -1714, 1510, -739, 1891, -477, 528, - 1847, -1572, 420, 103, -85, 508, 231, 2024, - -1343, 20, 238, -655, 668, -1561, -743, -651, - 709, -1136, -208, 979, 258, -693, -535, -1126, - -283, -944, -209, 603, -1797, -2998, 253, -296, - 842, 63, -203, -468, 675, 337, 1458, 114, - 259, 3202, 145, 419, 631, 352, 2309, 1337, - 815, -99, -824, -779, -1839, -1455, 166, -2092, - 1299, 162, -1026, -914, 128, 1321, 896, -209, - 255, -1144, 807, -2870, -632, -588, 866, 81, - 453, 154, -1258, -499, -452, -98, 2599, 3070, - 540, -834, -228, -1268, -313, 1269, -65, -56, - 1035, -499, -507, -657, 447, 26, 96, -175, - 133, -291, -538, -259, 7, -206, 411, 145, - 25, 215, 267, -4354, -442, 250, -814, -143, - -459, -182, -640, -1258, 169, 379, -1196, 429, - -128, -1971, 2681, -45, 1641, 152, -556, 909, - 365, -618, -417, -363, -434, 270, -1388, -473, - 62, 58, 509, -3909, 1327, 1571, 482, 1081, - -896, 459, 480, -557, -267, 390, -15, 484, - 248, 52, 49, 702, -10, 162, 245, -416, - 1397, 23, 183, 325, 591, -816, 4429, 674, - -332, -1243, 68, 285, 235, 759, -315, 799, - 313, -331, -182, -629, 394, -1079, 3879, -81, - 651, -774, -21, -297, 231, -1826, 47, 104, - 284, -171, -198, -110, -193, 881, -715, 294, - -490, 395, -1261, 2859, -3175, -1477, 668, -215, - 310, 10, 762, -837, 101, 142, 201, -940, - 453, -82, 493, -983, 23, -211, 990, 1327, - 4664, -27, 821, 809, 500, 243, 41, 568, - 44, -320, 105, 461, 306, -408, -793, -35, - -18, 229, -12, -416, 577, -301, 4870, -520, - 499, 57, -544, -21, 611, 226, -20, -412, - 440, -680, 448, 430, 226, -610, -310, -218, - 1161, 523, -400, -148, 783, 395, -126, 370, - 686, -497, -301, 161, -5, 238, 375, 357, - -126, 954, 5952, -53, 121, -405, 1571, 435, - 461, -1166, -1163, 1347, 1394, 170, 2035, -1580, - -958, 276, -680, -968, 275, -323, 524, 48, - -1896, 46, -495, 548, -929, -859, 224, 1079, - 863, 3080, -1594, -379, 302, -403, 710, 655, - -293, -719, -683, -944, 228, -341, 563, -495, - 920, 738, -614, 552, -249, -402, -164, -262, - -425, -4025, 164, -984, -518, 157, -1156, -729, - 1024, -768, 1003, 481, -116, 319, -918, 1563, - -662, 4852, 617, -250, 549, -265, -93, 680, - 470, 925, -293, 629, 142, 231, 44, 133, - 12, 40, -867, 269, -77, 445, -1132, -985, - -1304, 728, 424, 530, -258, -625, 377, -1400, - -2538, -470, -1711, 413, -1603, -81, -393, -1013, - 1130, 906, 287, 640, 3785, -463, -159, 43, - -165, -441, -513, -287, -554, 1547, 848, -275, - 936, 653, 769, -58, -1007, -698, -792, 2175, - 398, 1382, -122, 459, -7, 281, 2785, -637, - 632, -279, 293, -1078, -996, 96, -293, -1335, - -74, -587, -286, -565, -977, -228, 5080, 3, - 171, 111, -34, -177, -619, 577, 448, -280, - 189, 1033, -579, 134, -713, -947, -249, -1897, - 364, 1748, -2098, 21, 859, -73, -1881, 116, - 36, 1591, 1386, -1128, -346, -1015, -25, -90, - -691, -984, -120, 29, -635, -236, 26, -691, - -742, -203, 294, -472, -901, 2582, -171, -357, - 406, 162, 1561, -913, 308, -3319, 461, 779, - -305, -927, 290, -941, 615, -688, -508, 222, - -432, 387, 170, -115, -5338, 508, -212, 150, - 26, -38, 306, -15, 50, 2008, -1112, -187, - 44, 591, -280, 1187, 934, -228, 554, 65, - -1387, -1999, -805, 2555, -1225, -283, -435, -430, - -50, -655, -103, 248, -234, 32, -826, -708, - -704, -1006, 176, 784, 274, 626, -2353, 707, - 1852, -132, -196, -169, -463, -2117, 56, 413, - -141, -818, -365, 921, -816, -126, -135, 438, - -948, -145, -349, 700, 205, 1001, -3626, 314, - -493, -1182, 131, 733, 2404, -1244, 564, -960, - 328, -1137, -108, -755, -168, -995, 966, -1706, - -565, 806, -693, 1369, -269, -428, 675, 768, - 341, -794, 2265, -208, -1883, -801, -1889, 961, - 182, -504, -595, 871, -1280, 952, 1351, 665, - 474, 1032, 58, 451, -198, 345, 176, -853, - -2891, 2250, 624, -616, 183, 144, 736, 0, - -198, -138, -1218, -501, -658, -24, 1232, -286, - -233, -937, 2150, -1035, 449, -623, -2748, -2176, - 918, -170, 421, 1376, 93, 153, 627, 493, - 28, 549, -292, -175, 1066, 1037, -475, 413, - -2006, -2022, -334, 365, 901, 945, -663, 515, - -351, -597, 155, 1318, -153, 417, -425, 44, - 338, -1958, -355, -596, -2134, 360, 341, 2501, - 824, -2106, -282, -1723, -735, -550, -743, 113, - 1027, -479, -2114, -16, -631, -282, -1054, 1320, - -158, -234, 3479, 28, 1818, 627, 1464, -795, - -22, 897, -6, 392, -234, -170, 714, -382, - 1262, 67, -618, 145, 25, -710, -247, -545, - -1386, -1797, -995, 865, 465, -364, 830, -53, - -1108, -383, -538, 85, 731, -188, -813, 2, - -1667, 3379, 289, 425, 1319, -259, -592, -212, - 271, -268, -126, 1282, 306, 3859, -1423, 607, - 20, 755, 174, -782, 72, -234, 675, -1177, - 1101, -635, -1641, 2574, -978, -1390, -1743, 2183, - 53, 75, 650, -97, -456, -126, -719, -675, - 557, -375, 643, 853, -81, -192, -1174, -1288, - -954, -883, -806, -2182, -2111, -1426, 180, -266, - -301, 626, -443, 61, -149, -443, -935, -48, - 642, 250, 17, 596, 1342, -2127, 323, -1456, - 1995, 837, -1456, -1683, 945, -722, -1445, 452, - 178, -441, -250, -137, -128, -50, -311, -600, - 2237, 922, 139, -107, -637, 1770, -2503, 413, - -803, 496, 209, -391, 401, 412, -552, 605, - -37, -667, -1609, -19, -1073, 1522, -705, 670, - -992, 882, -1213, -854, 2150, -371, 73, -1167, - -592, -153, -509, -584, -495, -83, 2075, -1489, - 719, 1245, -1138, 72, 950, -950, 542, -590, - 988, 1646, -64, 562, -223, 73, 583, -151, - 215, 914, 1391, -2997, 161, 436, 49, 2225, - 271, -283, 3844, -578, 335, -90, -698, -162, - 1236, -117, 470, 383, -718, 520, 295, 29, - 292, -179, 774, 204, 372, -251, -824, -487, - -1822, -312, -731, 568, -1008, -255, 189, -1195, - 657, -227, 3422, 651, -220, -1204, -590, 713, - 365, -977, 204, 3118, 321, 922, -347, 1505, - 375, -77, -1520, -1411, -680, -507, 543, -492, - -1844, 135, 689, 384, -408, 140, 633, -1192, - 475, 220, -1711, -1318, 606, -103, -712, -1734, - -218, -855, -835, -3071, -109, 1391, 62, 21, - -75, -77, 369, 216, -1484, 2057, 661, 314, - 275, 1048, 175, 1842, 743, 808, -594, 338, - -1217, 1606, -531, -1360, -1073, 452, -531, -798, - -771, -1292, -918, 606, -1776, -509, 178, 1422, - 3424, 634, 722, -257, 525, 437, -197, -130, - 291, -411, -259, -890, -84, 368, 1117, -1321, - -324, -2122, 515, 1158, 1749, -963, 681, 39, - 268, 549, 324, -601, 151, -200, 829, 3881, - 797, 660, -572, -693, 633, 1023, -147, -581, - 102, -207, -163, -511, -30, -102, 379, 776, - 494, -510, 55, -1811, 1073, 4384, -318, 3277, - 1958, -209, -539, 1823, 1200, -182, -186, 213, - 123, 506, -471, -431, -698, -331, -1168, 88, - 276, -184, 733, -295, -1053, -717, 862, -1453, - -4235, 1063, 1049, -621, -429, 372, 1043, 599, - 271, -693, -689, 122, 466, -323, 332, -533, - 645, 516, -371, -207, -2046, 72, -1125, -229, - -2769, -330, 1387, -89, 342, 2786, -730, 152, - 629, 809, -459, -248, -266, 111, 380, 724, - -411, 640, -72, 323, 34, -277, 443, 289, - 151, -4816, 402, -171, -731, 635, -84, -133, - -310, 397, 904, 1193, -1512, -25, -1306, 587, - 322, -3762, 537, -306, -981, 917, 190, 787, - -613, 149, 301, -376, 366, 350, 18, 893, -}; - -static const int16_t cb1110s1[] = { - -332, 1306, 1626, 1555, -3510, -225, 418, 1520, - -969, -74, -286, 233, -313, -97, 375, 181, - -309, 1348, 969, -504, -141, 789, -1224, -137, - -704, 98, 1003, 466, 2259, 1485, -225, 61, - 272, -223, -347, -23, -368, 96, 2345, 112, - 363, -552, -6, -806, -1637, -1703, 1597, -2114, - -196, 293, -1173, -630, -863, -1224, 784, -722, - 744, 885, 798, -384, 92, 298, -873, 1808, - 1389, 488, -1569, -1541, -3064, -734, 3, 467, - -987, 346, 1915, -683, 205, -487, 341, -330, - 274, -25, 49, -83, 1246, -405, -777, 266, - 121, -250, 466, -1232, -3197, -871, -638, -332, - 1563, 1900, -470, 556, -465, -412, 901, -86, - -683, -577, -1033, 808, -863, 1212, -724, 2222, - 429, 2733, 413, 891, 1669, 515, -439, 187, - -359, 414, 176, -706, 679, -63, 1247, -1721, - 779, -2770, -484, -633, -993, -243, 1442, -312, - -324, -370, 392, -407, 229, 97, 1267, -18, - 46, -303, -684, 515, -166, 4212, -775, -23, - -53, 23, 1966, -465, 231, 1195, 252, -1036, - 16, -824, -116, -582, -286, 470, -159, 217, - -456, 549, 648, 60, -1119, 221, -747, 354, - -628, -486, 894, 1280, -2631, 247, 430, -1703, - 69, -236, 147, 1445, 540, -936, 181, -163, - 931, -1044, 669, 2457, 519, 597, -2031, 11, - -1319, -4, -1190, 85, 254, -1494, 230, 1583, - -547, 277, -2006, -103, 1195, -2522, 1301, -633, - -104, -511, 573, 1628, -451, -1022, 564, -692, - 255, 1029, -408, 757, 172, -395, -472, -1703, - -1856, -379, 289, 509, -628, -1349, -207, 404, - -399, 1671, 392, -935, -190, 952, -1267, 1150, - 1562, -609, 491, -346, -270, -483, 310, 1420, - -1017, 1714, -645, 897, -1327, 3154, -1046, -857, - -499, -496, -1348, 399, 63, -653, -315, 820, - 1645, 614, 2202, 779, 3001, 1382, 387, -843, - -1840, 422, -1017, 246, -219, -550, 105, -608, - 426, -346, -224, 375, 22, -448, -270, -1150, - -897, 4298, -882, 49, 633, -937, -694, 675, - -322, -793, -516, -360, -248, 1190, 575, -843, - -13, 50, -801, 1181, 452, -335, -495, -102, - -1057, 506, -206, 66, -647, 991, 259, 259, - -468, 197, 373, -4216, -750, 224, -182, 520, - -530, 1888, -2018, -1492, 656, -1447, 993, -790, - -785, 792, 1658, 373, 131, -460, -703, 1080, - -875, -212, -694, 747, -639, -2267, 1263, -415, - -749, -1278, 591, -745, -225, -1677, 69, 625, - -146, 212, 345, 728, -553, 1117, 471, 550, - -498, -729, -2070, 1006, -330, 939, 3636, 34, - 349, 761, -131, 372, 610, -399, 10, 86, - 110, 931, -1159, -175, 633, 568, 140, 712, - 2800, -1558, 2343, 3, -974, -673, 233, 1436, - -783, 599, -442, 852, 639, 447, -976, -564, - 1511, 36, 529, 433, 677, 1971, 2777, -820, - -655, -1463, -1392, -1142, -352, 432, 730, 439, - -273, 844, 108, 115, 408, -361, 504, 337, - 58, 1074, -1645, -1623, -493, -70, -1585, 2878, - -741, 636, -224, -974, 722, -147, 149, 135, - -107, -154, -1027, -18, -989, 282, 3173, 1123, - -778, 1389, -591, 337, 1660, -288, 1162, -65, - 660, 326, 141, 358, 679, -222, 460, 105, - 512, 36, -854, -477, -942, -2362, 265, 2252, - -164, -2059, 106, 666, -420, 521, -178, 396, - -1836, 475, 82, 356, 207, 433, -1005, 97, - 385, -304, -853, 1282, -239, -2134, 83, 84, - 201, -1894, -1603, 683, -1957, -113, 839, 1187, - -313, 774, -754, 941, -739, 748, 116, 716, - 1134, -530, -2178, 71, -611, 1544, 3527, -3, - 283, 527, 457, 399, 762, 17, -279, 196, - -518, -160, -1204, -289, -1354, 132, -315, -290, - -2179, 676, -1474, -1010, -1397, 363, -45, 783, - 1326, -33, -109, -617, -271, -967, -103, 1867, - 769, 740, -818, 1011, 1411, -693, -2458, 808, - 806, -213, 468, 31, -70, 166, 230, -405, - 163, 70, 652, 1077, -190, -622, 2343, -1328, - 601, 928, -1661, 174, 429, -2479, 501, 503, - -41, 1365, 671, 1006, -1968, 7, 103, -399, - -382, 573, -27, 554, -2263, -3174, 277, 177, - 807, -328, -816, 453, -1548, 828, -327, 187, - -393, -745, -76, -808, 575, -8, -326, -2062, - 601, 566, 755, 775, 595, 419, -3925, -226, - 272, 368, 395, 59, 1117, 548, -649, -429, - 321, 549, -744, 319, 82, 135, 73, 14, - 374, 93, -270, -453, 177, 4991, 569, 169, - 111, -246, -362, -88, -49, 583, -35, 60, - -759, 1327, 1768, 766, -350, -880, -106, -449, - -113, -683, -418, -999, 992, 559, -290, -147, - -324, 93, -947, -3932, -37, 307, 1087, -314, - -293, 432, 830, -130, -208, 59, 719, -348, - 4511, 224, 488, -174, 588, 795, -301, -246, - -447, 682, 917, -1207, -503, -450, 575, -116, - -126, 594, -22, -101, 5, -1188, -431, 1146, - -3869, -72, 402, -417, -390, 350, 1141, -138, - 697, 77, -3255, -268, -786, -106, -1386, 400, - -856, -691, -438, -1550, -228, 2162, 236, 64, - -382, 1, 1032, 153, -659, 1563, -410, 1280, - 1573, -3675, -1041, 240, 401, 215, -353, -1140, - 265, -103, -824, -93, -319, -849, 253, -477, - -463, 153, -1017, 538, 1233, -1041, 11, 998, - -437, -569, -970, 2118, -1577, 1, 321, 1784, - -298, 2315, 72, -20, 83, 905, -1289, -246, - 731, 4076, -1477, 602, -911, 978, 698, -239, - 391, -729, -276, 225, 143, -417, -500, -27, - -1220, 89, -403, -1453, -2546, 1015, 70, 78, - 2364, -159, -775, 29, 37, -231, 73, 433, - 426, -529, 420, -613, -100, -605, 1463, 1001, - 1159, -4082, -553, 348, -806, 624, -162, -1121, - -25, 919, -62, 90, -275, 233, 203, 32, - 745, -221, 458, 529, 901, 1088, 38, 1209, - 450, 451, 2250, -411, -205, 761, 249, -1226, - -266, -3195, -801, -31, 1015, -324, -596, -42, - 150, 207, 2597, 1041, -1045, -2254, -1428, 250, - 217, 69, -933, 1424, 280, 446, 524, 540, - 639, -1027, 23, 412, 36, -67, 475, -1126, - -739, 1160, 514, -157, -2832, -1432, 559, 77, - 740, -888, 134, 1304, -267, -267, 329, 8, - 1721, 1488, -29, -1760, -1904, -2634, -1342, -528, - 2233, -219, -194, -2919, 128, 1203, -623, -127, - 488, -386, -133, -329, 62, 85, 1271, -185, - -479, -588, -2964, 546, 1651, 1526, -830, 1046, - 347, 63, -1048, 239, 1402, -22, 307, -1606, - 768, 999, 304, -512, -175, -246, -373, 529, - 93, -521, 1310, -508, -4366, 27, -768, -358, - -575, -2, -593, -21, -838, 635, 197, 634, - 321, -263, -377, -549, 20, 739, 395, -9, - -392, 70, 5679, -133, -130, -240, -678, 421, - -101, 412, 143, 209, 194, 216, 200, -22, - -748, -399, 2863, 284, 231, 691, 571, -3460, - -200, 312, 480, -1338, -603, 435, -308, -615, - 520, 178, 68, -716, 45, -593, -32, -1393, - -554, -1000, -867, 613, 288, 507, 202, -113, - 17, 93, -141, -47, 665, 559, -808, -4091, - -575, -193, -873, -790, 673, -608, -941, 745, - 1562, -1060, 988, 1192, 29, -1207, 207, 653, - -622, -132, 370, 1435, 1977, -1878, -119, 101, - -100, -154, -869, -2375, 1254, 122, 188, 877, - 188, -838, -355, 667, 3813, 1076, 369, -771, - -712, -669, -14, 107, 1027, 112, 2306, 1418, - 133, 1055, 377, 249, 1023, -927, 12, -1983, - 1174, 223, 385, 827, 1425, -1694, -1178, -94, - -593, -286, 1263, -671, -425, 2002, 701, 1546, - 547, 182, 1013, 128, 351, -243, 407, 2349, - -376, 445, -93, 968, -337, -601, 1342, 987, - -1499, -644, 521, 327, -557, 1800, 12, 285, - 127, -269, -1989, -449, 87, -1042, 184, -499, - 1231, -1664, -352, 4, 1253, 403, -1064, 837, - -1702, 133, 1687, -1300, 2248, 179, -847, -617, - 460, 450, -260, 94, -780, -675, 1209, 38, - 453, 857, -631, 317, 535, 1086, -196, 638, - -288, -389, 688, -93, 1271, -4290, -96, 445, - 64, -211, 148, -74, 486, -1873, 1214, 1836, - -708, 1800, 1644, 576, -1088, -1212, 1147, -456, - 173, -911, 489, -443, 644, 534, 846, -1522, - -786, 497, -401, -1087, 1410, 1391, 837, -253, - 124, -598, -254, -3945, -1169, 103, -193, 50, - 846, -1014, 353, 455, 784, 1343, 3055, 178, - -628, -148, -266, -324, -96, -190, -930, 115, - 475, -651, -314, -82, -236, -88, -3753, -1048, - -283, -178, 351, -671, 325, 1054, 28, 540, - 113, -73, 763, 844, 543, -6, 799, 245, - 176, 124, 262, -112, 1010, 361, -843, 3290, - -3741, 914, -1835, -259, 2467, 297, -1205, 168, - -1917, 156, 87, 637, -677, -955, 312, 1246, - -219, 92, 1090, -292, -773, 343, -523, 299, - -513, 1321, -536, 586, -1324, 2345, 2384, -719, - -936, 1389, -27, 880, 338, -127, -666, -441, - 1603, 143, -218, 2167, -1335, 469, -1224, 2489, - 1365, 568, 19, -1322, -736, 208, -494, -454, - 990, -250, 305, -575, 206, -168, -1177, 282, -}; - -static const int16_t cb1110m0[] = { - 429, -104, -210, 216, 361, -2586, 253, -1350, - 145, 2795, -5, 663, -262, 37, -122, 205, - 270, 321, 2623, 256, 4, -42, -37, 112, - -346, 20, -51, 9, -90, -3342, 78, 52, - -239, -454, -207, 355, -136, -19, 394, -212, - -166, -73, -68, 1049, -2945, 385, -545, -211, - 116, -15, 687, -232, 1824, -66, 133, -403, - -63, 3, 46, -104, -101, 136, -61, 420, - 149, -24, -9, 4277, -149, -166, 96, -35, - 1786, -1044, 115, -1326, 3381, -520, 70, -134, - -433, -198, 146, -615, -143, 201, 342, 412, - -162, 22, 111, 16, -85, 14, -120, 79, - -30, -84, 56, -34, -52, -147, 19, 155, - 17, -120, 5853, 96, 767, 262, -194, 124, - -180, 13, 3081, 39, 402, 90, 292, 84, - 1999, -16, 866, 292, 416, -314, 177, -1, - 68, 3, -28, -56, -54, 10, -5, -63, - 89, -69, -251, 70, 7523, -83, 67, 62, - 178, -1723, -76, 101, 369, -139, 58, 135, - -32, 138, 3393, -575, 586, 292, -296, -505, - -634, 52, 280, 78, 14, 117, -39, 77, - 231, 136, 14, 51, 173, -96, 5, 378, - -52, -4340, -263, 61, 22, -2896, -20, 180, - 21, 3636, -138, 104, -279, 56, -407, -8, - -123, 134, -95, -500, 266, -64, -43, 1, - -170, 31, 110, 53, 56, -5938, 151, 49, - -76, -166, 34, -8, 193, 198, -118, -4, - -44, 249, -28, -102, -3614, 49, 464, -388, - -744, -500, 603, -88, -19, 1606, 325, -227, - -277, -142, 232, -1835, 150, -89, 29, 9, - 76, 425, -320, 179, 231, 1720, 424, -2730, - -298, 666, 72, -428, -1243, -299, 93, -12, - -20, -96, -123, 18, 188, -1, -235, -2, - 3328, 107, -1489, 199, 893, -63, 46, 3799, - 22, -118, -127, 283, 254, -2091, 293, 331, - 857, -92, 46, 13, -457, 169, 851, -19, - -231, -8735, -62, 69, -190, -103, -31, 108, - 66, 95, 53, -6, 12, 19, -73, 105, - -40, -29, 60, -263, -107, 2233, -246, 485, - 342, 1732, 76, 2489, 40, 44, -300, 280, - -109, -107, -990, -45, 1014, -5073, 1, -169, - 25, -55, -340, -427, 603, 206, 151, 360, - 312, -44, -106, 514, 683, 98, 3331, 19, - -106, 106, -3383, 85, -161, -88, 8, 12, - -163, 183, -393, 117, -243, -498, -60, 292, - -322, -2105, 920, 301, 41, -19, -142, -2485, - 631, -289, -849, 132, 800, -255, -390, 137, - -850, -411, 41, -93, -8653, 9, -25, 134, - -66, 222, 152, 59, 29, -193, -129, -105, - 39, -21, 188, 111, 25, -3, 0, -79, - 8907, -24, -18, 37, -33, -42, 87, -44, - 56, -79, -67, -52, 18, -132, 1925, 309, - 145, -443, 1279, 200, 1215, 281, 3343, 311, - 390, -154, -119, -523, 19, -529, 190, 272, - 541, -393, 278, 161, 13, 161, 891, -65, - -199, -1376, -350, -1409, 340, 2115, -209, 2459, - 30, -509, 141, 11, -557, -1560, -1912, -234, - 76, 787, 2781, 45, -158, 330, -623, 655, - -845, -463, -119, -252, -299, -1940, 145, 17, - -183, -71, 98, 67, 145, -134, -88, -5, - -3636, 3, 34, 231, 981, 33, -953, -403, - 129, 215, -11, 109, -188, 51, 5176, -89, - -113, 60, -138, -94, 142, 216, 322, -33, - 350, -285, 182, 92, -16, 12, 15, 126, - -27, 5, -5220, -154, 13, 109, 18, -326, - -257, 118, 313, 342, 2289, -35, -22, 115, - -256, -2908, 68, 1211, 203, -735, -380, -134, - 249, 522, 109, -48, -5114, 32, -42, 85, - -99, 265, -187, -93, 373, 341, -254, 16, - -121, -92, -260, -80, -2, -322, 234, -96, - -2834, 230, 146, -264, -3287, -153, 41, -349, - -149, -98, 140, -115, 628, -11, 292, 4, - -166, 82, -4548, 116, -23, -311, 612, -334, - 451, 259, 559, 320, -267, 517, -139, -166, - 126, 27, -89, -156, 14, 63, -3, 31, - 109, -43, 10, -7682, 36, -23, 73, 129, - 0, -116, 66, 5, 137, -17, 2523, 203, - 431, -2729, 175, 540, 454, -175, -297, -60, - 348, 53, 688, -49, 133, -72, 200, -348, - 136, -142, -2259, -3047, -60, -737, 48, -331, - 85, -134, 218, -962, -278, -148, -1077, -131, - 53, -127, -2265, 82, -31, -262, 226, -385, - 83, 756, -2715, -492, -115, 663, -312, 240, - -318, -819, 3040, -181, 148, 165, 376, 92, - -233, 188, -100, 902, -401, 1005, -52, 162, - 219, 1831, -68, -66, -10023, -90, -23, 39, - -91, -231, 23, 174, 42, 79, -57, -58, - 18, 175, 32, 122, -185, 266, 162, 300, - -3158, -3381, -3, -312, 178, -24, -234, 248, - 68, 293, 360, -146, -30, -2, 177, 113, - -1215, -538, -274, 79, -2, -17, 2791, 71, - -1300, 93, -818, -558, -331, 115, 215, -603, - -202, 113, -87, 39, -277, 3564, 75, -444, - 201, 111, -369, -1072, 212, -276, -322, -484, - -700, 37, -302, 177, 86, 10, -87, 56, - 76, -8941, -27, -73, -133, -51, -106, -28, - -52, 49, 68, 26, 16, -81, -423, 2834, - 7, -54, -107, 144, -3812, 17, -355, 3, - -32, -24, 14, 76, 169, -260, 349, -159, - 3691, -184, 4345, -46, 146, -14, 143, -384, - -75, 12, 144, 105, 47, 141, -32, -31, - 48, 187, 74, 139, 132, 86, -15, -317, - -267, 3112, 1821, -363, -125, -1152, -294, -449, - 277, 1151, -341, 12, -41, 210, -51, 6, - 18, 53, 11, 37, -36, -70, 65, 44, - -7302, 15, -133, 56, 150, 63, 515, 271, - -32, 47, 41, -130, 168, -158, -239, -60, - 226, 247, -593, -237, -3559, 65, 623, 16, - -212, 26, -181, 81, 83, 26, -25, -92, - -5, 36, -31, 277, -263, 135, 78, -173, - 220, -5260, 2239, -96, -19, -95, 75, -25, - -64, 244, -154, -2646, -446, 980, 512, 392, - -402, -1050, 276, -456, -1334, 1863, 636, -1512, - 234, 199, 237, 363, 66, 284, 198, -277, - -267, -540, -329, 856, -482, -645, 178, -240, - -178, 6633, -5, 127, -80, -167, 307, 7, - 248, 13, 53, 124, 215, -310, 255, -194, - -3066, -22, 3524, 51, 193, 165, 82, -80, - 54, -191, -278, -19, 379, 285, -58, -157, - -168, -183, 388, -198, 191, 107, 10, -2, - -6148, 45, -58, 48, -150, -72, 112, -124, - -41, -129, 36, -66, -3311, -4092, 15, -11, - 93, -54, 72, -105, 131, 66, 29, -54, - 201, -210, 221, 47, 55, -99, 31, -3626, - -3623, -175, 91, -53, 40, -98, -76, 224, - 15, 172, 85, 103, -147, -135, -214, -313, - 1304, 143, 190, 19, -2526, -91, -168, 875, - -27, 789, 791, -462, 912, -580, 70, 1523, - 787, -150, 567, 2717, -5, 2943, -107, 155, - 32, 65, 158, 133, -191, -44, 141, -149, - 199, 177, 270, -14, -57, -3669, 3891, -158, - 239, -17, 52, 244, -343, -118, 186, -54, - -134, 106, -133, -116, 186, -149, -894, -22, - -399, 1, 288, -3988, -260, 113, 66, -276, - 179, -226, 119, 420, 51, -483, 551, 129, - 245, 2013, 639, -87, 5058, 41, -53, -116, - -130, -223, -104, -760, 276, 117, 338, -137, - -233, -65, 119, 100, -3245, 2, 3877, 126, - 172, -2, -72, -153, 200, -109, -62, 135, - 194, -82, -150, 98, 550, -251, -274, 71, - 160, 121, -13, -365, 356, -212, -271, 5067, - -203, -251, 222, 75, -131, 17, 103, -911, - -348, -26, 6, 110, 120, -645, 355, -649, - -132, -3416, 65, -1478, 461, -109, 258, -15, -}; - -static const int16_t cb1110m1[] = { - -110, 2743, -31, 86, -11, 3705, 192, -89, - 57, -252, -11, -212, 163, 0, -137, 405, - -99, -124, -137, -407, 125, 106, -922, 1567, - 85, 165, 241, 110, 2918, 598, -443, 812, - 159, 518, 555, -1886, -65, -52, -3, -27, - 56, -30, -126, 126, 23, 74, 157, 6990, - -34, 56, -257, -172, 115, -23, -616, -243, - -441, 34, 159, 6, 78, -119, 49, 34, - -133, 988, -1007, 474, 77, -274, 354, 4907, - 222, -16, 69, -4, 924, -18, 3535, -299, - -38, -83, -111, 977, -138, -1075, -444, 540, - 199, 202, -502, -194, -198, 249, 101, 276, - -89, 96, -301, 6, -4023, -70, 174, 93, - 192, -120, 755, -560, -22, 78, 56, 29, - 28, -44, 65, -4, 0, 49, -250, 87, - 46, 44, -41, -7035, 14, 288, 632, -259, - -64, 20, -178, -343, -274, 106, 2842, 336, - -283, 245, -612, -5, 500, 77, 2492, -250, - 64, 171, -988, 4, -51, -34, -555, -171, - -2629, 272, 2852, -162, -98, -237, -278, -489, - 641, -96, 7815, -139, -116, -137, -121, -314, - -161, 211, 76, 136, -35, -124, -27, 76, - -98, 133, 85, 332, -4352, 507, -14, -275, - -212, 308, 258, 129, -165, -197, -104, -150, - -104, 60, 125, 568, -3, 1694, 62, -70, - 109, 122, -57, -18, 8642, 100, 50, 92, - 17, -86, -93, -68, -121, -61, -32, 27, - -188, 502, 123, -81, 37, 48, 187, 75, - -30, -22, -224, -292, 99, -49, 4273, 10, - 834, -25, 225, 2773, 78, -3281, -181, 234, - -130, -74, 101, 214, -26, -113, -268, -168, - -90, -435, -26, 38, -569, -4009, -1, 11, - 69, 3, 249, 98, 178, 131, 300, -826, - 48, 337, -828, -371, 96, 312, 712, -667, - -70, -2070, -242, 519, -676, 143, -613, 893, - -2193, 471, 1071, 213, -1231, -196, -580, 155, - 401, 78, -64, 27, -238, 22, -73, -19, - 194, 60, -87, -210, -155, 244, -123, -169, - -4442, 169, 3132, -181, 65, 3950, -396, 209, - 39, -52, -26, 166, 1, -164, 143, -66, - 169, 46, -16, -295, 39, 42, 40, 67, - 25, 17, -1, -8920, -82, -42, 49, 81, - -61, 1, 39, -40, 18, 74, 206, -131, - -71, 106, 7, 88, -13, 69, -113, -89, - 212, -4, 4373, -34, 283, 105, 252, 59, - -2578, -298, 1846, -110, -105, -310, -143, -127, - 274, 225, 861, 262, -815, -311, -26, -685, - 243, -620, -374, 2992, -112, -35, 2903, -94, - -56, -213, 65, 383, 41, 508, -258, -103, - -440, -237, 428, 132, 2793, -77, -113, -58, - -19, -3857, -25, 40, -167, -243, -233, -41, - -279, 213, -22, 8, 120, 126, 159, -212, - -244, 183, 1605, 62, -12, -244, 519, 780, - 116, -3197, -992, 341, 222, 681, -357, -669, - 55, 1213, 100, 441, 1, -57, 232, 10, - -114, 318, -147, 89, 188, 448, -327, 3735, - -292, 875, -216, 211, 111, 160, 172, 286, - -3513, -849, -185, -9, 31, 442, 747, -1045, - 187, 704, -219, 509, 48, 69, -25, -10, - 75, 23, 10, 23, -32, 89, 8628, -77, - -19, 27, 0, -232, 22, -50, -1904, -137, - -169, 128, 138, 78, -443, 243, 157, -3809, - 231, 277, -341, 73, -70, 596, 259, 157, - 2197, 575, 2445, 11, -53, 118, -115, 562, - 108, 30, -241, 30, -394, -155, -186, -344, - -237, -319, -2258, 343, -311, 14, 169, 59, - -15, 233, 732, 365, -692, -108, 1416, -463, - -279, -248, -1731, -406, -278, 298, 209, 5333, - -198, -167, 50, 439, 142, 91, -523, 226, - 262, -130, -15, 573, -4, 271, -2, -47, - 7, -9106, -69, -44, -144, -98, 199, -181, - 6, 45, 47, 37, -51, -68, -50, -116, - -105, 49, 376, -420, 187, 2894, 29, -471, - -221, 455, -1, -858, 55, -197, 359, -1972, - -188, 921, -134, 186, -843, -2542, 322, -1, - -158, -352, -307, -578, -60, 143, -1302, 333, - 681, 1373, -1021, 18, 284, -28, 8, -57, - -16, 15, 58, 31, 8389, -35, 18, 77, - -78, 15, 36, 17, -134, -17, 316, -680, - 491, 38, -217, -278, 276, -299, -75, -4030, - -293, -507, -62, -344, 64, -438, -344, -256, - 341, 199, -66, 28, -17, -17, 2, 142, - 6, -48, -169, -27, -117, 6739, 42, -61, - 140, 246, 3357, -3243, 48, -55, 49, 27, - 4, 172, -169, 6, 69, -265, 70, 25, - 223, 28, 129, 231, 57, -1608, 2640, -28, - -197, 29, -11, 138, 621, 427, 20, 514, - 663, 562, 447, -158, -909, 343, -321, -257, - 6641, -1, -20, -70, 62, 241, 51, -83, - -48, -156, -266, -335, -43, 421, 350, 306, - 165, -541, 47, 5, -40, 364, 21, 190, - -4584, -125, -441, 489, -571, -47, -10, 205, - 60, -73, -584, 417, 233, -34, -109, 85, - 41, 134, 485, -171, -183, -1522, 202, 390, - -3112, 144, 1675, 651, 402, 1953, 120, 93, - -276, -1930, -197, -61, 100, 81, -250, -155, - -19, 336, -178, -2340, 88, -543, 226, -2507, - -60, -62, 218, -9, 158, -3617, -66, 32, - 314, -192, -121, 372, 334, 516, 412, 247, - -609, -1237, 312, -120, -39, 47, 61, -63, - -90, 4500, -191, -353, 10, 54, -163, -345, - 121, -318, -235, 190, -99, 181, -3369, 4, - -188, -87, 128, 167, -507, -1132, -666, -354, - 121, 43, -546, 601, -409, 181, -47, -315, - 127, -2845, 487, 186, -2724, 343, 177, -837, - 387, -84, 259, 122, -159, 88, 117, 137, - 79, 126, 1584, -521, -2448, 2648, -246, -75, - 567, 114, 244, 653, -551, -196, -623, 205, - 816, 48, -326, 66, -94, -33, 133, 412, - -241, 491, -32, -712, -249, -3756, -185, -229, - 248, 268, 557, 73, 164, 24, -70, -27, - 54, -156, -51, -47, -26, 43, 187, 179, - -38, -137, 218, 1916, 4614, 435, -15, 21, - 145, 1868, 241, 240, 299, -204, 73, -24, - -118, -372, -89, 23, -298, 479, 2837, 959, - -76, -85, -2, 28, 94, -3245, 28, -130, - 159, 295, 264, -419, -98, -16, -159, 349, - 202, -158, -2680, -210, -390, -18, -8, 364, - 1367, -110, 932, -232, 1348, -80, 865, -291, - -408, 406, -118, 6462, -55, 10, -152, -161, - -132, 231, 258, 135, -13, -104, 247, 207, - -238, 212, -19, -31, -3303, -160, -24, 3402, - 50, 116, -191, 97, -139, -100, 71, -49, - -293, 133, -120, -10, 197, 196, -516, -686, - 79, -52, 6002, -47, 88, -201, 146, 136, - 54, 162, -180, 287, 67, 70, -55, 210, - -1938, 635, -162, 82, -120, -456, -75, -3753, - -83, 176, 137, 18, -6, -281, 232, 137, - -167, 373, 78, -2622, -38, -293, 89, 69, - -3476, 8, 152, 136, 32, -15, -140, 11, - 6, 13, 481, -175, -228, -254, 158, -3423, - 206, 22, 900, 2025, 266, -402, 132, -356, - 558, -592, -262, -419, 1002, 73, -246, -24, - -3145, 3220, -33, 283, 398, -31, -25, -7, - 103, -93, -143, 1, 32, -497, 206, -35, - 1424, 114, 140, 2393, 3245, -218, -163, 113, - 191, -164, -215, 504, -256, 140, -364, -226, - -340, 91, -464, 32, 188, 4, 15, -6068, - 69, 109, 219, 75, 196, -24, -84, -218, - 27, 57, -97, 8, -338, -4, 358, 23, - -52, -68, 552, 4023, -255, 684, 144, 188, - 100, -293, 462, 553, 9, 665, 12, -640, - -5099, -158, -245, -74, -168, 263, -355, -370, - -653, -163, -473, -394, -233, 750, 17, -31, -}; - -static const int16_t cb1110sl0[] = { - -3736, -3737, -18, -285, 383, -144, -155, -204, - 296, -399, -663, 356, -364, 329, -330, -5, - -52, -88, -41, 228, -21, -45, -136, -280, - -109, -86, 57, 91, -212, 158, -106, -90, - -8192, 70, -255, 78, -8, -89, -110, -58, - 104, -51, -2598, 411, -94, -567, 209, -464, - 139, -234, -336, 754, 863, 399, 345, 117, - -3435, -219, 369, 59, -325, 2439, -148, 6, - -48, 84, -14, 71, 94, 10, 6, 73, - 106, -490, -200, 186, 345, -8, 99, -3687, - -1571, 1836, -1593, 1111, -3700, 470, -6, 401, - -182, -119, 438, -263, 228, 785, -361, -56, - -492, 465, 333, 61, 53, 234, -23, -87, - 39, 105, 7282, 59, -47, -57, -77, -45, - -172, 12, 179, -134, 37, -157, -19, -206, - 9, 1186, -264, 600, 350, 374, 115, -55, - 727, -164, -3903, -735, 586, -24, 145, -786, - -118, 943, 514, 396, 3435, -35, 83, 294, - 107, 16, -3636, -93, 360, -307, -105, -172, - 204, 320, -148, 410, 175, 335, 0, -178, - 12, 94, -47, -91, -49, -159, -155, -65, - -17, -159, -316, 64, 155, -260, 81, -4766, - -150, -116, -332, 128, 675, -105, -479, 563, - -101, 101, -379, 33, 37, 1, 106, 151, - 69, 140, -6, -74, 157, -125, -120, -33, - -178, -286, 60, -158, 43, -7291, -295, -68, - -34, -68, -58, 8, 176, -42, -212, 176, - -533, -62, -27, 167, 291, 59, 311, -3050, - 552, -493, -207, 2576, -991, -375, -102, -980, - 1130, -565, -199, 559, -1390, -428, -618, 70, - -437, -245, -1132, -1302, -453, 83, 222, -1555, - -178, -1396, -1176, -228, 730, -3121, -1085, 84, - -326, 71, -185, -315, 889, 803, -2910, -3609, - -639, -199, 187, 137, -622, 473, 121, 181, - 85, 395, 523, 589, 71, 703, 123, 361, - 47, -675, 299, -446, 307, 591, 3341, 64, - 526, -1541, -50, -1369, 701, -144, 1720, -713, - 562, 297, 146, -34, 1315, 956, 761, -415, - -1311, 637, -1263, -1096, -385, 3228, -395, 317, - -354, -503, 255, -526, 245, 598, 853, -269, - -110, 1354, 333, 110, 855, -3346, 635, 636, - -917, -577, 260, 147, 1041, 1273, 385, -862, - 1751, -1099, 80, -148, 120, -118, 5565, -484, - -74, 326, 291, 234, -41, 212, 192, 207, - -108, 198, 118, -389, 178, -151, -252, -69, - -243, -800, 2640, -531, 84, -301, 157, -3428, - 3, -418, -173, -166, -722, 207, 448, -387, - -504, 202, 453, 210, -203, 304, 190, -264, - 101, -23, 36, 74, -146, 26, 29, -33, - 59, -127, 22, 213, -167, 103, 8192, 183, - 2709, -125, 324, -964, -259, -400, -41, -430, - 367, 127, 266, 369, 1081, -190, -220, -1083, - 641, -2733, 750, 525, -623, -18, 3159, 686, - -278, -2083, 1680, 587, 123, -6, -266, 376, - 522, -433, -499, 169, 106, 2041, 174, 571, - -108, 129, -116, -87, -252, 89, -14, 14, - 120, -7874, -204, 15, 19, -110, -82, -54, - 66, 31, 210, 55, 339, 61, -219, -3205, - 1292, 80, 344, -733, 3172, -21, -55, 712, - -192, 38, 408, 489, 388, -343, -763, 438, - -1812, -6, -129, -1392, -382, -28, 105, -284, - -168, -462, -284, 22, 113, 1203, 3253, -589, - -619, 348, 113, 847, 3, -557, 460, -636, - -601, -742, 46, -111, 51, -66, -2867, 551, - 455, 898, 17, 2205, 1004, -46, -1475, -367, - 2849, 766, -32, -119, 624, -722, 3371, 172, - -330, 93, -221, 457, -453, 84, -281, -360, - 108, 487, -301, 166, -2611, 577, 192, 34, - 1105, 705, 34, 29, -3041, -898, 172, 578, - 307, 483, -439, -327, 360, -935, -76, 387, - -2485, 800, 333, 601, -712, -973, -65, -442, - 220, 3577, -428, -210, 565, 757, -382, 289, - 726, -19, -182, 384, -32, 38, -810, -181, - -2978, 259, -213, -473, -187, -823, -279, 1518, - 26, -385, 1143, -409, 1310, 676, -2472, 64, - -391, -102, 455, -5751, 278, 30, 64, -177, - -113, -170, 94, -234, -167, 101, -2, -149, - -131, 351, -254, -138, 149, -42, 631, -21, - 237, 2893, -291, 2917, -1240, 211, -215, 22, - -827, -160, 140, -213, 156, -250, -1233, 691, - 498, -30, 350, -28, -12, 217, 34, -348, - -70, -140, 103, -60, 353, -200, -314, -74, - 112, 4435, -80, -287, 413, -99, 1407, 1519, - -2230, 114, 3179, -523, 39, 340, -379, 373, - -1552, -138, -446, -106, -762, -1017, -297, -183, - 498, -481, 374, 271, -5609, 297, 98, -378, - 187, -78, -125, 333, 114, -81, 62, -145, - 14, 362, 518, 134, 195, 130, -34, -72, - -3088, -2965, -114, 585, -78, 6, 552, -633, - -98, -224, 980, 338, -83, -1064, 42, 106, - -119, 644, -293, 496, 67, 128, -129, 620, - 20, 526, -177, 68, 351, -3703, 1465, 905, - -245, 86, 511, 39, -512, -150, 239, 86, - 60, 39, -79, -9, -65, 77, -7993, 57, - -19, 56, -38, 161, -221, -129, 8, 93, - 52, -5622, -114, 133, 26, 64, -194, -316, - -143, 225, -66, -81, -74, 240, 130, 137, - -549, 11, 352, -53, -4029, 513, 3164, -205, - 127, 80, -193, -197, -36, -885, 223, -858, - 5, -458, 290, 459, 247, -284, -176, -748, - 173, 191, 114, 406, 126, 3, 91, 84, - 8027, 379, -56, 47, 35, 246, -143, 65, - -36, 8, 59, 67, -69, -421, -3492, 312, - -252, 261, 3367, 319, -67, 77, -346, 386, - 34, 237, 18, 111, 348, -547, 186, -93, - -3558, -178, -3801, -133, -27, -561, -308, 112, - -224, 272, -195, -270, -179, -165, 199, -524, - 681, -117, -429, 37, -5891, 94, -55, -433, - -354, 122, -60, 67, -200, -80, 267, -136, - -42, 130, -324, -25, 156, 167, -47, 178, - 8, 289, 157, 88, -28, -39, -262, -11, - 9, -113, 76, 8192, 89, 115, -298, 137, - 34, 0, 261, -30, 49, 274, 130, 824, - -944, -56, 1074, -314, -76, 527, 75, -3321, - 733, -798, -352, -1038, 1049, 72, -233, 312, - 3363, 69, 104, -149, 22, 283, -20, -101, - -3350, 164, -328, -362, -993, 430, 78, 125, - 269, -29, 362, -73, -30, -1189, 1396, 59, - -1285, -216, -121, 3893, 84, -464, -38, -113, - -369, -181, -930, -1012, 394, 120, 274, -552, - -800, 105, -141, -12, 241, -667, 543, -416, - 28, -182, 51, 905, -3964, -1213, 12, -271, - 378, -234, 838, -113, 56, 567, 35, 48, - 490, -180, 1097, 170, 2596, -28, 3098, -220, - 424, 885, -42, 783, -30, 907, 63, 46, - -131, 28, -55, 54, -46, -25, 30, 58, - -15, -200, -6, 11, -70, 66, -8089, 86, - -136, 96, -56, -101, 300, -661, -41, -201, - 760, -252, 955, 189, 1459, 3562, -457, 35, - -54, -164, -329, -1245, -830, -365, -399, -23, - 616, -238, -1301, -198, 335, -3400, 149, 175, - -97, -279, -594, -92, -915, -830, 468, 628, - 728, 1024, -549, 1073, 222, -142, 296, -75, - -168, -5, -67, -7311, -50, -256, -321, 121, - 358, -272, 30, 258, 105, -161, -291, 462, - -7, -211, -227, -104, -151, -152, -72, -98, - -59, -23, -98, -203, 103, 89, 239, -484, - 7749, 110, 35, 345, 282, -578, 140, -51, - -62, -238, 102, 454, 64, -107, -223, -174, - 285, 110, -190, -16, 1624, 142, 3813, -849, - 43, 234, 84, 0, -132, 131, -135, -70, - -1, 125, -83, 171, 109, 8044, 97, -38, - 143, 64, 13, 4, -225, 181, 712, 626, - 20, 167, -467, 186, 3801, -2179, -647, -119, - -112, -183, -223, 295, -438, -407, -29, 36, - -34, 2536, -47, -402, -33, -62, -136, 2444, - -152, -717, -868, 86, -2323, 931, 659, -1281, - -98, 638, -162, 195, -5, -40, -88, 3019, - 3466, -323, 316, -784, -715, 5, 188, 42, - 155, -608, 500, 185, 475, 100, -51, 879, - -891, -158, 18, -453, 380, -207, -143, 401, - -153, 926, -184, 2775, 3176, -797, -198, -888, - 405, 460, 309, 304, -114, 2386, 2319, 658, - -2200, 216, 435, -1210, -655, 154, 81, 538, - 908, 220, -118, 482, -864, -526, -241, 857, - -473, 774, -288, -886, 46, 250, -96, 301, - 120, -488, -128, -233, 422, 38, -3416, -974, - -243, -226, 381, 2394, 652, 3124, -205, -1303, - 1484, -159, -152, -1037, -105, -121, -466, -76, - 605, 181, -55, -326, -527, -126, 1691, 1316, -}; - -static const int16_t cb1110sl1[] = { - -743, -300, -347, -441, 85, 5282, -250, 32, - 28, -306, -434, 78, -178, -112, -28, -162, - -188, -43, 17, 94, -242, -258, -2691, -471, - -556, -815, 120, -57, -36, -325, 3282, -765, - 355, 2, -162, -454, -72, 192, 86, 219, - -123, 237, 135, -42, 492, -471, -114, 5146, - -164, 28, 77, 70, 276, -148, 333, 64, - -89, -46, -135, 474, -218, -119, 351, 7619, - 93, -80, -84, -51, -110, -223, -13, -116, - -160, -102, -64, -140, -376, 156, -143, -421, - 105, 102, 519, 1256, 786, -284, -3029, -3021, - -365, -515, -1358, -273, 394, 489, -242, 31, - 239, -1328, 169, -488, -3069, -398, 303, -274, - 498, -2758, -748, -208, -324, -285, 78, -386, - -1063, 298, 5, 693, 160, -629, 1656, 186, - 457, 742, 422, -3723, 1997, 1025, -24, 291, - -588, 16, -327, 459, -521, 421, 1279, -408, - -2, -1320, 101, -372, -66, 100, -605, 3214, - -374, -660, -371, 207, 175, -553, -574, 2962, - 119, -551, -140, -62, 50, -608, -237, -100, - 108, 101, 3258, -31, -45, 375, -161, 132, - 2842, 1458, 235, 800, -113, 719, -291, -29, - -512, -267, 53, 780, -59, 3387, -175, 88, - -78, -475, -536, 584, -3025, -19, -105, 91, - 875, -55, -771, 143, 384, 810, -372, -253, - 160, -128, 232, 98, 7755, 181, -19, -177, - 46, -39, -30, -212, -289, 75, 127, -114, - 80, 79, 325, -128, -436, 2547, -73, -29, - 1046, 344, 3340, -335, 458, 637, -175, -695, - -366, 294, -322, 564, 542, 209, 524, -62, - 444, 2827, -53, 66, -959, 84, 484, -147, - 158, 259, -479, 3216, 232, -68, 583, -810, - 107, 93, 629, -168, 143, -552, 96, -71, - -3903, -438, 335, -133, -186, -278, 73, -575, - -253, -733, -91, -8, -1149, 350, 140, 12, - 3935, -236, 103, 469, 610, -536, -305, 3112, - 13, -182, -686, 637, 525, 327, 102, -49, - -450, -16, -480, 233, -82, -132, -3979, 426, - 757, 54, 152, -701, 513, 2330, 148, 242, - 1709, 162, -168, 146, 0, 891, -644, 109, - -549, 104, -50, 275, -193, -55, -144, -117, - 31, -234, 68, -5369, 72, 54, 54, 119, - -140, 192, 286, -42, -278, -3524, -3609, 692, - -366, -15, 343, -885, -267, 294, -387, -215, - -83, -469, 790, 85, 428, -613, 114, 634, - 279, -570, 616, -813, -117, 3073, 3121, -717, - -200, 285, -1061, -44, 945, 386, -166, 494, - 776, 36, -25, -444, -260, 407, 3885, 1049, - 1348, 185, 454, -136, -2275, 1064, -271, -316, - 645, -1050, 483, 430, 32, 569, -676, -335, - -328, -2982, -370, 50, 189, 155, 1058, -119, - -407, -310, 461, 3293, -604, 195, 48, 68, - 196, 194, 547, -210, 785, -383, -410, -268, - -149, 192, -88, -13, 20, -80, -5146, -86, - -111, 40, -36, -138, 12, 239, -36, -84, - -512, 149, -237, -672, 3477, -3446, 1198, 220, - 146, -747, 242, 48, -146, -196, -335, -777, - -405, 620, -340, -367, -389, -108, -27, -184, - -2024, 518, 241, -104, 417, -1356, -1961, 134, - 3221, -423, 286, -60, -110, -568, 14, 76, - -144, 159, 704, -410, 542, -43, 223, 105, - -154, -141, -84, -132, -271, -235, -285, -248, - 480, 430, -4711, -487, -86, 482, 80, 46, - -239, -93, -115, -54, -1, 7, 97, -12, - 151, -180, 159, -63, 65, -215, 54, 5712, - 2886, -115, -236, 113, -25, -301, -450, -276, - -78, 197, -55, -278, -511, 163, 3442, -910, - -74, -225, -103, 63, -204, -43, -126, -334, - 223, 192, -131, 202, -83, 5000, -66, 441, - 33, 0, -116, 237, -238, -37, 445, -48, - 7, -1855, -1154, -251, -117, -185, 125, 1877, - 375, 388, -904, 202, 649, 376, -3231, 897, - 101, -637, 376, 16, 1, 845, -550, -610, - -380, -1363, -955, 71, 1303, 296, -264, -584, - 247, 3247, 98, 1035, -670, 416, -2008, -448, - -56, -169, -1787, 3314, 408, 2541, -833, -2, - -169, -184, 193, -575, -81, 410, -293, -478, - 21, 194, 223, -111, 4648, 60, 354, -593, - -2429, -671, 150, -350, 151, -448, -5, 386, - -441, 131, -339, 87, 815, 279, 51, 131, - 56, -3194, -170, -3899, -297, 270, 21, -215, - 7, 205, -305, 141, 577, 83, -289, -502, - -66, -96, 433, -106, -685, -194, -82, 33, - 98, 315, 258, -2453, -2957, 608, 672, 152, - -681, 1804, -74, -459, -423, 114, -1183, -100, - -798, 357, -79, -3418, -676, 580, -1637, -506, - 306, 437, 1001, 731, -885, -1276, -583, -359, - 650, 15, -189, 190, 86, 39, -7987, -133, - 324, 174, 22, 86, -144, -125, -43, -81, - -49, 68, 39, -204, -159, -291, -217, -68, - 264, 193, 406, 247, 27, -272, -168, 536, - -5740, -141, 38, 18, -7, 258, -111, 125, - 476, -364, 5, 72, -2668, -197, -605, -671, - -82, 201, -752, 227, 240, 345, -11, -138, - 551, -351, -228, -2774, -132, 1115, -1038, -18, - 791, -3136, 81, 219, 357, 755, 579, 26, - -3129, -398, -719, 193, 495, 290, -1123, 854, - -381, -535, 33, 232, 2340, -4577, -94, 1023, - -117, 39, -54, 15, -161, -860, 64, -209, - -597, 415, -135, -407, 1068, 894, -784, 108, - 267, 7506, 140, 67, 198, 74, 52, -388, - -184, -24, -54, -24, 172, 172, -50, -184, - -113, 164, 128, -39, 252, 90, 356, -313, - -90, -313, -355, -73, 19, 139, 141, -122, - -231, -4548, -157, -227, 47, 231, -421, 60, - -80, -3619, 4252, -354, 69, 148, 336, 446, - -183, 86, 248, 35, 73, 120, 157, 156, - -291, -523, 35, -264, 3434, 189, 495, -59, - 533, -343, -554, -3014, -415, 17, 436, 552, - -240, -394, -761, 43, -766, 46, -1119, -254, - 1540, 195, -298, -833, 45, -93, 61, 40, - -171, 167, 82, 107, 16, 40, -166, -46, - 120, -185, 13, 151, 8151, -235, 92, -23, - 214, 206, 260, 93, 163, 78, 184, -60, - -12, -171, -499, -151, -219, 11, -221, 221, - 3253, -376, -1079, -481, 763, -257, -120, -10, - 34, -640, 341, -2953, 528, 567, -672, -335, - -175, -61, 581, -260, 1159, -802, 1070, 12, - 168, 2305, 291, 203, -15, -569, 3247, -179, - 620, 339, 224, 710, -416, 512, -86, 571, - 439, -167, 571, -72, -144, 236, -382, 11, - 268, -176, -136, -337, 220, 64, 341, 361, - -4474, 25, 385, 453, -153, 89, -572, 245, - -197, 33, 75, 588, 51, -199, -74, -149, - 224, 210, 4689, 282, 20, -47, 129, 221, - -72, 27, 76, 93, 331, 215, -5, -20, - 74, -80, 169, 126, -40, -137, -24, -8101, - -23, 165, 271, 403, -34, -19, 290, -199, - -14, 205, 657, 301, -885, 2457, -1965, -2266, - -1004, -224, -554, 182, -220, -467, -611, 1012, - -122, 3303, -73, -205, 93, 3549, 217, -223, - 55, -459, 541, 286, -46, 128, 354, 137, - 824, -313, 32, 301, 139, -492, 170, 136, - -35, -752, 4613, -830, -34, 41, 344, 279, - 643, -394, -461, 163, -330, 199, -215, 83, - 1096, 613, -473, 816, 3534, 210, -772, 935, - -275, -600, -341, 602, 104, -598, -217, -789, - -2428, 870, -351, 474, 50, 321, -148, -2929, - 25, -135, -46, 11, -566, -3057, -664, 700, - -300, 256, -960, 350, -480, 414, 431, 24, - -51, -228, 407, 142, -321, 316, -290, 149, - 56, -84, -359, -118, -4948, 138, 373, -49, - 142, 71, -163, -13, -279, 38, -121, 35, - -47, -70, -43, 116, 3, -159, -11, 97, - -116, -62, 156, 307, -173, 7294, -143, 288, - -34, 671, 613, 16, -240, -229, -414, -494, - -43, -169, -854, 336, -991, 719, -353, -163, - -750, 2685, 2837, -558, 129, 2076, -47, 641, - -37, -93, 226, -69, 598, -284, 127, 106, - -426, -555, -947, 485, 54, -3175, 622, -341, - -544, 278, -205, -689, 391, 238, 9, 152, - -233, -392, 28, 36, -394, -1059, 132, 3761, - -480, 87, -656, 1304, 478, -272, 65, -147, - 91, 520, -896, 166, 62, -30, -28, 194, - 542, 3, 625, 1795, 3613, 1097, 1030, 906, - 400, 133, -127, 219, 958, 93, -546, -702, - 2937, -524, -270, -767, -192, 725, -897, -643, - 2502, 141, -1147, 257, 279, 470, -3001, -104, - 79, 508, 450, 265, -21, -74, -437, 647, - -2755, -407, -816, 620, 24, 537, -668, 604, -}; - -static const int16_t cb1110ss0[] = { - -8187, 90, -694, -168, -452, -4, -259, -332, - 352, -554, 43, 389, 236, 508, -175, 461, - -277, 118, 651, -245, 696, -1423, 368, -1417, - 1782, 1650, -540, 27, -461, 516, -599, -185, - 422, -11, -181, 19, 1809, -3226, -839, -191, - 468, 180, -550, 198, 2487, -923, -1335, -1008, - 1029, 1716, 588, 371, 902, -1214, 179, 1026, - 1560, 1815, -1714, 1230, -712, 1675, 1867, -154, - -2860, -484, 2289, -1018, 33, -1494, 614, -2340, - -724, -1088, -1930, -775, -876, 642, -1358, -144, - -2518, 62, 543, -1049, -1081, 672, 1305, -1506, - -86, 2920, 518, -1836, -546, -132, -45, -642, - 381, -404, -2206, -1211, 698, -703, -667, -606, - -677, -2246, 526, -1157, 177, 510, -1420, -617, - -1819, 1710, 1631, 1049, -1697, -495, 961, -1250, - 39, 482, 445, -956, -71, 977, 426, 1826, - 286, 36, 295, 1786, 794, -3456, 1645, -766, - -1580, -2435, 1108, -286, 731, -659, 960, -1759, - -978, 316, -350, 91, -35, -222, -1417, -53, - -529, -679, 681, -4700, -524, -39, -350, 196, - 199, 191, 653, 1344, -942, -428, 156, 173, - 636, -1538, 1795, 1709, -190, 1265, 164, 650, - 2302, -1757, 1762, 413, -851, 44, -1371, 343, - -3845, -122, 1864, -489, 601, -748, -402, 590, - -124, -1988, -1536, -999, 399, -753, 295, -384, - -1316, 55, -669, 262, -1157, -3766, 992, -111, - -2928, -1424, -98, -62, -334, -1848, 377, 1560, - 947, 1568, 1554, 206, 664, 2014, 2098, -164, - -640, -2897, -647, -1675, -2307, -254, -555, -2426, - 1497, 465, -1525, -1148, 55, 632, 554, 2068, - 451, -1532, -715, -2065, -1177, -623, 478, -88, - -1140, -72, -450, -248, -1111, -250, 1356, 2717, - -1841, 420, -1299, -1715, 746, -101, 600, 1130, - -903, -473, 1225, -876, 193, 694, -193, -482, - -1838, 94, 157, 1131, 267, -242, 2021, -39, - 795, -285, 438, -4322, 1097, -621, -518, -338, - -289, -114, -671, 1700, -477, 449, -1664, -693, - 1403, -3629, 1480, -991, -234, -213, 354, -269, - -1140, -40, 1455, -758, 1273, 497, -686, -945, - 59, -66, -769, -2930, 2343, 2452, -1576, 995, - -734, 1009, 98, -350, -1116, 545, 189, 99, - 566, -916, 20, 117, -807, 986, -428, 177, - 1247, 485, -680, 1139, -1263, -256, 4828, 89, - 27, -1339, -1091, 149, -641, -703, -570, -112, - 346, -93, -641, -97, -991, -2247, 2284, 847, - 2110, -1393, -315, -1468, 514, -1493, -46, 1135, - -1231, 39, -913, -278, -762, 1775, -684, 735, - -1676, 386, -2030, 2534, -2371, -1661, 1204, -111, - -8, -607, 1233, -1532, -1263, 1530, -537, -1728, - -335, 269, -614, 12, -1187, -770, 471, 373, - 4743, 12, 197, 610, -101, 417, -350, 551, - 544, -898, 387, -682, -1216, 126, 96, 94, - -268, 535, 126, -778, 1595, -1379, 3366, 49, - 460, 1772, 198, -896, 75, 253, -1376, 68, - 838, -1121, -578, -630, -718, -975, -565, 1303, - 354, -769, -38, -246, -193, -408, 41, 165, - 374, -87, -155, -8, -746, -430, -869, -1842, - -385, 281, 5119, 432, 1119, -807, 1756, 816, - 131, -548, -528, 1347, 478, 1482, 2942, -290, - 650, 1012, 163, 840, -804, 94, 2507, 1514, - -953, -289, 23, 1128, -895, -1009, 1871, -370, - 699, 659, -3069, -695, -1559, 1435, 672, 94, - 1496, -637, -2208, 1083, 688, 485, 251, -828, - 1313, -21, -1948, 230, -603, 783, -829, 524, - -1142, -3845, -1383, 323, 1295, 732, 759, 591, - 68, -1869, -756, 1727, 339, -1565, -510, 2623, - 358, 3071, 281, -790, 1129, 243, -588, -431, - 492, 372, 96, 890, -935, -727, -236, -416, - 171, 226, -1090, 1257, -1063, -303, -817, -1506, - -947, 2282, -659, -406, 79, 772, -816, -2610, - -1802, -1019, -816, -1886, -1306, 1365, 624, -2314, - -57, 1012, 215, -130, 3404, -864, 959, 202, - -26, -1015, -1212, -34, -408, 3494, -284, 845, - 275, -1005, 458, 840, -2258, -13, -129, 2536, - 1269, 1216, 2071, -243, 624, 584, 2192, 720, - 604, -1397, 766, 984, -1050, 157, -246, 438, - 240, -587, 1251, -649, -22, 33, 5818, 608, - -996, 474, -523, -454, 1252, -791, 631, -465, - 663, 452, 1793, 853, 39, 3732, 758, -1329, - 11, 2217, -136, -540, 1335, 65, -2047, 943, - 701, 1886, 2085, -890, -16, -184, 325, -1077, - -271, -1246, 391, -1686, -651, -77, 319, 292, - -160, 1204, 1093, 776, -310, 1512, -1196, 149, - 46, 593, 1738, -566, 97, -3667, -485, -683, - -121, -216, -149, -344, 406, -989, -311, 383, - 979, -828, 394, -22, -5143, -1368, -18, -433, - 359, 607, 996, -1144, -229, 1365, -1243, 413, - -591, -621, 803, 1356, -625, 1149, -234, 182, - -1285, -2487, 359, 2640, -1426, -66, -688, 237, - 1307, -361, 108, 207, 1026, -500, -1156, -1043, - -2192, -2232, 1790, 1135, 1742, 1494, -1156, -698, - 2520, -2596, -620, 431, 748, 88, 912, 832, - 1122, -483, 1837, 1821, -826, 1112, -424, -306, - -750, 1085, 260, 152, -114, -1065, -4518, -300, - -976, 143, 1452, 1395, 1677, 59, -51, -1072, - 868, -171, -26, -914, -109, -2420, -48, 69, - -230, 630, -522, 2274, 1265, -1612, 2570, 836, - -2042, -1922, 2970, 775, -320, -2486, -2935, 553, - 178, 994, -1054, -1321, 699, 749, 1002, 513, - 586, 1550, 35, 654, -995, 1743, -1049, -405, - -3431, 1943, 700, 555, 111, -67, 1007, 111, - -57, 661, 404, -628, 425, 2185, 860, -516, - -523, 452, 238, -1778, -378, -721, -2197, 218, - 864, -1031, -832, 135, -2543, -447, 789, 1117, - -1491, 120, 1294, -702, 627, -412, -902, 404, - -1843, -786, -597, 900, 1963, 22, -843, 1168, - -1045, -797, 764, -423, 329, 2308, -1950, 331, - -1090, -2466, -483, 2023, -3363, 2126, 495, 2812, - 1922, -1488, -1041, -798, 135, 408, 33, 563, - 1333, -36, -2181, -787, 709, 287, -971, 93, - -459, -975, 2412, 280, 2555, 32, 2217, -1825, - 650, 313, 585, -947, 1170, 45, 1108, -435, - 1092, 220, -155, 512, 460, 211, -231, -627, - -836, -2205, -181, -113, 130, 226, -321, -765, - -1327, -1190, -676, -357, 691, 232, -365, -1818, - -3007, 2210, 997, 601, 2156, -782, 1626, -1081, - -49, -616, 685, -12, 40, 3480, 563, 515, - 245, 51, 290, 1227, 171, -1078, 520, -483, - 280, -1517, -1331, 2132, -1176, -1381, -1546, 1436, - -852, -505, 672, -807, 623, -244, -125, -1958, - 516, 798, 1185, 922, 441, 651, -610, -1430, - -1887, 114, -869, -2024, -1627, -2276, 2008, -1224, - 125, -609, 371, -1104, -506, -942, -624, -478, - 197, 141, -242, -1051, 1532, -1269, 666, -1055, - 1689, 444, 1720, 16, 301, -2311, 1196, 1108, - 1298, -564, -1197, -1858, 439, -198, 324, -1884, - 3193, 2281, 201, 587, -2028, 1969, -1087, -352, - -87, -632, 144, 165, 68, 1150, 173, 478, - -837, -470, -464, -195, -205, 2111, 15, 643, - -453, -339, -1128, -1368, 1182, 822, 654, -2331, - -1668, -215, -678, -2460, 1169, -664, 777, -348, - 2570, -767, -563, 254, 562, -557, 4, -97, - 1990, 373, -780, -677, 1996, -1527, -365, -416, - -325, 587, 910, -3780, -553, 104, 1705, 240, - -719, -1717, 2765, -582, -76, 399, -1152, 2379, - 3169, -1153, -725, -35, -1214, 362, 1600, -724, - 424, -722, 472, 872, 694, -126, -1649, -1314, - -1814, -95, -312, -34, 780, -884, 824, -864, - 526, -100, 3820, -56, -452, 43, 564, 487, - 177, 890, -1423, 894, -552, 1438, 204, 1015, - -4, 327, -3327, -433, -335, -869, 1312, -488, - -1287, -169, 2018, 435, 73, 508, 1160, -1060, - -134, -1304, -341, 623, 125, -15, -1120, 108, - -71, -1487, -189, -3640, 1424, 1740, 1116, 579, - 1603, -3294, 1241, -225, 1481, 2775, 1326, -242, - -632, -1560, 563, 559, 138, 115, -557, 2004, - -1771, 717, -1052, -1115, -1634, 889, -441, 1954, - -164, -1507, -1312, -407, 662, -867, -896, 225, - 2576, -224, -107, 237, -694, 859, 192, -1033, - 2255, -1225, -891, -1994, -90, 339, -382, -774, - 1460, -1553, 648, -521, 2370, 160, 714, 54, - -906, 1435, -1752, -274, -523, -36, 1208, 1553, - -339, 1000, -178, 209, -1001, 916, 495, 310, - 726, 127, -391, 107, -513, -1052, -376, 297, - -307, 933, -233, -253, 1196, 4619, -1278, 762, - -13, -387, -973, 2153, 68, 362, -887, -1922, - -106, 298, -1127, -2601, -2184, -111, 111, -1588, - 1002, -365, -2226, -290, -599, 610, 551, -1368, - -4344, 618, -172, 349, -914, -530, -192, 718, - 348, -675, -884, 913, -94, 215, -834, 353, - 753, -811, -84, -905, -128, -483, -1782, -1255, - -2333, -1110, 477, -566, 346, 2018, -1644, -325, - 1365, -1223, 158, -1786, 566, 203, 742, 281, - -555, 573, -978, -459, -1671, 378, -689, 349, - 606, -5961, 562, -13, -223, -419, -442, -447, - 125, -1052, 53, 2594, -1377, 209, -1549, 533, - -118, -2538, 1808, -364, -37, 1221, 607, 593, - 309, -240, 1574, 254, 434, -141, -220, -2018, -}; - -static const int16_t cb1110ss1[] = { - 631, 3041, 1215, 2376, -1843, -103, 750, 144, - -87, -249, 715, -201, 758, 202, -197, -135, - -523, 1243, 457, -717, -700, 1662, 918, -48, - -1008, 180, 411, 948, 2192, 2607, -826, -962, - -1130, -59, -1047, -305, -325, -1032, 2096, -287, - 395, -1543, -268, -1218, -2045, -1674, 951, -1846, - -636, 263, -138, -287, -327, -2208, -664, 496, - 2179, 1645, 340, -601, 473, 670, 950, 2774, - 364, 613, -1896, -1876, -3177, -105, 506, -164, - 281, 718, 2419, -1077, -50, 365, -1631, -134, - -384, 231, 767, -285, 1268, 321, -1408, 217, - -409, -725, 1225, -2551, -2622, -274, 473, 2752, - -11, 342, -495, 1627, 79, 240, 2, -1021, - 640, -508, -269, 648, -116, -1283, -217, 13, - -1674, 2402, -879, 1791, 2753, 2386, 1195, -700, - -282, -428, -671, -92, 1187, -672, 1037, -1913, - 246, -816, -69, -2284, -712, -996, 2498, 902, - 809, -149, 66, 775, -44, -566, 955, -1073, - -1438, -894, -978, 274, -390, 5528, 1153, 17, - -750, 63, 545, -725, -301, -323, 661, -813, - -347, 739, 335, 136, 203, 342, 802, -199, - -818, -679, -282, 2195, -1714, -757, -154, 182, - 132, -1737, 405, 2394, -3727, 1349, 213, -193, - -2495, -1354, -629, -1171, 1429, -16, 834, -1260, - 160, -1892, 874, 1754, -567, 344, -3499, 1612, - -987, -424, -997, -1640, 594, 1058, -783, 511, - -604, -1480, -1754, -424, 2262, -1991, 1297, -638, - 350, -588, -55, 1483, -456, -567, 146, -946, - 731, 1541, -759, 592, 1231, -270, 171, -1975, - -2707, -456, -227, 392, -891, 1008, -1066, -487, - 231, 1372, -51, -599, -227, 696, -820, 354, - 1928, -48, -1302, -570, 316, -283, -848, 2563, - -266, 2821, 540, 553, -1272, 1120, -1164, -451, - 384, -1058, -1018, 1735, 992, -1220, -83, 1490, - 2304, 122, 1630, 1108, 1997, 2346, -647, 301, - -1746, -218, 313, 462, 1486, -536, -508, -463, - 104, 930, 605, 2116, 793, 2881, -724, -1379, - -53, 4458, 793, 275, -180, -516, -489, -774, - -265, 704, 112, 175, 112, -121, 652, 310, - 564, -440, 773, 1885, 927, -672, -773, 1726, - -614, 818, 1589, -372, -207, 499, -894, 987, - 796, 652, -1228, -4010, -2208, 458, 645, 498, - -279, -852, -1897, -1820, -35, 674, 201, 474, - 77, 94, 2327, 723, -1081, 261, 209, 1179, - -1175, 623, -1293, 2154, -117, -3707, 940, 813, - -1059, -335, 1306, 525, -191, -2066, -425, 19, - -366, 529, -145, 822, -913, 254, 424, -354, - -167, -2437, -1433, 603, -318, -1517, 4250, 541, - -1360, 450, -531, 200, 534, 1200, -222, -535, - -162, -1211, -116, -144, -462, -139, -482, 511, - 2068, -2100, 971, -1487, -1050, -3150, -701, 119, - 16, 1535, 272, -1184, 2242, 488, -492, -915, - 1660, 212, -826, -444, 1003, 2705, 3591, -174, - -333, -431, -59, -903, 61, 751, 1087, -45, - -1031, 617, 686, -15, 848, -348, 947, 396, - 931, 1785, -552, -920, -669, -63, -1869, 2357, - -1549, 807, 889, -1581, -1071, 1587, -1108, 1300, - -658, -625, 300, -285, -977, 1656, 4183, 1487, - -191, 658, -300, 497, 1378, -300, 1031, 322, - 114, -449, 666, 1250, 264, 125, -109, 748, - -503, -40, 199, -1212, -1643, -2522, 151, 121, - -1128, -3200, 876, -446, 878, -989, 1510, 2261, - -1507, 1793, -402, 30, 228, -50, 985, -1568, - 755, 1559, -688, 1342, -423, -1507, 96, -501, - 474, -2926, -2493, -131, -656, 450, 1035, 812, - -14, -933, 941, 1396, -957, -621, -516, 379, - -225, -2063, -2048, 669, 287, 1688, 1727, 299, - -658, 852, 745, -260, 993, 158, -1236, -1422, - 33, 611, -112, -323, -194, 839, -1407, -1505, - -2010, 1267, -355, -675, -3779, 768, -228, -643, - 661, 1313, -529, 962, -948, -212, 1043, 1560, - -174, 1744, -938, 289, 1942, -2228, -1932, 1056, - -590, -940, 922, 601, -853, -791, -637, -2, - -52, -83, -209, 1422, 856, -1141, 2500, -1195, - 773, 1087, -1389, 409, 439, -3674, 453, 1637, - -15, 1013, 2635, 1530, -1104, 440, 895, -210, - 1118, -6, 45, 65, -1110, -3307, -331, 478, - -155, -410, -721, -1234, 129, -971, -1117, -27, - -1132, -1289, 1888, -1112, 203, -1091, 442, -2207, - 501, -343, 468, -52, 385, 269, -3102, -366, - -469, 391, 505, 176, 356, -69, -929, 1155, - -280, -1264, -897, 1006, -494, 155, 36, -627, - 924, -816, 154, -750, -837, 5263, -1099, 91, - -481, 71, -681, -574, 1229, 675, 1217, 1073, - -695, 274, -381, -140, 1372, -524, 1164, 341, - -149, -856, 793, -1294, 981, -961, 371, 1178, - 1463, 373, 1375, -4384, 239, 136, 67, -1196, - -126, -1001, -228, 150, 437, -1830, 477, 498, - 4246, 793, -661, 260, -1810, 1405, 76, 902, - -844, 908, 1830, 27, -124, 257, 765, -98, - 592, 487, -132, 202, 675, -669, -679, 1309, - -4002, -206, -66, -390, -253, -190, -921, -83, - 1411, -417, -2560, -646, 1853, -148, 548, -370, - -723, 959, -906, -3058, -276, 467, -1280, 970, - 687, 484, 506, 1143, -1509, 828, -2169, 2931, - 1322, -579, 1033, 209, -979, 217, -434, -1438, - 314, 2384, -906, -29, -1478, -31, 574, -373, - 1478, -124, -680, 330, 794, -753, -977, 1151, - -1190, -1479, -642, 1658, -2201, -1469, 1589, 587, - 52, 1298, 2092, -1483, 678, 1988, 918, -648, - 328, 2096, -1090, 2153, -1416, 295, 537, 261, - 398, -1389, -399, 1105, 10, -395, 1169, -431, - -423, -1617, 766, -1900, -3205, 131, -746, -852, - 2215, -317, -232, 1079, 293, -727, 50, -446, - -713, -897, 768, -896, -667, -281, 377, 115, - 1695, -4870, 713, -393, 251, 1268, 477, -497, - 294, 18, -359, 556, 308, -752, -863, -216, - 151, -163, 695, 587, 810, 2107, -107, 921, - 1203, -472, 1280, 372, 110, -581, -225, -714, - -58, -2587, -1980, -186, -372, -1410, -1504, -1020, - -745, -88, 2373, -568, -2841, -2041, -1841, 2065, - 389, -430, 1163, -208, 569, 375, 650, 317, - 1114, -1036, -959, -896, 1060, 1014, -599, -1743, - 1121, 808, 1556, 326, -2876, -1556, -1283, 384, - -1102, 378, 1433, 702, 1454, -1243, -725, 224, - -610, -455, 1413, -1747, -2516, -572, -1455, -313, - 231, 780, 1531, -2475, -34, 921, -1650, 269, - 818, 5, 835, -209, -911, -432, -1104, 165, - -1638, -46, -2031, -445, 1308, 1519, -1992, 1606, - 956, 757, 1139, 116, 829, -1376, 209, -893, - 963, -569, -466, -185, -1345, 1524, 1714, 269, - 219, -161, 482, -1178, -3621, -831, -668, 1871, - -529, -983, 558, -818, 81, 555, 33, -473, - -187, 113, 899, -577, -1093, 1408, 902, -258, - -111, -648, 4340, -780, -651, 789, -92, 2310, - -401, 669, -213, 369, -104, -820, -290, 48, - -917, 71, 1070, -239, -744, 891, 23, -5130, - -761, 312, 319, 842, 280, 78, -149, 352, - -594, -361, 354, -906, 42, -1610, 835, 157, - -631, 1100, -297, 1081, -96, 484, -825, -2132, - 549, 1305, 128, -314, -1733, -265, 1285, -4061, - -348, -136, -940, -507, -232, -1511, -876, 78, - 2120, 175, 2216, 1179, 497, 335, 350, -18, - -1307, -387, -2207, 587, 3209, -370, 1155, 1501, - -1687, -796, -1417, -733, -269, 801, 83, 1173, - 718, -2702, 19, -315, 4501, 1025, -365, 348, - -417, -510, -172, -1201, 1478, 671, 1933, 1759, - 676, 416, 30, 400, 531, 351, -1176, -2807, - 1969, -1398, 1159, -568, 754, -149, -1880, -274, - -1203, -43, 1391, 383, 702, 2116, 1299, 1952, - 646, -719, 1735, -986, 100, -956, 1040, 2287, - -1606, 612, 1760, 733, -2453, 531, -14, -1, - -3214, -1993, 371, 227, 45, 2011, -531, 1089, - -1029, 282, -2426, -525, 989, -469, 285, 1787, - 927, -335, 1127, -305, 1143, -412, -1626, 1759, - -2567, -82, 1170, -3051, 1266, 1522, -124, -1935, - 552, 1122, -51, 347, -674, -360, 1183, 223, - 3015, 955, -826, 1108, 2325, 868, 1152, 1079, - 223, 217, -428, 382, 642, -2849, -767, -70, - 407, 147, -392, -407, -55, -508, 1785, -683, - -885, 851, 3879, 471, -674, -231, 1493, 1621, - -1698, 528, 623, 300, 1367, -588, 816, -24, - 600, -182, -841, 854, 370, 715, 116, 714, - -1308, 1435, 1802, -2627, -814, 363, -318, -73, - 850, -1744, 2509, -303, 1077, 660, 2145, 2130, - -730, -88, -115, -517, -154, 160, -337, 27, - 1502, 509, -70, 502, 820, -309, -3740, -1294, - -610, 241, -662, -524, 1319, 456, 926, 958, - -111, -1004, 1795, -604, 1086, 462, -127, -125, - 264, -1093, 1427, 334, 838, 1979, -576, 3052, - -3590, 1607, 356, 728, 1619, -400, 279, 570, - -434, 777, -1448, -888, 156, -277, -1529, 1122, - 2235, -794, 3417, -830, -82, -664, -1837, 946, - -370, 1434, -50, 742, -2368, 1438, 1264, 1172, - -1338, -108, -226, -958, -2130, -2, 917, 896, - 1563, 2181, 2684, 2343, 237, -407, -2685, 1447, - 1028, -728, 109, -620, 478, 46, -542, -789, - -879, -438, 1244, 1075, -1730, 119, -694, 137, -}; - -static const int16_t cb1110sm0[] = { - 916, -269, -44, 343, 623, -2512, -171, -1904, - 1001, 2776, 226, 1487, 705, 763, -616, 288, - -212, -535, 3080, -352, -367, 512, -673, 620, - -874, 769, -956, 460, -601, -2793, -102, -765, - -431, -1369, 149, 481, -49, 109, -412, 670, - -615, 287, 150, 321, -3293, -237, -1627, 188, - 1867, 1481, 353, -134, 2706, 147, 74, -77, - -148, -224, 196, -60, 179, 125, -13, 1011, - -189, -172, 658, 4441, -540, 531, 239, -329, - 2782, 392, 97, -660, 3488, -78, 1308, -574, - -903, -170, -279, 173, -70, 601, -385, 123, - -423, -512, -193, -233, 106, 175, 210, 185, - 489, -236, 153, -670, 25, 61, -196, 213, - 67, 339, 5443, 116, -647, 149, -130, 197, - -11, 305, 2669, 1212, 298, 84, 219, -26, - 2661, 650, 1348, -65, 574, -1482, -268, -30, - 626, 328, 279, -245, 87, 94, -202, 2, - 366, -505, -592, 2, 5666, 384, 22, 227, - 208, -1221, 78, 155, 260, -1111, 165, 396, - -678, -739, 2503, -2395, 2025, 1424, -343, -759, - -837, 101, 55, 274, -481, 22, -568, 1044, - -271, -124, -609, -833, -206, 53, -591, 1150, - -1950, -2875, 1949, 59, -334, -3230, 176, 1133, - -372, 2937, -803, -663, 631, -659, -32, -82, - 851, 113, -60, -625, 556, 177, 112, -753, - -33, 313, -33, -208, -177, -5496, 55, -533, - -815, 123, -755, -215, 638, 223, -156, -917, - -166, -33, 504, 704, -3001, 124, -153, -1809, - -977, -717, 1718, 476, 212, 1661, 953, -1422, - -1014, -94, -524, -2562, -267, 371, 104, -63, - -546, 262, 193, -1714, 261, 1867, 738, -1878, - 400, 1754, -445, -405, -841, -439, 709, 44, - 675, 248, 640, -138, 1217, 393, -1402, 653, - 3110, -938, -2491, -688, 1214, -649, -1356, 2506, - 203, 172, 679, 1003, 772, -3010, 82, -998, - 1011, -980, -28, -138, -430, 614, 427, -341, - 201, -8082, -118, 224, -1167, 195, -920, -352, - -657, 5, 46, -39, -72, 698, -136, -40, - 391, 287, 157, -1197, -60, 2808, -123, 489, - 152, 2318, -805, 958, 98, -1496, -835, -846, - 589, 455, -868, 245, -10, -5047, 12, -50, - 1277, -95, 456, -49, 570, 608, -658, -352, - -277, -268, 214, 388, 1865, 2, 3033, -269, - 259, -75, -3437, 800, -190, 668, -263, -111, - 229, -43, -139, 659, -290, 782, -18, -854, - 271, -2223, 30, -162, 71, 47, 756, -1269, - 336, 863, -1998, -16, 1172, 236, 929, -477, - -2446, -92, -425, -193, -8192, 321, -102, 85, - -85, 108, 318, 149, -27, -182, 69, -237, - 35, 451, -263, -890, -348, -295, 64, 410, - 6427, 569, 604, 543, 38, 31, -15, 148, - 249, -83, -67, 457, -76, -560, 694, -797, - 190, -113, 2006, 136, 1705, -428, 3549, -550, - 70, -3, -147, -288, 1142, -919, 493, -1305, - -460, -151, 831, 623, -768, -211, 31, -296, - 167, -2721, -16, -654, 243, 2555, -311, 1845, - -531, -576, 143, -574, 490, -1089, -2302, 1080, - 701, 472, 2782, 320, -1455, -632, -218, 281, - -1492, -661, -1379, -538, -236, -1928, -502, -565, - -480, 525, -81, 38, 263, 3, 366, 163, - -3140, 882, 189, 1123, 382, -1748, -1210, 371, - -602, 696, -413, -207, 358, -616, 4725, -473, - -784, 249, 621, 764, -265, -1004, -570, 339, - -643, -123, 302, 284, 1, -159, -321, 250, - -297, -43, -3512, -1064, -493, 556, -1184, -263, - 1314, 2028, 1074, 9, 2941, -998, -271, 966, - -754, -2589, 88, 741, -307, 134, 152, -86, - 311, 904, -917, 1199, -5090, 118, 181, -311, - -412, 475, -647, -717, -637, -221, -291, -469, - 77, 946, -1196, -119, -175, 530, -465, 383, - -1253, 589, 826, 835, -3578, -319, -80, 488, - -238, -497, 360, 839, 1870, 762, -1669, -769, - 429, 778, -3121, -325, -55, -128, 2606, -874, - 1043, -902, 1746, -725, 115, 167, 142, 604, - -101, -725, -11, -458, -27, 450, 293, 2, - -383, 23, 172, -6725, 400, -205, 165, 45, - -38, 86, 372, 354, -68, 390, 2444, 521, - 4, -3586, 357, 129, 665, -328, 524, 113, - -446, -514, 1132, 289, -560, 239, 167, -349, - -724, 101, -3165, -3139, -163, -147, 865, -617, - 0, -789, 797, -1026, 432, 359, -460, -105, - 1119, 486, -233, -360, -175, -349, 837, 469, - -250, -521, -4470, -108, 1009, -575, 283, 22, - -555, -682, -234, -249, -33, -106, 521, 515, - -283, -78, 101, -135, -648, 506, 181, 392, - -517, 5405, 442, -106, -8168, 51, -310, -813, - 49, -314, 586, -479, 376, 113, 337, -151, - 245, 270, -1, 619, -312, -37, -215, -482, - -3055, -3261, -346, -493, -357, 306, -160, -21, - 258, 872, -577, -141, 18, -84, 693, 151, - 218, -533, -37, 540, 61, 40, 3150, 157, - -2549, -324, 267, -456, -1236, 798, 517, -224, - -196, 587, -495, 18, 258, 3147, -15, -568, - 957, -444, 637, -354, 828, 1182, -769, -137, - -2130, 408, -1667, 252, 282, 201, 239, 154, - 125, -7882, -332, 198, -47, 265, -289, 358, - -4, 103, -795, 207, 82, 229, 429, 361, - 263, -409, -451, -1036, -3419, 899, -568, -1480, - 898, 284, -53, 179, 975, -1283, 759, -150, - 3244, 408, 2579, -418, -117, 226, 583, 210, - -62, -1513, -148, -820, 1073, 1290, -263, -454, - 653, 555, 286, 218, -105, -135, 231, -892, - -284, 2513, 2715, -1530, -165, -1419, -223, -66, - 525, 1556, -18, -664, -19, 856, 179, 535, - -339, -245, 498, 193, 235, 328, -491, 231, - -5629, 65, -85, 313, -395, 6, 344, 267, - 672, -991, 178, -1335, -64, 9, -1508, -69, - 57, -310, -1793, -850, -3669, 427, -79, -720, - 219, 366, 131, 523, 141, -1055, -66, 13, - -843, -55, -794, 661, 112, -407, -496, 550, - 931, -3938, 1780, -509, -543, -157, -270, -1015, - 564, -231, -854, -3372, -327, 869, -196, -981, - -205, -215, 605, 746, -2188, 2250, 74, -2979, - -242, 832, -190, 365, -1327, 453, 95, 76, - 158, -683, 628, 297, -867, -542, -143, -568, - -414, 6018, -40, -35, -456, -632, -779, -226, - -442, -295, 310, -766, 578, -197, 84, -961, - -3346, -106, 3266, -3, -477, -8, 652, 122, - -606, 49, 34, 686, 385, -258, 214, -572, - -72, -193, 124, 440, 48, 45, 75, 9, - -7724, 200, -364, 578, 318, -461, 84, -233, - 46, -404, 185, 470, -3387, -3397, 374, -519, - -320, -378, 27, 921, -280, 188, -245, -69, - -322, 504, -72, 460, -80, -35, -220, -3098, - -3678, 477, 248, -801, 580, 187, 468, -636, - -364, -432, 183, -82, -79, 266, -787, -740, - 552, 228, 238, 482, -2229, 275, 149, -360, - -350, 2774, 871, -118, 55, -961, -165, 2429, - 982, 313, -502, 3094, -431, 3485, 473, -347, - 171, 544, 253, -324, -50, 464, 116, 650, - 1102, 495, 420, -404, -1, -2991, 4055, 207, - 374, -187, -121, 130, -451, -953, 822, 526, - 287, 120, -979, 376, 594, -79, -130, -362, - -979, 166, 693, -4108, 84, -135, -195, -703, - -1506, -1098, -611, 870, 935, -156, 974, 286, - -86, 83, 2975, -681, 3218, -286, -452, -70, - -113, -395, 137, -1295, -503, 853, 297, -352, - -1004, -117, 476, -431, -2848, -7, 3601, 402, - -534, 312, 86, 1524, -358, -164, -43, 913, - 1003, 239, -364, -88, -468, -672, 220, -211, - -326, -431, 438, -297, 380, 125, -146, 4550, - -271, -831, 768, -1360, -45, 266, -278, -246, - 625, -132, 153, 514, 115, -1311, 707, -361, - -601, -3224, 376, -2107, -259, -1155, 426, -646, -}; - -static const int16_t cb1110sm1[] = { - 360, 3106, -518, 185, -906, 3245, 508, -91, - 938, -1270, -492, 36, 168, -997, -208, 991, - 99, 1553, -294, 204, -22, -108, -2405, 2893, - 49, 72, -490, -529, -218, 1343, -786, 903, - 411, 207, 131, -636, -129, -134, 621, -253, - 319, 135, -234, -75, -293, 46, 207, 5985, - 280, -86, -78, 690, 984, -770, -565, -226, - -242, 374, 26, -696, 81, -277, -9, 639, - -730, 250, -232, -488, -284, 460, -398, 4336, - -303, -266, 546, -292, 2936, 70, 2077, 373, - -141, 292, 2102, 340, -312, -523, -341, 1017, - 457, 224, 315, 271, 1080, 152, 192, 568, - 1014, 155, 85, 329, -5235, 137, -503, 141, - 275, -7, 752, 282, -267, 321, -735, 746, - 489, 450, 478, 432, -152, 451, -1192, 1267, - -341, 1136, 100, -3538, -1551, 1547, -551, 294, - -473, -821, -51, 718, -655, -11, 2817, -26, - 73, -459, -1569, 181, 516, -151, 2846, -112, - 186, 714, -228, -210, -451, 920, -99, -132, - -2662, 589, 3040, 376, 662, -834, 782, 542, - 1485, 538, 3531, 107, 47, 62, 398, -11, - -15, -733, 471, -231, 668, -212, 38, -536, - -1905, 2769, -149, 1623, -3418, 237, 55, -328, - -770, 335, 2755, 340, 62, -466, 267, -946, - 427, 266, 80, 1134, 34, 949, 366, -339, - -112, 3, -105, 442, 5117, 545, -93, 611, - -186, 566, -39, -172, -59, -1120, 388, 703, - 619, -359, -117, -68, 569, 148, -214, -245, - 281, 617, -2337, -88, -255, 124, 3292, 443, - 434, -17, -1157, 3090, -205, -245, -983, 250, - -1086, 643, 1392, 831, 733, -59, -1199, 1747, - -415, 1073, 279, 428, -512, -3392, 0, -6, - 526, 275, -79, 477, 411, 85, 1485, 795, - -209, 495, -2628, 367, -1734, 900, 301, 239, - -53, -2068, 403, 1333, -1304, -566, -1420, -771, - -2300, -15, 842, 342, -2373, 61, -1379, 303, - 733, -108, -316, 94, -477, -254, -211, 807, - 273, -792, 159, -66, -857, 1092, -1001, -69, - -3770, 999, 2418, 854, 173, 2281, -681, 485, - 578, 145, -1245, 845, -375, 219, -259, 374, - 751, 226, -1347, -825, 66, 319, -173, 191, - 445, 284, 62, -8150, -71, 53, 637, -96, - 227, 75, 73, -88, 654, -24, -466, 477, - 671, -125, -942, 104, 248, -151, -383, 11, - 322, 332, 4160, 108, -301, 463, -402, 352, - -1799, 580, 1443, 396, 287, -158, -421, 340, - -349, 109, 61, 47, -2816, -298, -947, -817, - 673, 189, 36, 4069, -584, -335, 2608, 10, - -378, -630, -801, 228, 946, -405, -1186, 473, - 625, -2, -741, 523, 3747, 318, 733, 171, - 268, -2554, 402, -252, -205, 292, -351, 64, - 289, 801, 989, 435, -100, -163, -1215, -467, - 661, -714, 165, -228, -637, 1357, -498, -52, - 488, -3882, 130, -1053, 796, 1040, 381, -729, - 147, 803, 169, 46, -157, 167, -209, 126, - -1016, 88, -1018, -458, -527, 1259, 621, 3847, - -525, 1247, 18, 253, 642, 340, -705, 838, - -2769, -672, 153, 115, 453, 773, 9, -2285, - -291, 6, -219, 628, 284, -330, 568, -240, - -206, -127, 273, 373, 367, -494, 8192, -595, - -255, -158, -326, -60, 513, 334, -667, -549, - -110, 2, 573, 1086, -610, -368, 259, -3611, - -455, 1577, -524, 11, 904, 390, 313, 707, - 2670, -223, 2710, 593, -25, 228, 540, 663, - 740, -1108, 298, 1223, -531, -1978, 248, -661, - -341, -910, -2434, 111, 217, 748, 231, -305, - -419, 1873, 1094, -936, -1741, 1133, 1881, -671, - 41, 268, -1826, 466, 135, 37, -200, 4623, - -1212, -969, 541, 1278, 652, 1061, -759, -747, - -427, -107, -1329, -583, -255, -67, -311, -10, - -421, -8192, 322, -181, -442, 76, 176, -742, - -175, 147, 385, -275, -87, -704, -545, -315, - -414, 569, 81, -387, 628, 2954, -604, -1459, - -29, 1693, 840, -1024, -66, -317, 266, -2465, - -917, -14, 151, -369, 366, -2388, 1, -773, - 1333, -99, 223, -694, -1169, 917, -2496, -1290, - -286, -1007, -508, 734, 451, -256, 266, -105, - -143, 439, -120, -146, 7690, -183, 188, 68, - -385, 7, -278, -24, -66, 292, 137, 143, - 21, -495, -527, -284, 89, -1584, -64, -3664, - 286, -2258, 80, -932, -771, -338, -830, -1029, - -99, -32, -800, 351, -87, 600, -93, 133, - 389, -690, 269, 201, -328, 5489, 558, -702, - -487, 210, 3107, -3628, -96, -388, -169, -221, - 339, 403, -816, -24, 469, -112, 560, 844, - -441, 698, 169, -378, -283, -924, 2842, -479, - -694, -117, -94, 523, 974, 1356, -638, 590, - 820, 2164, 247, -532, 648, -243, -599, -67, - 5686, 174, 78, -608, 230, -172, 369, 342, - -113, 111, -345, -311, 594, 350, -260, -1423, - -425, -407, -1017, -298, -180, -738, -891, 66, - -3312, -1157, 1, 811, -1431, 612, 797, -1344, - -890, -959, 318, 392, -190, 735, 196, -347, - 61, -116, 344, 243, -411, -446, 62, -128, - -3386, 476, 2695, -193, -39, 1960, -7, 909, - -118, -2275, -28, -997, -210, 374, -586, -82, - 914, 323, -73, -2743, 858, -65, 43, -2444, - -246, 145, 78, -638, 844, -2079, 352, -332, - 615, -779, 270, 1799, 680, 500, 686, 1168, - -397, -2233, -31, -163, -18, 602, -232, -915, - -941, 3708, -337, -559, 315, -401, 42, 26, - 316, -100, -191, 36, 206, 214, -3336, -407, - 494, 749, -491, -162, -55, -2902, -1515, -198, - -311, -359, 439, 359, -935, 203, -214, -2401, - -607, -2843, 818, -579, -2066, 388, -514, -912, - 787, 564, 149, -103, -757, 389, 173, -303, - 154, 814, 1631, -393, -2264, 1664, -802, 904, - 541, 784, 1063, 1152, -2510, 297, 84, -154, - 160, -497, -78, 1503, -598, -543, 86, 1683, - -330, 46, -24, -892, 747, -3336, -393, -2268, - 107, 710, 1682, -277, -278, -276, 1253, 327, - -986, 802, 191, -732, 286, -761, 1008, 461, - 1615, -1041, 2127, 2456, 3927, -160, 187, 31, - -101, 3258, 202, -75, 330, 375, -301, -275, - -782, 949, 12, -621, -617, 572, 1007, 414, - -91, -428, -392, -985, -692, -3422, 199, 845, - 91, 418, 290, -983, 721, -1265, 208, 1200, - 91, -758, -2649, -451, -814, -623, -458, 272, - 2777, 809, 1282, 763, 1122, 21, 520, 50, - -1018, 428, 385, 6149, -255, 8, -12, 21, - 20, 293, -315, -446, -423, 549, 428, -56, - -497, 101, 653, -177, -3975, 56, -127, 3214, - 291, -384, -721, 478, -314, -231, -469, -362, - -682, 765, -308, 420, 456, 322, -54, -2, - 10, -239, 6916, -461, -482, -211, -286, -110, - -877, -711, -470, 159, 260, 59, 252, -97, - -2978, -646, -35, 156, -123, 360, 556, -3254, - -475, -313, -268, -1771, -538, 203, 967, 283, - -653, -565, 387, -3097, -255, 25, 295, 264, - -3716, 505, 1024, -315, -215, -222, -780, 660, - 431, -341, -521, 46, 127, -244, -772, -3741, - 190, -335, -17, 2135, 744, -35, 627, -1115, - 681, -343, 123, -1534, -86, -542, -297, -82, - -2772, 3914, -75, 526, 124, -523, -112, 500, - 863, 371, 190, 1036, 141, -1011, 373, 796, - 421, -682, 403, 2924, 3730, 6, 211, -691, - -167, -391, -655, 162, 348, 216, -227, -535, - -147, 367, -189, 331, -191, 159, 49, -4905, - -252, -290, 609, -452, 1042, 1027, -645, -159, - -633, -542, -925, -262, -91, 192, 1266, -2, - -164, 587, 188, 3434, -1014, 2, 1373, 1832, - -1224, -965, 831, -987, 1180, 1389, -925, 48, - -3239, 263, -329, -660, -733, 262, -988, 598, - -2421, 630, 720, -925, -455, 208, 1092, -294, -}; - -static const int16_t cb1616l0[] = { - -15, -7707, 115, 30, -36, -27, -22, -43, - 2, 5, 31, -1, 87, 2, 41, 21, - 270, 16, 3747, -773, 3027, 224, 92, -168, - -7, -62, -79, -44, -9, -4, -58, -78, - 1063, 203, -2, 76, 289, -36, 92, -29, - -78, -148, -5176, 137, 219, 299, 89, -233, - 62, -129, 33, 123, -30, 197, 4018, -37, - -38, 139, 41, 153, 71, -26, 27, 53, - 72, 3358, -68, -122, 293, -19, -355, 104, - 34, 3121, 16, 29, -344, 37, 174, -28, - -43, -102, -59, -1661, 14, 5, -62, -1, - 14, 15, -42, 4, -31, -2, 13, 23, - 957, -419, 20, 31, -14, 51, 24, -46, - 8, -16, 27, -75, -27, -33, -28, 18, - -67, -152, -48, 47, 90, 48, -74, -103, - -18, 4863, 3, 132, 414, -86, -60, 285, - 16, 32, -44, 0, 22, -163, 23, -3, - 23, -61, 13224, 52, -139, -13, 171, 215, - -51, -21, -48, 33, -10, -17, -21, -7662, - -57, -44, -51, 35, 35, 34, 105, 178, - -77, 77, 147, 67, -816, 2913, -3087, 516, - -112, -296, 21, 133, 211, 162, 87, -25, - -535, -830, -12, 46, -59, -10, -4, 42, - 0, -91, -9, 47, -90, -29, 74, 322, - -106, 83, 44, 4693, -788, -73, -85, -105, - -76, -1031, 34, 6, 78, -34, 160, -48, - -707, -12, -9, 39, 14, 23, 88, -2286, - 21, -25, 42, 130, 39, 251, 16, -50, - 397, -226, -2570, 88, -129, -347, 159, 92, - 0, -44, -49, 235, -196, -24, -36, 113, - 13387, 45, 22, 54, -20, 29, 27, -27, - 54, 38, -63, -12, -74, 45, -8, -115, - 591, 46, 5, -234, 57, 124, 86, -3794, - -51, 292, -160, -152, 96, -334, 348, 96, - -186, -3870, -3715, 54, 0, -29, -65, -68, - 6, 132, 47, -155, 62, 26, 66, -10, - -46, -3093, 66, 3633, 183, -171, -132, -24, - 154, 157, 129, -185, 12, -26, 96, -12, - 88, -34, 42, -15, 37, -6625, -27, 13, - 41, -30, 62, 142, -93, -168, 84, -22, - 139, -19, 18, 10590, -111, 36, 13, -44, - 4, -45, -3, -3, 28, -25, -4, 115, - 119, -49, 41, 33, 87, -85, 12444, 73, - 71, -111, 61, -15, 117, 23, -24, -5, - 131, -31, -1, -22, -57, -12, 50, 35, - -1555, -20, 38, 82, -52, 27, -128, -14106, - 808, 190, 89, 595, 63, -291, 282, -48, - 32, -706, -433, -673, 3285, 1311, 830, 3745, - -204, -1185, -584, -51, 952, 1005, -566, 1764, - 186, 1211, -495, -112, 1213, 192, 2320, -43, - -30, 24, -1152, 2, 2, 32, -55, -25, - -2, -17, -14, -6, 22, -54, 32, 45, - 10, -85, -26, -16, -66, -60, -210, -104, - 208, -248, 62, -28, -14552, -11, -44, 1601, - 47, -138, 46, -35, 2647, -81, -3, -38, - -66, -59, -33, -19, 43, -17, -79, 53, - 1821, -1572, 2582, 85, 48, -140, 78, -155, - -173, 96, -32, 121, -58, 201, -174, -54, - 74, -2442, -282, -771, 37, -2930, 15, 1762, - 154, 263, -15, -19, 139, 246, -243, -31, - 84, 145, 8, 152, 43, 128, 679, 1828, - 3476, 17, 92, 102, 258, -29, -275, -39, - -187, 88, 70, 28, 2, 2143, 274, 202, - -67, -13, -22, 68, -35, 135, 114, 108, - 27, 1, -11248, -100, 14, 26, 59, 10, - -24, 30, 1, -38, -9, 21, 18, -1, - 2029, -83, -342, 3443, -25, 7, 0, 54, - 78, 198, 45, 233, -6, 0, -109, -172, - -2250, 41, -79, 2820, 44, 216, 39, 59, - -41, 52, 79, -52, 12, 23, -72, -125, - 83, 17, -28, -32, 13, 2, 28, 0, - -26, 75, -81, 66, 25, -81, 6516, 9, - -93, 49, -4036, -2484, -42, -71, 178, 99, - -133, 79, -41, -112, 57, 66, -28, 13, - 39, 64, -123, 3174, 3061, 259, 55, 123, - -123, 246, -138, 139, 75, 31, -215, -154, - -218, 26, 16, 21, 126, 26, -33, -10, - -15, 16, -20, -53, 21, 15526, -35, -59, - -50, -11, -58, 67, -11, 107, -24, -37, - 8155, 31, -111, -62, 138, -60, -10, 84, - -128, 37, 24, -45, -10, 129, -68, -37, - 42, -80, -205, -79, 5994, -93, -270, -400, - 20, -89, -39, -200, 230, 197, 325, -305, - -294, 94, 3207, 128, 3119, 226, 28, -49, - 264, 186, 8, -29, -13, 27, 22, -63, - 43, 84, -19, 57, -2605, 316, 259, -43, - 50, -2241, 105, -12, -23, -36, 89, 41, - -15, 145, 10, -81, 7, -50, 70, 60, - -23, 55, -62, 0, 52, -77, 180, 74, - 79, -14297, 6, 24, 299, -107, 4, -29, - -3252, -51, 40, -143, 3550, -28, 102, 24, - 215, 147, -169, -60, -43, -486, 5, -1, - 62, -116, -2917, 430, 50, 2927, 139, 127, - 63, -53, 141, -255, -85, 95, -101, -176, - 195, 104, -3066, -56, 3239, -161, -214, 57, - 24, -375, -181, 0, -259, 130, -120, -2, - -6, 175, -147, -185, 68, 219, 425, 2685, - -3120, 266, 246, -270, -70, 273, 168, 121, - -143, 2641, -553, -547, 638, 113, 2965, -161, - 29, -374, 105, -869, 108, 70, 15, 230, - -54, -106, -21, -4, 86, 85, 155, -120, - -17, -21, -2534, 57, 149, -129, 21, -169, - -2289, -127, -19, -26, 3, 60, 35, 1, - -28, -7, 36, -180, -13, 87, -68, 56, - 80, 64, -8, -73, 6691, -32, 47, 48, - -6, 61, 36, -8, -41, -1, 13, 68, - 140, -51, 25, 12, 3, 57, -54, -33, - -19, 12, 28, -60, -56, -2399, -14, 127, - 1935, 84, 127, -193, -3, 3307, -56, 15, - 31, -116, -187, 236, -289, 261, 69, 144, - 1723, 79, -68, 102, 727, 69, 654, -60, - 21, 124, 3497, 248, -684, 1469, 368, -254, - -211, -2600, 771, -138, 368, 3089, 52, -206, - 147, 200, -15, -136, 194, -164, -352, -152, - -4870, 5, 191, -3, -97, 28, -41, 107, - 2, 11, 60, -76, -35, -42, 129, -77, - -2610, -295, -218, -369, 10, 253, 15, -125, - 74, -87, -70, 3366, 115, 240, -106, -93, - 121, 10, 36, 9, -18, -66, -77, 7, - 37, -76, -22, 2913, 242, 22, 172, 102, - 186, -231, 90, -11, -57, 45, -10, -44, - -84, 44, -117, -43, 49, 5585, 18, -166, - -43, 64, 28, -9, 26, -160, 31, -28, - 29, 56, 29, -57, 109, -25, 3140, -131, - 57, -20, 27, -27, -5, -42, -52, 18, - 23, -56, -38, -14, 213, -33, -86, -4741, - -151, -46, 1, -17, 46, 7, -13, 0, - 50, 28, -57, -7291, -20, 12, 66, 214, -}; - -static const int16_t cb1616l1[] = { - -81, 5, -16, 34, 19, 10938, 141, -21, - 27, -105, -110, 32, -67, -75, 19, -138, - 3, -14, -408, -302, 36, -4612, 23, -579, - -35, 19, -312, 35, 120, 97, 82, -109, - 41, -1745, -158, 299, -3069, 84, 18, -447, - -33, 65, -32, 45, -7, 144, 86, 100, - -1738, 250, -226, -137, 159, -45, 134, 438, - 102, 37, -15, -161, -23, 4221, 174, 47, - -264, -182, -182, 686, -248, 89, -41, 80, - -2687, -194, 2552, 407, -1106, -970, -181, -228, - 4395, 118, 1027, -255, 136, 100, -43, 246, - 80, 15, 34, 82, -54, -367, 698, 232, - -177, 45, -67, 49, 138, -158, 168, 202, - 43, -70, -101, 20, -97, -3465, -342, -255, - 127, 25, -52, -5, 7, 76, -3, 19, - -19, 42, 10, -63, 16, 121, 732, -3127, - -43, 116, 36, -2519, 23, 18, 181, 41, - -32, -11, 22, 51, 35, 16, -34, -62, - 1744, 94, 173, -1243, -262, 11, 3218, 239, - 149, -219, 29, 118, -382, -289, -42, 161, - 17, -1, 2551, -83, 90, -128, 138, 3238, - 43, -29, -112, 110, -268, 293, 23, -117, - -64, -137, 79, -70, -10747, -66, 73, 90, - 35, 90, -29, -78, -111, 75, 48, 8, - -169, 2944, 16, 89, 186, -34, 82, 241, - -46, 257, -243, 93, 2966, 178, -256, -18, - -33, 103, -320, -271, 3088, 2893, -250, 102, - 696, 124, -211, 18, -143, 97, 216, -99, - 195, 40, -35, 144, 26, 135, -152, -215, - 120, 25, -254, -1875, 657, 197, -3527, -332, - 310, -11, 1958, 102, -12, -45, 2, -127, - 4, 1, -19, 47, -20, -52, 97, -30, - -7738, 51, 26, 5, -21, 18, 15, 15, - 66, 30, -8, -7, -31, -1, -33, 38, - 164, 90, 6798, -33, -90, -17, -5, 14, - -42, 21, -20, -41, 48, -6, -36, 6, - -207, -4363, 5075, 31, 6, 100, 65, 86, - 19, -158, 28, -134, -91, -68, 9, -26, - -37, 2588, 307, 3467, -451, 101, -441, 323, - 62, 188, -132, -294, 98, -22, 152, -46, - 65, -39, -37, -82, -9, 18, 43, 17, - 8, 56, 97, -11564, 21, 15, 75, 85, - 155, 15, 32, 0, 20, -45, 7412, 48, - 3, 38, 72, 30, 23, 42, -20, -110, - -454, -233, 653, -325, -276, 504, -481, 583, - 270, -649, 481, -3166, 1619, 164, -90, 150, - 32, -96, -47, 49, -13, 115, -183, 75, - 62, -9026, 12, -93, -715, 6, 137, -338, - 810, -39, -277, -108, -20, 315, 572, -3, - -4570, 1053, -132, 13, 388, -223, -355, 31, - -47, 61, -113, 5, -38, 43, -47, -80, - 2550, 27, 247, 277, -86, 336, 139, 146, - -111, -73, 187, -312, 68, -276, 72, 638, - 73, 792, -170, 1383, 421, -703, -3813, 112, - 391, -195, -162, -28, -25, 317, 228, -83, - 4611, 654, 353, -380, -283, -627, -301, 161, - -156, -81, 5, -15, -13, -17, 53, -50, - 36, -66, -7921, -2, -54, -41, -26, 47, - -3, 22, -6, 11, 63, 2, 42, 71, - -50, -87, -39, 2, -56, -2, 11165, 44, - -119, -74, 131, 134, 5, 115, -39, 144, - -23, 0, 186, 4648, 351, 36, -70, -71, - 1706, 2131, -228, 42, 6, 8, 4, -43, - -12, -40, -44, -7, -14, 11, 83, -93, - -144, 186, -46, -9, 13, -87, -120, 70, - -209, 115, -3513, 139, -46, 133, 96, 25, - 215, -35, -437, 126, 403, -115, 145, 203, - -69, -334, 37, 934, -481, 3163, -2528, -49, - 57, 100, 76, 82, 251, 288, -114, 46, - -201, -161, -161, -716, -4080, 378, -830, -254, - 12, -2110, -300, 78, 288, 48, -90, -99, - -31, -110, 201, 66, 327, 119, -180, 148, - 633, 71, -4100, 33, 57, -9, -48, 151, - -20, 72, 71, -11, 39, -67, 176, 27, - 143, 198, 383, 155, 3182, -128, -152, -3209, - -172, -262, -13, 129, -167, -128, 55, 46, - -37, 70, 107, 7, -23, -2082, 241, 236, - -47, -85, 105, -47, -202, 208, 201, 30, - -106, -14, -38, 14, -45, 24, -24, 12083, - 22, 151, -58, -9, 59, 170, 113, -82, - 369, -155, 53, 97, -185, -57, 203, 311, - 236, 4789, -24, -591, -1463, 118, 94, -274, - 3188, -145, -406, 183, 0, -54, 17, -22, - 37, -55, -34, 63, -340, 175, -300, 106, - -190, -38, 67, -2, 19, -46, -42, 11, - -33, -33, -28, -10, -27, -9235, 29, 62, - -927, 1285, 49, 72, 65, 89, 57, -44, - -9, -15, 85, -1, 74, 81, -123, 160, - 69, -2803, -22, 47, -467, -74, 748, 168, - -9, 235, -3155, -154, 48, 483, -341, 74, - 2403, 97, 93, -106, 219, 136, -191, -50, - 7, 71, -103, 261, 3283, -124, -624, -2570, - 73, -31, 10, -73, 30, -15, -2256, -2, - -73, 55, 73, 14, -74, -81, 38, 352, - 108, -18, 25, 61, 54, 1, -5, 109, - 25, -2676, -25, -52, -316, 2, 36, -36, - -355, 40, -19, 120, 27, -4, -51, -8, - 42, -10, -28, -90, -143, 29, -10, -8442, - -22, -566, 59, -39, -1, 27, 29, -20, - 6, 19, 0, -36, 38, 68, -43, 35, - 22, -47, -146, 3567, 13, 12, 3230, -18, - -32, 75, -112, -8, -157, -23, 101, 165, - 198, 93, 383, 1236, 1077, -3592, -1401, 1135, - 844, -266, -74, -70, -280, -98, 67, -109, - 38, -5109, -66, -57, 89, -21, 6, 19, - -21, 70, 60, 76, 35, 18, 44, 51, - 45, 40, 54, -6685, -67, 9, 113, -29, - -10, -96, 80, 98, 103, -40, -8, -20, - -131, 15, 262, 47, -253, -116, -12, -4807, - 2, -81, 76, -46, 37, 353, -130, -191, - -127, -10, -35, 91, -122, 173, -165, -8, - -15179, 86, -186, 123, -295, -25, 21, 63, - -93, 730, 20, -120, -4624, 340, -253, -473, - 44, -18, -99, -37, -54, -317, 65, -52, - 2167, 68, -245, 224, 117, -180, -4695, -276, - 118, 142, -101, 202, -301, -33, -129, -303, - -90, -75, 50, 98, -56, -68, -153, -38, - 168, -278, -22, -64, 9757, -91, -23, 1284, - 53, 56, -11, -46, -1645, 11, 15, 12, - 8, -40, -2, 84, -56, 17, -7, -30, - -4010, -3557, -252, 56, -79, -87, -7, 8, - 79, 16, 21, 51, -63, -22, 118, 228, - -1525, -78, -22, -2, 16, -49, 17, -37, - -3, -14, 10, 31, 17, -111, 32, -144, - -3612, 3473, 79, 23, -89, 74, 33, -29, - 11, -42, -42, -129, -41, 155, 52, 31, - -162, 12609, 147, 17, 68, 2, 15, -12, - -39, 50, -108, -66, 121, 69, -27, 94, -}; - -static const int16_t cb1616s0[] = { - 1213, -1302, -1130, 90, -69, 22, -360, 360, - -55, 453, -705, 4416, 227, 173, -8, 149, - 210, -118, 51, -3759, 949, 2418, -238, 201, - -597, 94, -253, 24, 225, -497, -59, 273, - 576, 651, 608, -483, 335, -125, 256, -2873, - 318, -146, -650, -306, -2021, 1044, 41, -455, - -1120, 832, 978, 212, -463, -209, 12, -275, - -20, 118, 31, 639, 5933, -180, -121, -285, - 65, 212, 439, -135, 538, 116, -302, -245, - 2534, -623, 1549, -34, 727, -1750, 1477, 79, - 1669, -828, 618, -856, 773, -286, 343, -94, - 107, -320, -3144, -380, 694, -80, 843, 103, - -700, -269, 452, -6847, -12, -527, 97, -21, - -76, -246, 2, -104, -68, 98, 312, 117, - -342, 1025, 207, 838, -71, 2463, 60, -1294, - 1549, -1310, -202, -1585, 682, 327, 608, 649, - 664, -801, 588, 137, -468, 286, 234, -6726, - -107, 177, -147, 278, 118, -81, -242, 97, - -235, 1599, -877, 1985, 448, -319, -745, -504, - -433, -1859, -35, 286, -665, -1449, -124, -97, - 930, 2622, 682, 698, 1898, 1120, -323, -142, - -679, 294, -162, -539, -1649, 152, 23, -414, - 1493, 602, 913, 1428, -3212, -103, -330, 557, - 463, 92, 251, 339, 16, 936, -116, 229, - -827, -504, 2015, 1553, -503, -350, 214, 386, - 295, 2697, 429, 72, -705, -120, 427, -139, - -334, -318, -6613, -468, 10, -122, 59, -322, - -165, -144, 45, -427, -12, -79, -202, -266, - 981, -273, 240, -454, -30, -119, 340, 92, - -251, 247, 189, 71, 243, -5648, -601, -434, - -674, 867, -713, -428, -101, -231, 1144, -89, - -10, 57, 302, 154, 362, -425, 2014, 2577, - -8659, 389, -90, 76, 15, 147, 30, -202, - -99, -255, -242, -165, 257, 97, 41, -72, - 263, 613, 272, 400, 5020, -199, -196, -177, - -276, -25, 28, 97, -155, 119, 763, 33, - -3540, -1447, 16, -169, 148, -143, 707, -2483, - 178, 83, -83, 154, -75, -15, 153, 283, - -323, -139, -1390, 69, 725, -1744, 331, -3665, - 415, -514, -366, 124, 660, -295, 180, 77, - -228, 192, 684, -193, 4, 4409, 298, 427, - 591, 290, -159, -166, -372, -514, -1840, -562, - 795, -1765, -349, 1178, -1619, -391, 615, -784, - 1353, 746, -871, -994, 182, -464, -498, -96, - -306, -729, 743, 270, 223, -731, 73, 2692, - 1110, -2354, -328, -21, -172, -339, -528, 93, - -338, 548, 1498, 309, -134, 160, -247, -619, - 1127, 783, -1557, 400, 1035, -445, -155, -2443, - 590, -790, 137, 388, 1188, 844, -395, 1005, - 55, 1141, -122, -3174, 138, 155, -506, 306, - -3255, 2432, -116, -1289, -744, -350, 3, 192, - -156, 95, -552, -57, 329, -405, 737, 138, - -835, 4096, -1037, 797, -417, -418, -507, -694, - -256, 78, -94, -63, -93, 754, -555, -90, - -1518, -878, 167, -392, -100, -78, -80, -45, - 4774, 114, -284, -560, -21, 275, 15, -195, - -1692, -711, -1057, 167, -1555, -690, -263, -267, - 310, -229, -14, -880, 426, -2826, 320, -49, - -1223, -725, 3538, -270, -606, -1812, 481, -703, - 176, -284, -173, 271, 847, 711, 239, 314, - 1233, -61, 477, 429, -691, -156, 6712, 850, - 365, 229, -197, -355, 298, 250, 207, -437, - -1647, -261, 165, 114, 165, 1165, -58, -597, - -3290, -517, -478, -842, -187, -448, -302, -204, - 410, 544, 669, -2012, 476, 434, 214, 698, - 302, 100, 61, 63, -386, 918, 4434, -230, - 157, -1019, -1487, 2239, -774, -234, -378, 772, - -190, 270, -61, -19, 322, 488, 937, -3582, - -415, 2091, 1862, 81, -134, 1285, -2732, 221, - -235, 388, -216, -63, 664, -105, -37, 165, - 899, -373, 284, -375, 286, -263, -295, 276, - -246, 188, 5285, -303, 290, -60, -1, 95, - -703, -288, 74, -717, -127, -53, -422, -452, - 166, -54, -15, 268, 238, -31, -279, -5872, - 863, -907, -101, 885, 552, 442, -2336, -2142, - -804, -147, -791, 1000, 96, 250, -306, 134, - 743, -1648, -867, 673, 1594, 3725, 527, -676, - -661, 238, 262, 560, 277, -58, 444, 166, - -1039, -702, 558, -970, -1763, -1198, 580, 378, - -421, -972, 630, -279, -2456, -1222, -232, -749, - -3325, 174, 789, 729, -487, 583, -157, 1503, - -801, -38, -11, 556, 81, 1508, -140, 74, - 1373, 912, 1471, 4, -1080, -105, -58, -104, - -54, -544, -2392, 1550, 318, -506, -11, -180, - -1891, -230, -259, -1182, -154, 524, -568, 1972, - 546, 469, -720, 1089, -1530, -680, 1349, 429, - 82, -1524, 1894, -90, 188, -145, 15, -1113, - 15, 53, 282, 2212, -736, -941, -1148, -344, - 1473, 344, 392, -333, -556, -480, -3833, 35, - -160, -525, 151, -534, -782, 38, 520, -416, - -384, 7582, -158, -29, 74, -57, -23, 73, - -393, -245, -12, -260, -154, -319, 357, 247, - -306, 351, 273, 755, 227, 89, 283, -152, - 17, 5129, 191, -213, -531, 255, -468, -209, - 1128, 72, -807, 225, -319, 1638, 42, 20, - 935, -52, -326, 541, -1174, 130, 284, -112, - 444, 3959, 262, -631, -262, 275, 1025, 190, - 1125, -265, -95, 265, 35, 270, -92, -30, - -141, 325, -435, 45, -659, 149, 3648, 339, - -1701, -1338, -144, -989, -604, 84, -394, 168, - -302, -1294, -433, -921, 1271, 77, 374, -604, - -230, 97, 206, -138, 2909, 478, 707, 0, - 1242, -340, -1659, 349, 2751, -1175, -146, 1038, - 65, -775, -423, 14, 22, 41, -905, 287, - 280, -933, 195, -1817, 540, -2374, -661, -1102, - 879, 1232, 29, -1683, 286, -136, 658, -395, - -1782, -2823, -624, -223, -299, 2859, -103, -45, - 544, 82, -21, -263, -666, -362, -732, 249, - 1087, -242, 30, 663, -386, -350, 1240, -492, - -868, 69, -41, 35, 30, -1791, 3870, -455, - 1355, 1098, 2933, 347, 361, 79, 2855, -26, - -66, -598, -43, 21, -386, -802, -81, -436, - 846, -673, 377, -326, -1217, 1465, -480, -205, - -2168, -1689, 690, 355, 1192, 734, -113, 39, - -486, -644, 438, 1096, -723, -524, -1634, -621, - -394, 226, 167, -625, -709, 854, 3005, -910, - 13, -793, -1517, -1254, 18, -440, -836, 651, - -31, 229, -1081, -126, -191, -3612, 487, 451, - -292, 943, -2018, -618, -259, -649, -723, -447, - -238, 1096, -2228, 675, 563, -316, -1248, 32, - -28, 293, -1817, 226, 267, 1291, 624, -2279, - 143, 650, 5, -563, -504, -2124, -94, -1613, - -3050, 708, -3458, 442, 30, 65, -80, 89, - 204, -245, 94, 28, -2, -231, 623, -189, - -405, -2147, 1147, 3124, 806, 1048, 1145, 653, - 47, 86, -4, 46, 437, 229, -190, 310, - 1995, -48, -1015, -1806, -266, -941, 361, 179, - 172, 397, 182, 323, -516, 3435, 7, -5, -}; - -static const int16_t cb1616s1[] = { - -2521, -518, 1830, 985, -500, 109, -807, -197, - 543, -1036, 104, 1989, 428, 740, 1110, -366, - 1482, 899, -1828, 159, -3015, -311, -792, -42, - 3, -412, -157, -13, 863, -248, 261, -187, - -409, 156, 772, 271, 318, -262, 78, -571, - 28, 370, 119, 302, -4794, 106, -123, -153, - 1857, -702, 1090, -319, 415, -327, 2124, -170, - -411, 174, 62, -7, 921, -128, 735, -127, - 972, 1678, 166, -1471, -208, -224, 871, -900, - -223, -817, 288, -472, 10, 31, -401, -3201, - -1290, -3, -301, 183, 730, 473, 438, -81, - 882, -64, 2898, -242, 408, -211, -333, -254, - -820, 612, -1128, -60, -73, -2516, 45, 637, - -130, 459, -312, -223, -629, 1490, 1792, -199, - -21, -545, 1772, -1084, -173, 381, 380, 1289, - -117, 483, 138, -1200, -519, 598, -3453, 349, - -3102, 1260, -170, 238, -684, 48, -483, -883, - -879, 139, 298, -110, -203, -955, 195, 57, - -550, 1945, -711, -688, -1470, 1527, 58, 317, - 656, 310, 57, 162, 2006, 1387, 845, -127, - -398, 318, 2520, 2002, -906, -323, -194, 907, - 588, -228, -357, -316, 557, -596, -1559, -3, - 1614, 1317, -1701, 936, -89, -2270, 1327, 1046, - 400, -233, 18, -730, -23, -181, -593, 74, - -570, -969, 432, -261, -833, -90, -4675, 786, - -566, -183, -859, -554, 346, -493, -201, -220, - 241, -919, -1896, 265, -802, 1380, -718, -1103, - -574, 307, 138, -1260, 175, 2540, -82, 58, - 1046, -1381, 2486, 582, 455, 485, -824, -150, - 57, -45, -155, -490, -1108, -2191, 833, 423, - -2011, 267, 779, 140, -28, 57, 94, 6, - -301, 5, -833, -1226, -193, 1110, -63, 79, - -492, -1465, -2733, 444, 56, -1116, -601, 20, - -618, -1315, -695, 1146, -66, 336, -166, 158, - 530, -53, -371, -594, -685, 114, -146, 373, - 174, -1, 47, 119, -124, -121, -6697, -94, - -3544, 1506, 1221, -101, 2160, 558, -254, -728, - 511, 378, -383, 12, 626, 172, 183, 354, - 49, 1669, 1188, 3810, 409, 152, 694, -2520, - 342, 61, -85, -38, -170, 5, 305, 154, - -348, 699, 332, 2542, 673, -1130, -2601, 554, - 1483, 466, 271, 490, -644, 822, -96, 477, - 131, -2051, -111, 43, -31, -62, -767, -3257, - 663, 488, 1823, 522, -525, -249, 481, -7, - -1298, -941, -335, -566, 305, 534, -735, 207, - 709, -3170, 19, -20, -1888, 271, -1697, 117, - 1837, 2690, 305, -483, -463, 407, -706, 467, - 518, 1806, 244, -80, -453, -505, 882, 843, - 1328, -280, 175, 319, -842, 192, -680, -469, - 5440, -205, -187, 53, 332, 204, -184, 96, - 1026, -525, 20, 975, 125, -1562, -1873, -757, - -137, 133, -10, -340, -783, -1484, -2206, 1238, - -5212, -466, 129, -224, 17, 497, -41, 846, - 88, -41, 285, 284, -155, 21, -225, 150, - 223, -807, -444, -1141, -908, 292, -326, 559, - -446, -283, -41, -277, -3479, -667, 532, 83, - 257, 383, -2986, 1685, 697, 777, 1551, -142, - 1786, 579, -531, 787, 712, -984, 603, -174, - -459, 1303, -943, 741, 1103, -73, 600, -403, - -42, -169, -90, 220, 208, 105, -4083, -1069, - 981, -926, 124, 273, -145, -133, 307, 4720, - 209, 324, -79, 12, -41, -220, 211, -184, - 435, 307, -1544, 83, 1565, -445, -217, -648, - -379, -1270, -1590, -2337, -860, 348, 648, -157, - -785, 3318, -123, -138, -412, -876, 358, -173, - -280, -81, -149, -167, -160, -2113, 20, -40, - 1022, 432, -721, 55, -651, 17, -1135, -380, - -542, -1128, 2919, -475, -143, -53, 176, -152, - 7, -29, -172, 174, 195, -8005, 277, 105, - 35, 115, -314, 137, -253, 75, -278, 90, - -1508, 79, -153, -560, 1027, -349, -292, -466, - -1101, -324, -84, 4251, 822, -420, 55, 43, - 1886, 281, 964, 2408, 425, 1187, -27, -84, - -1277, 63, -978, -143, 506, 727, -155, -384, - 3434, 592, -262, -438, -30, 2849, -69, -58, - -181, -87, 20, 299, 412, -263, 702, 131, - -271, -10, 736, 121, -6299, -132, -116, 26, - -253, -586, 32, -145, -251, -12, 471, 135, - 585, 604, 29, 873, 363, -2, -1595, 41, - -1147, -142, 665, -2752, 1302, -358, -134, 29, - -691, -12, -702, -459, 100, 278, 9, 54, - 66, -458, 53, 213, 193, 14, -400, 4870, - -950, -209, 50, 470, 449, 3, -118, 2287, - -469, -58, 126, 1011, -826, 386, -1019, -2390, - -586, -1401, 137, 760, 141, -89, 117, -252, - 3106, -936, -198, 390, 463, -245, -509, -123, - 3057, 1200, 3451, 282, -332, -585, -662, -955, - 165, -276, 73, 373, 202, 506, 356, 125, - 141, -613, -670, 446, 2031, 1521, -446, 1339, - 198, -112, 214, 70, 265, -1310, 2492, -133, - -1880, -347, -961, 312, -3714, -475, 102, 391, - 64, 1091, -686, -101, 144, 447, 173, 66, - -374, 342, 69, -3379, -1331, 1160, -889, -858, - 982, -1613, -223, 57, 186, 428, 226, -477, - 449, -1052, -661, -382, 459, 277, -277, -250, - 12, 4077, -260, -161, -163, 38, 159, 243, - 131, 457, -2253, -301, -1626, 37, 806, 104, - 191, 1899, 346, 398, -1108, -623, -391, 1092, - 1252, 1126, 81, -116, 1192, 674, -1321, -32, - 1739, -708, -230, -844, -507, 415, 261, 211, - -619, -191, 5460, 8, 139, 197, 392, -556, - -215, 66, 64, -808, 0, -136, 151, 156, - 260, 94, 418, -1446, 1815, -540, -793, 451, - -477, 1788, -124, 330, 1638, 342, -503, -384, - -1201, -762, 929, -2886, 888, -63, 318, 598, - 42, -1226, -400, -462, -136, 321, 1872, 376, - 1260, 142, -79, 4377, 9, 294, -71, -190, - -21, -2612, -240, 26, -18, -227, 864, 79, - 2588, -882, 87, -2976, 9, 480, -1573, -170, - -429, 201, -124, 171, 632, -60, -447, 64, - -37, -1182, -86, -105, 2901, -3557, -134, 486, - 141, -259, 239, 465, 467, 1009, -409, 34, - 254, 2469, 1002, 834, 557, -845, 149, -747, - -504, 494, 1382, 1067, 353, 191, -1105, 1705, - -586, 1472, -444, -1303, 198, 602, 471, 468, - 4855, 127, -141, 487, -454, -138, -392, -118, - -491, -948, 58, -290, -7, -662, 229, -268, - -2, -537, -620, -4770, 1152, -173, 166, -69, - 32, -2555, 433, -583, -2219, 1107, 1082, -942, - -173, 399, -601, 250, 423, 125, -448, 352, - -571, -406, 0, 4735, -264, -174, -1020, 1105, - -1149, -171, -252, -130, -202, -74, 601, 601, - 570, -2742, -1403, 3129, -349, 194, 309, 130, - 261, 93, 154, -117, -418, -657, 270, -160, - 1660, -818, 613, -1458, -653, -3763, -232, 90, - -265, -99, -28, -13, -281, -553, 11, -142, - -1764, -4548, 936, -21, -683, -88, -806, -187, - 28, 78, -70, -99, -2, -493, -16, 48, -}; - -static const int16_t cb1616m0[] = { - -3821, -3397, 203, -25, -22, 68, 189, -13, - -286, 94, 18, 288, 29, -5, 3, -414, - 1483, -172, -1275, -180, -3792, 360, 145, -143, - 444, -139, -198, 70, -17, -353, -121, -6, - 76, -50, 2987, 173, -3070, -229, -16, 192, - 134, -55, -86, -200, 128, -2052, -59, -11, - -4, 309, 179, 494, -138, -363, -336, 119, - -127, 2497, -169, -316, -87, -538, 42, -534, - 315, 2364, 61, 269, -87, -94, 82, -2069, - 18, 1238, -7, 79, -9, 41, 70, 50, - 209, -158, -136, 28, -275, 62, 296, 77, - 6269, -184, 73, -19, -25, -57, 134, -52, - 8569, -176, -8, 17, 15, 79, 36, -137, - 12, 44, -270, 2335, 111, 517, -83, 207, - -276, 2577, -198, 83, 376, -75, -273, 62, - 109, 4, -48, 122, -41, 99, -87, 14, - -7696, -118, -66, 171, 96, -31, 123, -217, - -676, -439, 407, 97, -281, 1873, 626, -148, - -548, 1634, 704, 97, -2076, -336, 632, -371, - 113, 544, -88, 184, -2200, -420, -592, -168, - 759, 291, 2215, 704, -140, -145, -4088, 295, - 186, -270, 283, 294, -42, 76, 69, 41, - -140, 1635, -200, -682, 302, -192, 902, -540, - -843, -494, -529, 102, -759, -165, 3160, -180, - -1450, -424, -16, 6, -548, 296, -3056, 219, - -1883, -109, -566, -431, 95, -422, -532, -26, - 120, -46, 23, 174, 175, -369, 110, -2, - 25, 132, -1, -3338, -67, 2140, -25, 566, - -129, 35, 1187, 337, 1999, 2712, -71, 45, - -177, 94, -321, -197, -573, 98, 225, 46, - 53, 78, -40, 82, 23, 2718, 2534, 89, - -65, 77, 206, 343, 527, 102, -191, 94, - 463, 111, -4529, 97, 876, -205, -944, 181, - -132, 467, 366, 85, -302, -100, -33, -76, - -3087, -2546, 215, 277, -52, 352, 137, -45, - 162, 590, 406, 382, 85, -2824, 141, 219, - -3790, 40, 126, 32, 30, 100, 121, -210, - 196, -268, 178, 102, 1229, -80, -750, -11, - -57, 84, 238, 3571, 274, -254, 55, -1616, - -176, -755, 46, -1306, -201, -228, 101, 197, - -93, -156, 319, 82, -385, -17, -4660, 180, - 1278, -113, -215, 103, 832, -233, 412, 249, - -900, -132, -3427, 52, 416, 267, 317, -384, - 130, 78, 91, -360, 75, 386, 2219, -360, - -2975, 17, 286, -294, -213, 231, 131, 821, - -358, 222, -230, -44, -93, -1151, 294, -316, - -8, 129, 231, -993, -58, 3319, 48, -2546, - -213, -14, 3208, 162, -240, -176, 307, -165, - -20, 348, -113, -78, -91, -8, -261, 8033, - -179, 64, -7, -113, -59, -32, -170, 52, - 55, -80, 140, 64, -39, 915, 28, 416, - 38, -2328, 206, 115, 366, -92, 652, 110, - -2838, -59, 613, 23, 109, -151, -198, 185, - 3033, -122, 2863, -273, 86, 41, 114, -99, - 315, 372, 14, 2191, -171, 531, -18, -34, - -352, 130, -360, 117, -2896, 2, -564, 51, - 223, 57, -257, 3161, 3130, -384, 126, -40, - -160, -232, -138, 81, -34, -96, 82, 9, - 62, -161, 344, 100, 790, -243, -344, -393, - -531, 401, 90, 171, 144, -329, 7, -4639, - -135, -6, 351, -21, -195, 224, -25, 6027, - 224, -14, 344, 170, -169, -97, 252, -488, - -379, -73, 629, -9, 266, 152, -64, 330, - -8, 2080, -91, -3315, 229, 25, 45, -528, - -123, 2951, 40, -85, -4, -2695, -38, -112, - 84, -30, 79, 762, 151, -4089, -95, -151, - 9, 138, -206, -3, -2114, 99, -100, 116, - -403, -56, -8, -36, 115, -18, -195, -38, - -240, 8, -32, 122, 125, -7406, 45, -210, - 111, -152, -152, -35, -72, 28, -154, 303, - -3147, 459, -2881, -14, -13, -56, -126, -69, - -213, -97, 202, -88, -277, -557, 451, -376, - -91, 319, 141, 2728, 23, 2506, -101, 632, - 62, -314, 159, 44, 1231, -65, -37, 192, - 3118, -186, -396, -108, 71, 2111, 586, 95, - 15, -28, 176, 20, -67, 3, -265, 101, - -182, -21, -455, -15, -6225, -45, -353, -384, - -22, 113, -40, -47, 57, -73, -503, 134, - 736, -70, -125, -5, -250, 62, 165, 182, - 185, -132, 426, -276, 100, -497, -23, 81, - -112, -3528, -1997, -234, -154, -91, -125, -26, - 179, -611, 655, 767, -1064, 130, -264, 107, - 2811, -1391, 298, -20, 37, -74, -12, -157, - -270, -106, 2559, -89, -3107, 55, 187, -265, - 195, 140, 1, -484, 713, 171, -1123, -226, - 3666, -367, -516, -249, 38, 195, 236, -378, - -383, -205, -72, -7, 15, -9329, -6, -26, - 56, 141, 48, 6, -141, -95, -69, -40, - -99, -80, 73, -253, 456, -174, 51, -250, - -48, -2115, -63, -2555, -25, -2058, -58, 66, - 176, 14, -10053, -23, -39, -37, -15, 38, - 82, 11, 97, 169, 5, -67, 57, 61, - -2248, 108, -19, 256, -169, -122, -336, -431, - -77, -250, -156, -745, 184, 684, 10559, -199, - -34, -37, 96, -82, -17, 60, 65, 21, - -67, -337, 62, 35, 74, -214, 38, 47, - -129, 6139, -139, -57, -154, 261, 7, -127, - 109, 40, 179, -99, 198, -51, 48, -36, - -2377, -194, -334, -2826, 103, -220, -57, 41, - 979, -895, 68, -217, -1712, -430, -98, 91, - -107, -1755, 2615, 84, -500, 231, 480, -31, - 146, -157, -120, 152, 2342, -36, -1969, 57, - -109, 476, -243, 261, -58, 1998, 4, 1388, - -98, 45, -140, 400, -76, -321, -22, -9, - 210, 517, 5, -4708, 66, -330, -405, -19, - 2158, -65, -2163, 244, -16, -192, 494, -381, - -194, 413, 89, 220, 455, -54, 4, 206, - 221, -4998, 63, -365, 354, 364, 677, 207, - -66, -27, -477, -182, 841, 85, -40, 166, - -185, 321, -293, -181, -429, -231, 1401, -122, - 938, 67, -185, 51, 3188, -802, 421, -3230, - 1432, -432, -658, -587, -843, 421, 177, 446, - 510, -140, -90, -127, -78, 2, 1089, -185, - 301, -393, 4100, -152, 265, 224, 25, 95, - 534, 280, -254, -45, -5, -207, 49, -126, - 8922, 43, 9, 21, 28, 21, -42, -84, - 38, 90, -2014, 61, -149, 188, -3350, -120, - -43, 10, 14, 155, -225, -351, -114, 28, - -23, -4400, 367, -51, 76, -89, -113, 122, - 2007, 25, -348, -227, -370, -61, 135, -79, -}; - -static const int16_t cb1616m1[] = { - -321, -7, -6725, -36, 77, -20, -101, -529, - -166, 97, -76, -232, -70, 16, 13, 93, - -50, 222, -258, -4424, -125, 125, 83, 313, - -246, -325, 108, -331, 484, -188, 192, -964, - 2603, -38, -2236, 58, 337, -254, -17, -90, - -88, 40, -141, -1293, -56, -811, 247, -78, - -34, 144, 112, 43, 142, -137, -147, 56, - -406, 12, 210, 132, 3707, 109, -896, -268, - -2295, -509, 32, -219, 113, -104, 141, 273, - 18, -358, 16, -3354, 3474, -167, 220, 10, - 104, -175, -8, -71, -77, -48, 277, 82, - 86, 35, -712, -32, 36, -65, 213, 121, - -76, -742, 291, -4587, -169, -122, -77, -285, - 54, -120, 89, 71, 12, -133, 54, -215, - -1906, -115, 3220, -194, -391, 87, 415, -212, - -210, -138, 182, 590, 713, 944, 320, 142, - -1970, 197, -79, -548, 458, 2836, 33, -62, - -183, -149, -640, 147, -427, -113, -178, -1631, - -108, 2666, -58, 2210, -251, 288, 16, 382, - 2123, 636, -4, 1118, 232, 335, -33, -114, - 24, -68, 1309, -38, 2080, 534, 288, -162, - -630, -360, -643, 10, 62, -2229, 263, 19, - 310, -44, 419, 2846, -2579, -159, -246, 685, - -67, 394, 314, -356, -158, 19, 90, 116, - -2261, 163, 664, 163, -191, -49, -18, -308, - -15, 2508, -370, 693, -62, 818, -307, -658, - 133, 1858, -4900, 53, -2485, -48, -9, 126, - 159, 6, -71, 291, 102, -367, -62, 27, - 88, -6, 204, -65, -725, 31, -159, -1, - -5, 45, -133, -146, 261, -4481, -19, 694, - -261, -478, -177, 88, 214, -836, -14, -762, - -111, 501, 0, 254, 1971, -1024, 2678, -141, - -6064, 76, 430, 160, -195, -582, 280, 580, - 183, -315, -13, 665, -53, 315, -199, 438, - 220, 3267, 194, 2, 2808, -88, 42, 150, - -179, 237, -155, 143, 46, 99, 27, 30, - -6137, -51, -89, 201, 145, -179, 13, -358, - 55, 71, -3, 28, -9, -16, 125, 160, - 159, -21, -5407, -485, -4, -88, -89, 44, - 3, 166, 22, -413, 993, 80, 485, -107, - 446, -943, 1025, 261, -3, 2991, 547, -268, - -109, 536, -10, 187, 17, 388, -120, -71, - -343, -416, 162, 69, -9, 46, -477, 83, - 6134, 146, -236, -125, -94, -55, -274, -231, - 1120, 171, -139, -2714, 80, -111, 20, 2475, - -135, -1710, 317, -762, 155, 1222, 68, 1192, - -15, 1825, -36, -45, -120, -484, -131, -162, - -128, 163, -407, 72, -222, -46, -222, -5319, - 278, -373, -436, 284, 138, -243, -104, 28, - -77, 3022, 93, -15, -581, -498, 292, -165, - -1740, 121, 195, -1368, -134, -68, -20, -75, - -10, 113, 128, -381, -507, -237, -709, 13, - -22, 155, -5065, -95, 246, -226, 193, 687, - 1839, 246, -232, -359, 475, 106, 297, 205, - -2702, -378, -219, -20, 140, -3198, 192, -3077, - -135, -38, -23, 213, -72, 255, -90, -130, - -150, 62, -484, -94, -2625, -89, 344, -129, - 2655, 369, -35, 17, -697, 251, -343, 68, - 53, 176, 3104, 237, -75, -3020, 178, 45, - -86, 45, -115, 183, 49, 26, 140, 77, - 40, -2315, 249, 1791, 48, -755, -12, 201, - -455, -250, -62, 1729, -113, -959, 238, -114, - 289, -135, -2208, 2748, 65, 306, -83, 3, - -513, -481, -49, -163, -568, -88, 668, -51, - -2586, 106, -22, 584, -453, -350, 333, -177, - -236, -657, 536, -349, 394, -56, 14, 133, - -55, -84, 210, -19, -8647, 154, 80, 27, - -7, -76, -117, 100, -201, 1, 296, -101, - -6, 5642, 137, -59, -93, 95, -110, -280, - -61, -300, 25, 887, 43, -30, 2493, 76, - -22, -343, 489, 266, 308, 163, 132, -349, - 2021, 18, 15536, 61, 11, -41, -42, 41, - -4, -183, -40, -24, 26, 241, -102, -115, - -164, 2044, -35, -217, -226, 734, -228, -2546, - 218, 0, 122, -150, -528, -188, -1273, 155, - 107, -33, -37, -293, 6, 112, -155, -228, - 192, -2378, 153, -1045, 213, 2975, 39, -159, - -10, -41, 34, -125, 4, -30, 3907, -41, - 848, -346, 191, -195, -292, -126, 3421, -24, - -244, 92, 693, 64, -193, 192, 121, -33, - -141, 523, -162, 2754, 71, 59, 40, -63, - -142, -100, -338, 379, -136, -64, -196, 11, - 3198, 162, 2097, -132, -2359, -193, -398, -318, - 842, -635, -168, 425, 2001, -136, 290, 206, - 562, -96, -8, -214, -45, -11, 4, 52, - 177, -148, 229, 33, -48, -46, 6538, -106, - -27, -22, 6527, 20, -405, 157, 87, 208, - -117, -4, 30, 87, 28, -356, -76, -108, - -33, -568, -270, 177, 49, -457, -3210, 119, - 103, 256, -180, 211, -1209, -369, -256, 37, - -47, 4976, 84, 207, 225, 224, -425, 396, - 921, 58, -150, 104, 1509, 15, -58, 1724, - 47, -24, 21, 376, 353, 482, -236, 634, - 306, 3179, 73, -33, -54, -169, -214, 146, - 4322, -216, -644, 305, 305, -453, 53, 143, - -9, -1472, -141, 1314, 57, 40, -55, -80, - 67, 9264, 57, 86, 22, -147, 1, -6, - 0, 39, 7, 114, -51, -137, 155, -15, - -122, 5, 137, 125, 213, -6, 7158, 36, - -52, -54, 149, 901, 859, 703, 366, 673, - -13, 1186, 588, -202, -451, 18, -585, -250, - -2632, -134, 61, -3038, 1022, 78, -672, -276, - 96, 838, 533, -254, -525, -106, -378, 1627, - 12, 31, 317, -118, 81, 313, -186, 197, - 452, -2971, 83, 1326, 419, -2366, -328, -87, - -103, -243, -280, 25, -240, 590, -232, 105, - -2966, -2391, -326, 338, 80, -392, -243, 271, - -7, 1127, 1, 1901, -2279, -207, 32, -99, - 560, -193, 371, 494, 506, 255, 332, 10737, - 48, 8, -33, -33, 32, -33, 45, -104, - -259, -99, -37, -134, 72, -50, 138, 428, - -2258, 77, 744, 5, 96, 3020, -269, 49, - 112, -223, 186, 48, 224, 2571, 340, -129, - -39, -1900, -45, 1978, -261, 223, 294, 22, - -108, -58, 109, -31, -3252, -138, -2969, -19, - -133, 190, -36, 132, -136, 63, -175, 351, - -76, 232, -2708, -17, -24, -130, -474, 74, - -2978, 45, -139, -23, 227, -42, -141, 278, - 81, 8, -2491, -446, 315, -64, -167, -643, - -275, 100, 0, 2484, -482, -128, -144, -206, -}; - -static const int16_t cb1616sl0[] = { - -46, -5073, 119, -68, 8, -160, 201, -15, - 55, 44, 44, -197, -110, -83, -90, -66, - -29, -128, 2449, -182, 2226, 298, -69, 189, - -167, 199, -78, 60, -154, -169, -242, 189, - 214, 132, -41, 169, 222, -130, 209, 20, - -154, -327, -3458, 186, 1356, 672, 133, 100, - 375, -491, -52, -87, 153, 537, 2513, -349, - 47, -27, 118, -301, 250, 45, 191, -150, - 279, 2367, -70, 191, -301, -206, -5, -40, - -201, 3680, -67, 36, -341, -133, -197, -383, - -101, 21, -68, -1240, 69, -8, -7, -16, - 28, -47, -145, -169, 32, 170, 246, 149, - 3039, -2617, -42, -95, 184, -74, 71, -56, - -22, -85, -203, 129, 97, -105, -91, -304, - 4, 93, 89, 2724, 2809, -178, 52, -155, - -152, 149, 47, 182, 124, -75, 24, 256, - -38, 53, -135, 63, 70, 59, -59, 7, - 6, 46, 8192, -157, 142, 81, 121, 136, - -87, -147, -71, 59, 57, 119, 21, -1938, - 46, 186, 100, -158, -52, 34, 95, 22, - 20, 179, 112, 116, 234, 2551, -3012, -167, - -93, -379, -90, 24, 208, 257, 253, 23, - -1361, 209, 75, 191, -23, -115, 2024, 264, - 77, -159, 77, -219, -237, -154, 13, 273, - -3338, 122, -205, 3796, -96, 103, -136, -60, - 115, -81, 19, 69, 396, 225, -280, 86, - 329, 284, 505, 403, -37, 203, 310, -2587, - -2374, -241, -17, 492, -42, -32, 261, 112, - 123, -33, -1271, -112, -41, 12, 82, 67, - -71, 56, -10, -83, -28, 15, -12, 42, - 2292, 297, -235, -3, 528, -57, 159, -185, - -54, -84, -152, 775, 15, 54, 451, -294, - 53, -2, 141, 39, -65, 75, 149, -5460, - 17, -58, -126, -281, 264, 151, 362, -98, - 62, -2361, -2560, 173, 42, -290, -161, -96, - -52, 82, 130, -86, -150, 48, 20, -57, - 52, -2263, -96, 2662, -66, 21, 74, -37, - 22, 323, 64, 270, -141, -599, -300, -121, - -12, -128, -96, -3, -129, -4339, -293, -55, - 31, -82, 8, 82, -20, 58, 15, -238, - 140, -125, -98, 7632, -14, 96, -129, -12, - -39, 85, 0, -104, -225, 24, 3, 95, - -87, 115, 168, 19, 22, 95, 8056, 36, - -12, 106, -99, -15, -87, 112, -122, 55, - 14, 282, -31, 80, 42, -4, 81, -73, - 74, -10, 82, 35, 173, -20, -40, -8192, - -35, -386, 270, 263, -231, -142, 42, -445, - 204, 177, -330, -859, 715, 2731, 59, 2578, - 220, -478, 3, 410, -47, 61, -214, 2765, - -206, 174, 56, 427, 442, 118, 2708, -66, - -40, 41, 119, -65, -71, -21, 124, 106, - -18, -2586, -35, 106, -364, 286, -16, -178, - -146, -82, 157, 92, -4, -437, -131, -85, - -27, -90, 23, -58, -5332, 115, -69, -25, - -14, 13, 52, 14, -286, -13, -60, 16, - 19, 53, 35, 7, -21, 7, 231, 48, - 2495, -82, 2836, 44, -134, -76, 33, -394, - 47, -124, -175, 95, 103, 161, 57, -37, - 174, -499, 131, -394, 2007, -2596, -481, 294, - 152, 601, 144, -438, 109, -204, 317, 37, - 362, -153, 216, 269, -39, 1250, 505, 505, - 2571, -115, -595, -806, -998, 1226, -71, 26, - -67, 262, 51, -161, 183, 1622, -32, 233, - 3, -217, 19, -16, 209, 51, 40, -40, - -43, -27, -7227, 13, -128, -18, 82, 154, - 133, -121, 33, -66, 8, -102, 71, 8, - 2780, -43, 79, 3212, -282, -165, 125, 78, - -101, -59, 59, -136, 308, -61, -295, -241, - -29, 27, -326, 2932, -563, 308, -269, -34, - -158, -26, -64, -411, -75, 420, -294, -239, - -11, 429, 44, 36, 69, -200, -56, 279, - 80, -218, -294, -294, 252, 64, 7793, 7, - -155, -56, -3118, -2749, -178, 62, 441, 105, - -45, 23, 23, -101, -109, -26, -149, 566, - -29, -394, -850, 1699, 1986, 243, -665, 565, - 155, -1746, 96, -344, -651, 387, -363, 283, - 241, 101, 71, -18, -9, 43, 114, -22, - 9, -109, -119, -92, 117, 8192, -67, 87, - 174, -42, -195, 527, -155, -195, -167, -1619, - 2638, -824, 121, 44, 138, -808, 407, 584, - -217, -90, -278, 549, -118, -1278, 837, 220, - 142, -956, -294, 89, 2627, 269, -129, 253, - 10, 15, 167, 163, 87, -262, 89, 48, - 14, 24, 2967, -175, 2550, 51, 11, -152, - -111, 230, -267, -79, 321, -641, 507, -32, - -20, -238, 23, -322, -2506, 173, 2205, -91, - -21, -1594, 420, -157, 97, 64, 126, -38, - -84, 10, -85, 93, -21, 272, -427, 30, - -60, 61, -81, -40, 27, 18, -29, -208, - -70, -8192, 16, 15, 53, 34, 49, -26, - -2512, -152, 23, -77, 3015, 87, -164, 247, - 119, 91, 444, -43, -166, -26, 253, -93, - 50, 408, -3274, 913, 104, 119, 17, -54, - 42, 19, -294, -298, -416, -82, 38, -263, - 137, 132, -2609, -44, 2783, -34, -9, 266, - 8, 18, -183, 520, 515, -93, -159, -21, - 186, 27, -89, 137, 77, -60, -33, 34, - -5115, -44, -172, -122, -9, -104, 69, 16, - 94, 2813, -200, -142, -50, 375, 3276, -272, - -44, 47, -41, -188, 263, -237, -24, 312, - 120, -326, 823, 193, 410, -95, 356, 565, - 296, 1202, -2737, -968, 87, -204, -1329, -826, - -827, 584, 194, -31, -12, -109, -39, -7, - 73, 29, 24, -12, 256, -98, -46, 63, - 207, -8, 73, -342, 4578, -37, 60, -66, - 8, -39, -176, -125, -34, 57, -141, -52, - -39, -128, -50, -143, -85, -107, 19, -38, - 74, -40, -161, -54, -63, -3452, 176, 116, - 5274, 19, -42, 198, 3, 33, 80, -99, - -111, 11, -90, 97, -6, -3, -52, 301, - 2335, 148, -171, -88, 44, -404, 124, 4, - -80, 189, 2838, 62, -247, 394, -230, -91, - 92, -2587, 84, -139, -31, 3014, 25, 201, - -137, -64, 383, 2, -70, -115, -210, 43, - -1111, -403, -379, -9, 243, 77, -220, -60, - -38, -15, 7, 109, 41, 143, 56, -211, - -2492, -48, -218, -115, -321, -358, 388, -10, - -172, -52, 177, 2996, -96, 480, -23, -15, - 177, -225, 217, 10, 367, 129, -45, -114, - 23, 257, -48, 2497, 236, 12, 197, 245, - 19, -173, -321, 310, 406, -280, -72, -279, - 73, 3307, 245, 78, -186, 2928, 264, 263, - -227, 50, 172, 91, 293, 24, -148, -245, - -61, 219, -88, 169, 220, -99, 3222, 3, - 0, 103, 19, 116, 69, -180, -7, -49, - 26, -59, -93, -68, 123, 357, 241, -3308, - -297, 198, 40, -80, 285, 161, 90, -46, - -165, -32, 87, -5676, 254, -37, 7, -20, -}; - -static const int16_t cb1616sl1[] = { - 73, 78, -64, 76, 17, 6250, -4, -167, - 52, 4, -3, 11, -189, -19, -136, -220, - 15, 6, -420, -2205, 38, -2944, 16, 118, - -116, 61, 119, -390, 217, 548, 24, 161, - -24, -2342, -148, -159, -2783, 225, 401, -226, - 210, 643, -366, 240, 264, 167, 115, 827, - -39, -161, 30, -173, 42, 29, 98, 377, - -58, -163, -41, 27, 25, 4368, 87, -2836, - -175, -71, -62, -84, -476, 4, 2466, 113, - -2830, -916, 593, 276, -356, -427, -686, -215, - 2752, 395, -9, -345, 117, -122, -327, 92, - 107, -106, 32, 270, 271, 171, 3138, 198, - -46, -70, 46, 502, 91, 77, -19, 216, - 94, 122, -64, -392, -31, -2696, -364, -131, - -315, 129, -461, 229, 192, 236, 185, -263, - -173, 44, 24, -267, -40, -177, -149, -2471, - 26, 113, -183, -1693, -188, 48, 22, -73, - 50, -133, 58, -70, -173, -308, -442, -188, - 92, 389, -35, 167, 235, 66, 2593, 2435, - 244, 630, -22, 235, 112, -32, 533, -158, - 81, 71, 44, -59, -158, -23, 28, 8192, - -58, -181, 39, 220, -54, -124, -59, -277, - 71, 41, -82, -157, -6860, -4, 44, -84, - -48, 134, -193, 159, -45, 218, -47, -133, - 147, 1749, 765, -84, 184, -317, -286, -17, - -340, -262, -244, -21, 3122, 290, -127, -119, - 179, -128, -125, -439, 2766, 1917, 85, 57, - -32, 373, -16, 170, -74, 31, 425, 626, - 1, -511, 64, 387, 142, -621, 183, -224, - 220, 1195, 386, -3360, 332, 484, -1112, -96, - 187, 43, 1838, 39, -36, 13, -132, -8, - -1, -43, 29, -132, -19, 10, 10, -218, - -3659, 119, -103, -27, -29, -108, 13, 181, - 39, -117, 92, 37, -17, -198, 330, 538, - 17, 113, 4758, 1, 28, -10, 87, 22, - 96, -14, -99, -56, -130, 0, -55, 45, - -63, -2845, 2751, 464, -31, -62, 76, -154, - 88, 81, 125, 373, -348, 587, -314, -278, - -53, 2039, -516, 2437, 191, -212, 87, -2, - 181, -242, 117, 23, -63, 334, 145, 454, - 343, -235, 91, 69, -8, 2, -106, -108, - -5, 137, -168, -7818, -231, 25, 37, 75, - -138, 56, 142, -596, 130, -114, 3293, -366, - 290, 160, -2, -219, 83, 843, -18, 1289, - -177, 226, 667, 252, -683, 816, 26, 157, - 168, -487, -49, -3282, 432, 184, 1207, 23, - 164, 544, 965, -1, 61, -118, 92, 1359, - 89, -3234, 15, 496, 244, 177, -613, -160, - -23, -195, -111, -372, -115, 278, 96, 77, - -2567, 49, -423, -468, 13, -484, 1345, -298, - 194, -123, -248, -139, 738, 102, 1154, -335, - 2694, 1326, 213, 758, 17, 154, 609, -518, - -367, 201, -144, 61, 66, 2288, 50, 2688, - -87, 45, -13, -101, 127, -190, -40, -286, - 6, 121, 32, 31, 119, -85, 28, 93, - 8192, 273, 169, 44, 37, 255, -224, 219, - -34, -127, -134, 165, 169, 126, -188, -52, - 98, 15, -5820, -193, -331, -395, -1, 49, - -187, 55, -121, -196, 114, 10, 258, -145, - -14, -385, 105, -187, 59, 383, 5322, 147, - -110, -69, 378, 138, -352, -69, 15, -267, - 75, 162, -6, 3148, 515, 231, -74, -436, - 1288, 1234, -105, 68, -96, -166, -49, -64, - 144, -67, 135, 258, -71, -162, 156, -366, - -7, -67, -133, -20, -119, 71, -84, 31, - 26, 116, -2237, 212, 43, 380, -74, 13, - -7, 774, -1276, -103, -124, -48, -178, -319, - 26, 435, -111, 858, 295, 1601, -2727, -242, - 8, 36, -61, -20, -19, -19, 31, 258, - 21, -14, 381, -153, -8192, -99, 327, 72, - 175, -1181, -271, 104, -30, -135, -169, 21, - 29, -182, -25, 125, 165, -82, 73, -26, - 2311, -85, -2983, -125, 85, -206, -100, -100, - 36, -3, -77, -180, 35, 0, -170, 123, - 168, -302, 366, -334, 2936, -70, 404, -2870, - 13, 79, 226, -163, -242, -124, -40, -171, - -109, 189, 20, -52, 144, -1869, -88, 230, - -8, -27, 45, 131, -11, -188, 93, -227, - -452, -229, 158, 377, -9, -1736, 16, 3268, - -164, 41, 305, -414, -642, -111, -100, 118, - -155, -236, 936, -114, 51, 31, 60, 1299, - 5, 3048, 274, 273, -197, -289, -245, -288, - 1927, -7, 27, 307, 174, -243, -95, -134, - 14, 24, -119, -132, -2811, -254, 35, 95, - 22, 135, 21, -155, -80, -143, -60, -6, - 182, 77, 11, -197, -8, -6080, 28, 155, - 11, -27, 22, -48, -8, -50, -122, 11, - -34, 342, -1, 40, -208, 117, -35, -69, - 150, -3944, -425, 46, 456, 182, -451, -219, - 38, 15, -203, 766, -232, 243, -70, 179, - 2107, -222, 346, -166, 143, 239, 245, 59, - -137, 17, 475, -68, 2679, -423, 20, -313, - 74, 152, 171, -269, 68, 39, -4743, 94, - -3, 110, 134, -168, 73, 180, -116, 276, - -74, -203, 2, -83, 17, 170, 96, 169, - 75, -5541, 46, 20, -168, -22, 35, -74, - 104, -153, 264, 4, -57, 94, -192, 161, - 15, 7, 45, -186, 15, -125, 121, -4981, - -254, 179, 282, 72, 543, -97, 363, -5, - -67, -389, -66, 178, 427, -276, -2675, 447, - -2, -125, -223, 2869, -502, 117, 2017, -71, - 41, 9, 124, 19, 357, -562, 25, -385, - 80, -53, -175, 2532, -73, -2990, -164, 57, - -128, -254, 53, -150, -180, 16, -45, 322, - 266, -2418, -264, 317, 371, 5, 197, 7, - -2476, -93, 152, 90, -165, 11, -259, -24, - -55, -16, 98, -4904, -116, 53, 205, -45, - -57, 116, 75, 161, -55, 97, -292, 27, - -1396, 105, -127, 133, -265, -33, 5, -3622, - 25, -3, -104, 8, -283, -229, 236, -208, - 145, 627, -240, 118, 296, 108, -309, 48, - -3345, 582, 498, 259, 20, 785, -138, 421, - 97, 370, 161, 141, -2793, 106, -246, -140, - -172, 42, -194, -202, -319, -107, -24, 423, - 7293, -109, -13, -242, 55, 171, 13, -93, - 131, -141, 88, 132, 76, 176, 78, 153, - -63, -55, -410, -39, 6, 27, -223, -174, - 61, 645, 167, -35, 3079, -173, 950, 1, - -109, -118, -106, 15, -1345, -14, 50, -70, - -69, 24, 109, 182, 84, 31, -179, -93, - -3152, -3013, -60, 56, -60, 58, 166, -161, - 24, 129, 1, 181, 128, -12, 273, -43, - -1256, 134, 159, -36, 175, 43, -49, 41, - 48, -38, -45, 59, -36, -82, 48, -74, - -104, 2944, -124, -24, 98, 248, -146, -231, - -241, 72, -114, 776, -498, 242, -357, 250, - -102, 7121, 109, 11, 94, -53, 37, -37, - -133, 24, -157, 47, -46, -69, 62, -79, -}; - -static const int16_t cb1616ss0[] = { - 1401, 373, -516, 330, -711, -752, -475, -224, - 139, 492, -556, 4629, 1039, 333, 872, -542, - 474, -360, -378, -3459, 254, 1199, 113, -525, - -1705, 231, 46, 188, -50, -1038, 32, -198, - -109, 619, 1071, -1601, 1002, -411, -189, -3276, - 615, -468, -467, -275, -1286, 736, 541, -1107, - 423, 191, 439, -205, 17, -87, 500, 176, - 262, -341, -142, 268, 8164, -2, 112, -190, - 227, -50, -143, -326, 647, 601, 482, 443, - 2761, -497, 979, -298, 454, -2927, 746, -735, - 3921, 480, -167, -317, 1303, 111, 216, -961, - 110, -595, 244, 246, -222, -205, 46, 61, - -798, 258, 360, -7038, -654, -95, 75, 498, - -24, -250, 71, 138, 527, 240, -215, 250, - -408, 552, -325, 333, -989, 2648, -483, -1121, - 2344, -1647, -116, -901, 615, 327, 1, 497, - 411, -138, 332, 281, -145, 337, 163, -7379, - 70, 265, 365, 238, 604, 99, -149, 233, - 109, 827, -704, 1367, 1208, -717, -17, -223, - 15, -3259, 53, -485, -631, 285, 511, -8, - 242, 547, 129, 145, 2046, 520, 44, -177, - 382, 283, -169, -346, -2737, 294, -1311, 145, - 1873, 815, 1078, 677, -3419, -434, 484, 144, - -27, 669, 153, -242, -242, 814, 350, 361, - -462, -63, 2317, 1259, -373, -489, -534, 300, - 867, 2621, -117, -168, -414, -239, 812, 840, - 112, -463, -6286, -693, -830, 140, -168, 448, - 549, -149, 418, -105, 137, 31, -40, -43, - 422, -99, 297, 3, -220, -15, 81, 45, - -647, -535, -448, -731, 250, -6742, -320, -350, - -192, 1540, -1112, -1043, 1317, -1203, 1035, -506, - 673, 721, 854, -1487, 780, -294, 1173, 2142, - -8192, -170, -138, -54, -54, -233, -127, 145, - -233, -185, 87, 20, 530, -305, 141, -394, - 310, 40, 645, 809, 4801, -186, -432, -451, - 312, -144, -65, 65, 135, -64, -15, -357, - -3546, -1299, 216, 249, 261, -207, 117, -3138, - 527, 14, -142, 286, 100, 340, 581, 157, - 234, 739, -2521, -3, 639, -1440, 131, -3796, - 159, 39, 41, -659, 284, 165, 1100, -346, - -481, 295, 806, -227, -288, 4520, 253, 487, - -252, 88, -43, -1612, -5, -57, -66, 18, - 19, 557, -337, 1526, -2897, 144, 844, -404, - 1976, 787, 246, 264, -406, 778, -918, 51, - -113, -235, 518, 602, -307, -2046, -692, 2775, - 400, -2165, -184, 139, 403, -1855, -1317, 289, - 710, 1124, 1888, -517, 276, 190, 637, -441, - 717, 972, -370, 478, 626, -354, 241, -3651, - 145, 7, -738, 397, 991, -343, -826, 142, - 672, 2425, -616, -3278, 751, -193, -944, -35, - -1061, 1258, 631, -721, 145, -112, -69, 828, - -39, -196, -237, -73, 771, -195, 239, -533, - -1673, 3477, -559, 104, -647, -798, 167, -497, - -559, 591, 259, 300, -25, 422, 93, 39, - -63, 233, 144, -1170, 142, -456, 73, 411, - 6920, -338, -307, 436, 143, 420, 152, -9, - -1788, -1096, -2998, -727, -524, 128, 460, 782, - -102, -576, -138, -976, 1035, -3196, -436, -27, - -1047, -1389, 3244, -143, -883, -1012, 4, 327, - 16, 411, -497, 1444, 516, 1183, 252, 510, - -698, -676, 569, -70, -397, -227, 7829, 312, - -410, 20, 41, -65, -219, 175, 297, 40, - -1534, -498, 194, 871, 409, 280, 1098, -1471, - -2825, 931, -105, -545, -801, -795, -372, 73, - 331, 100, 488, -2101, 560, 44, 885, 1065, - 380, -195, 276, 124, -87, 193, 3979, 30, - 95, -509, -931, 2737, -457, 805, 10, 53, - -73, -203, -587, -177, 242, 238, 656, -3403, - -380, 2364, 2902, -226, 204, 1559, -2219, -40, - -442, 111, -703, -424, -252, -241, 461, 749, - 658, -481, 125, -366, 601, -246, -286, 132, - 297, -232, 5231, -141, 196, -121, -235, 406, - -199, -174, 87, -107, 363, 272, -563, -620, - 235, 223, -627, -339, -467, 349, -1596, -5496, - 644, -96, -81, 1938, 749, -160, -1976, -1436, - -1056, -1045, -1098, 2327, 976, -57, -124, 1139, - 275, -209, -636, 298, 2484, 2764, 962, -39, - 108, -718, -442, 9, 797, 1123, 1092, 1179, - -1170, -701, -381, -237, -1266, -1045, -337, -351, - -274, -981, -272, -111, -3409, -387, 421, -406, - -2123, 623, -18, 2473, 617, 176, 26, 1402, - -1351, 212, 23, -172, 296, 1572, -63, -402, - 837, -521, 2209, -613, -329, -309, -180, -1152, - -535, -1380, -2617, 475, 385, -672, 182, 92, - -2211, 320, 109, -633, -582, 1208, -1536, 1009, - 896, 1991, -374, 1750, -1259, -341, 1774, 1063, - 678, -2084, 987, -337, 48, -205, -82, -288, - 388, 217, 1263, 2427, -1472, -1073, -964, -836, - 2086, -161, 438, -449, -37, -926, -3706, 164, - -372, -616, 160, -572, -725, 727, 11, 53, - -84, 7494, -74, 523, -172, 464, 452, -426, - 803, 106, -262, 32, 298, -491, -181, -760, - -908, 303, 747, 1316, 272, 906, 767, 105, - 247, 6120, 948, -557, -928, -595, -342, -450, - 686, -815, -1243, -157, 572, 1414, 166, -229, - 3317, 1940, -283, 623, -781, 717, -212, -707, - 30, 3635, 1147, -696, -928, -637, 925, 797, - 843, -1359, 214, 1096, 1031, 852, -84, -228, - -34, 1067, -1109, 392, 292, -755, 3495, -40, - -1806, -637, -236, -602, -264, -147, -68, -233, - -55, -2005, -271, -647, 963, 309, -5, 56, - -275, -398, 34, -496, 2556, 1249, -87, -112, - 1663, -554, -1926, 627, 2515, -1128, -566, 1539, - 740, 38, -614, 272, -232, -152, -782, -420, - -304, -2313, -33, -944, -77, -3468, -69, -1730, - -21, 665, -314, -1640, 660, 661, 106, -21, - -1505, -2888, -427, -866, -666, 3128, 786, -55, - 739, 112, 8, 567, -602, -350, 165, 108, - 767, 64, -715, 980, 673, -186, 768, -545, - -298, -233, -524, -70, 511, -2051, 3816, -1104, - 529, 1012, 2577, 777, 342, -387, 2730, 247, - -20, -227, -432, -263, -885, -1192, -644, -259, - 2314, 38, 108, 614, -386, 470, -78, 681, - -3334, -1049, -300, 177, -174, -422, 110, -641, - -406, -472, 468, 885, -730, -877, -1972, -1372, - -410, 545, 543, -800, -1156, 279, 3290, -1305, - -213, -262, -832, -994, -1110, 718, -364, 1416, - -7, 963, 452, 680, 165, -3815, 903, 806, - 149, 11, -1332, -622, -451, 152, -618, -309, - 246, 435, -2098, 487, 469, -451, -1574, -204, - -187, 552, -333, 515, -331, 1452, 278, -2691, - -146, 1009, 353, -839, 6, -3206, -1080, -572, - -2698, 752, -1726, -318, 397, -152, -128, -77, - -36, -506, 456, 1094, 281, -158, -19, -149, - 48, -2831, 2042, 2545, -161, 619, 1129, 274, - 24, 1, 313, -164, 655, 157, 770, 182, - 1942, 241, -898, -1748, -589, 256, 322, 683, - -65, -73, 621, 74, -317, 2585, 185, -465, -}; - -static const int16_t cb1616ss1[] = { - -3218, -607, 1665, 1100, -563, 421, 377, 445, - -270, -3, -1503, 224, -593, -316, 31, 362, - 1186, 389, -1817, 589, -2842, 289, -1925, -356, - -228, -148, 618, 135, 358, 238, 1, -767, - -266, 1, 101, 245, 231, -167, 408, 1, - 162, -35, 241, 215, -4702, 486, 546, -339, - 349, -292, 1342, -881, 184, -675, 2639, -284, - -995, 346, -499, 1499, 1616, 578, 445, -78, - 844, 1800, -686, -414, -1425, 795, 754, -1418, - -178, -2226, 515, -143, 43, 569, 967, -2333, - -1991, 282, 528, 1410, -377, 736, 394, -230, - -365, -242, 2773, 136, -738, -36, -1171, -76, - -132, -300, -223, -680, -416, -2738, 93, 414, - 490, -346, 75, -1089, -1132, 2237, 1844, 395, - 325, -1514, 1913, -1850, 1162, -442, 689, -66, - -71, -83, 342, -197, -940, 206, -3381, -1275, - -423, -87, -455, 498, 865, 355, 1225, -115, - -3333, -404, -588, 1021, -2180, -1470, 1225, 728, - 59, 2592, -335, 194, -649, 3586, -951, -142, - -947, 898, -99, -269, 977, 1520, 488, -364, - -253, 127, 2524, 849, -1166, -191, 627, 372, - 772, 145, -21, 279, 402, -863, -2695, 1217, - 1543, 1005, -1419, 1712, 110, -2191, 969, 1563, - 183, 811, -218, -1078, -220, -1092, -322, 803, - -533, -359, 405, -70, -771, -267, -4730, 235, - -607, -387, -285, -68, 48, -60, -222, 229, - -1087, -1261, -2249, 1265, -1624, 864, -65, 223, - -322, 337, -262, -3170, -12, 4571, 19, 198, - 458, -1029, 2560, -3, -115, 619, -645, -836, - -399, 246, -81, -12, -1057, -2119, 2780, 25, - -1559, 291, 592, -513, 62, 157, 553, 570, - -657, 72, -118, -284, -454, 3853, 145, 259, - -1709, -2161, -3167, 189, -233, -1099, 141, 114, - -506, -1012, -775, 474, 331, 798, 469, 1915, - 96, -266, -385, -329, -658, 192, 16, 97, - -47, 284, -163, 200, 189, 18, -7453, 160, - -2988, 2725, 520, -132, 2593, 627, -694, -26, - -558, 44, -209, 40, 377, 491, -68, 384, - 271, 2117, 642, 3166, -569, 702, 513, -1858, - 108, 944, 248, 166, 681, 408, -908, 525, - -145, 1035, 189, 2812, 135, -356, -2551, 401, - 150, -508, -265, 244, 461, 958, -233, -204, - 744, -1603, 397, -229, -174, 539, -139, -4473, - 837, -310, 253, -635, 397, -80, 601, -371, - -2015, -261, -364, 50, 331, 89, -938, 709, - 1444, -2910, -228, -162, 419, 62, -319, -266, - 584, 3728, 57, 220, -543, 768, -630, 361, - 361, 642, -313, 182, -488, -48, 3001, -397, - 640, 179, 8, 1081, -1161, -58, -70, -64, - 4456, 323, 883, -191, -16, 61, 419, 429, - 627, -898, -883, 750, 499, -1335, -467, -1410, - -5, 283, -301, 276, -1636, 310, 114, -428, - -8192, 12, -114, 74, 215, 511, 317, -314, - -86, 198, 138, 315, -271, 246, -363, 426, - 608, -714, 367, -1356, -2217, 1178, -385, 1442, - 28, -642, -371, -87, -2895, -710, 303, -150, - -398, -868, -1727, 1548, 982, 1177, 332, -377, - 1580, 962, -1028, 1922, 1494, -824, 93, -1362, - -552, 1641, -1729, 228, 1054, 421, -185, -536, - 51, 87, -204, 88, -847, -754, -3761, -2706, - -138, -1242, 35, 64, 418, -460, 713, 3960, - 733, 468, -150, -823, -211, -674, 366, -269, - 180, -294, -384, 604, 1829, -121, 271, 241, - 192, -211, -2672, -1483, -1102, 960, 90, 49, - -1144, 2552, -887, -32, -301, 62, -183, 193, - 78, -781, 193, -606, -285, -3082, 240, 392, - 704, 20, -1103, -195, 166, 577, -105, -45, - -310, -106, 3035, 28, -369, 725, 53, 87, - -232, -191, 7, -282, -572, -8192, 325, 99, - 162, -113, -237, -209, 412, -573, 295, -389, - -1603, -66, -485, -867, 466, -882, 862, -216, - 221, 50, -51, 3927, 557, 441, 223, 234, - 4048, -173, 420, 1670, 436, 341, 175, -441, - -201, 75, -549, 315, 172, 418, -159, 7, - 2973, -3, -220, -1360, 26, 2781, 132, 295, - -15, 217, -166, 187, -282, 357, -121, 480, - -216, 294, 263, 95, -7367, 589, -63, -412, - -103, -201, 335, -96, -203, 240, 223, -435, - 366, -467, 118, 528, -472, -559, -417, -189, - -641, 339, 1546, -2741, 1413, -265, 637, -1556, - -49, 422, -195, 392, -21, 3, -2, 282, - -130, -272, -483, -860, -675, 762, -1455, 5212, - 178, 197, -468, 270, -310, 1038, 406, 2699, - -537, -33, 272, 225, -1986, 1295, -857, -2906, - -904, -1861, -206, 866, -145, -207, 252, -825, - 3051, -1361, -441, 85, -186, -127, 139, 285, - 3067, -332, 1163, 248, -483, -177, 268, 691, - 733, -104, -54, 2541, -1042, -226, 165, 250, - 7, -259, -383, 327, 2164, 2272, -750, 2482, - -930, -139, 1203, 766, 150, 320, 970, 28, - -1351, 467, 544, 521, -2908, -75, -902, 611, - 575, 1216, -209, -7, 541, 330, 528, 347, - -185, -306, -432, -3384, -1844, -380, 155, -1230, - 629, -1085, -413, 119, 114, 1093, 198, 806, - 491, -137, -518, 536, -64, 387, -1712, 608, - -24, 4961, 149, 299, -342, 505, 503, -387, - -944, -297, -2423, -98, -1027, -432, -259, 736, - 127, 3561, -473, -623, -751, 114, -438, 657, - 2448, 863, -413, -81, 2066, 988, -539, -528, - -111, 314, 390, -1228, -863, 19, 763, 2227, - -844, -24, 4164, 139, 130, -111, -630, -428, - 538, -606, 940, -877, 122, 526, 194, -104, - 127, 117, 907, -789, 2865, 526, -548, -253, - 289, 2329, 176, -70, 775, 681, 21, 38, - -1481, 766, 2093, -2974, -289, -571, -445, 1833, - 333, -84, -243, -413, 188, -492, -22, -867, - 605, -333, 904, 3192, -29, 491, -411, 370, - -556, -2671, -294, 132, -243, -233, 180, 181, - 383, -79, 26, -3539, 642, 1127, -2125, -170, - -386, -135, -703, -290, -157, -444, -885, -341, - -920, 460, -407, -176, 3153, -3084, -505, 543, - 7, 79, 1191, 1148, -401, -17, 289, -735, - 300, 1971, 626, -146, 110, -1281, -613, -649, - -206, 1850, 701, 1138, -803, 742, -1392, 147, - 554, 1861, -658, -1481, 108, 856, 1021, 574, - 3314, 518, -1156, -307, 42, -92, -132, 278, - -352, -37, 35, 146, -93, -662, 216, 125, - 823, -876, -170, -5027, 444, -182, 844, 189, - -490, -1441, -335, -907, -173, 1138, -472, -1505, - -1641, 648, 66, 627, 64, -1096, -620, 1588, - -506, 309, -100, 5702, -555, -157, -179, -85, - -299, -114, -20, 178, 415, 118, -581, -132, - 1025, -2631, -1154, 2623, -286, 201, 340, 949, - 235, 171, 649, 328, 397, -142, 1369, -7, - 2305, -373, 658, -1681, -744, -3574, 34, -183, - -504, 165, 81, 21, 635, -307, 428, -520, - 164, -4701, 744, 249, -844, -7, -334, 38, - 539, 267, -213, 73, 134, -251, -248, -923, -}; - -static const int16_t cb1616sm0[] = { - -4119, -2861, -76, -49, -192, -542, 0, 94, - -550, 6, 601, 236, -446, -202, 167, 238, - 2609, -688, -406, 265, -3078, 321, 59, -601, - 157, 200, -265, 78, -699, -679, 18, -54, - 203, -687, 2683, -111, -3037, -627, -493, 413, - -480, 54, 75, 276, 206, -1861, 17, -420, - -169, 312, 361, -277, -12, -363, -592, 758, - -123, 3267, 78, -862, 81, -356, 596, -536, - 729, 2239, -49, 553, 112, 444, 652, -2990, - -70, 1084, -436, 34, 53, -10, -23, 41, - -3, -126, 207, -130, -208, 63, 480, 191, - 6229, -45, -33, -82, 35, 56, 259, 1, - 8034, -97, 52, -159, -334, -41, 50, -57, - 56, -194, -567, 2050, 146, 987, -383, 416, - -258, 2846, 51, 8, 690, -126, -704, 316, - 16, -4, -90, 159, 34, 126, 65, 218, - -7037, -261, -87, -21, -185, 14, 112, 42, - -164, 274, -269, 1138, -208, 574, 589, -143, - -479, 2745, 782, -13, -2492, -132, 498, -406, - 260, 828, -580, 558, -2861, -600, -447, -313, - 1316, 800, 1772, 1131, 323, -48, -3972, 697, - 5, -403, 46, 95, 130, 84, -39, 219, - 117, 1629, -189, -1371, 25, -116, 2311, -681, - -411, -685, -1340, -409, 223, -462, 2530, -816, - -1118, 314, -893, -109, -262, 376, -2795, -48, - -2878, -6, 180, 53, -500, -181, 125, -291, - -265, -154, -23, -184, 185, -563, -1159, 675, - 24, -213, 273, -2905, -242, 2373, -6, -166, - 92, 276, 1375, -28, 1879, 2572, 205, -121, - 51, 356, -873, -308, -1060, 952, 719, 456, - 106, 116, -107, -211, -21, 3319, 2109, -172, - -172, 143, -718, -138, 1135, 232, -1361, 157, - -99, 522, -4367, 84, 605, 319, -937, -397, - 117, -434, 82, 633, 274, -1555, -221, -59, - -2419, -2486, -112, 136, -182, -480, 27, -548, - -237, 817, 530, 656, 252, -2685, -26, 703, - -3268, 381, -383, -323, 105, -500, 66, -299, - -1056, -363, -69, 21, 292, 398, -379, -106, - -356, 38, 169, 2866, 206, -523, -277, -2875, - -582, -69, 649, -3, 198, -30, 98, 145, - -125, -186, -19, -107, -102, -173, -7299, -62, - -503, -231, 24, 145, 1367, -355, -175, 373, - -953, -704, -3454, 170, 899, 386, 592, -754, - 620, 81, 86, -65, 84, 683, 3054, -280, - -2825, -757, 53, -10, 441, -145, 138, 1364, - -2, -92, -300, 225, -199, -2087, 1095, -363, - -75, 288, 765, -869, -7, 3261, 9, -2860, - -330, -382, 3309, 28, 629, 244, -143, -298, - -512, -409, -241, 104, -6, -271, -2, 8192, - -137, 139, -304, -14, 81, 262, -36, 51, - 380, 11, 101, 100, -153, 2167, -271, 267, - 306, -3008, 579, -277, 316, 327, 1168, 71, - -1401, 389, -25, -265, 101, -53, -170, -226, - 2861, 145, 3040, -159, 77, -16, 233, -570, - 490, 661, 452, 1986, -522, 212, -107, 196, - -247, 308, -353, 186, -2689, 486, -46, 813, - -24, 233, -166, 3305, 2832, -343, -82, 475, - 267, -385, 26, -35, -226, 27, 416, 231, - 12, 88, -209, -139, 404, -239, -109, -182, - -851, 260, 242, 109, 11, -1096, 85, -4226, - -124, 12, -139, -100, -604, -87, 89, 5820, - 59, -43, -84, 264, -543, 0, 428, -16, - -146, -556, -195, -159, 875, 27, 261, 207, - -182, 2367, -622, -3193, 481, -289, 52, 12, - 34, 3014, 10, -345, -94, -2883, -62, 400, - 249, 51, -178, 1190, -128, -3940, 41, -296, - -48, 13, -26, 223, -2392, 516, -384, 33, - -46, -161, -43, -224, -89, -4, -349, 135, - 540, -120, -276, -198, 129, -5113, 175, -45, - -34, -109, 419, -45, -104, -185, -393, 416, - -3514, 149, -3088, -115, -78, 431, -172, 21, - -290, -162, 216, 41, -56, -487, 705, -194, - -1003, 100, 172, 2793, -83, 2584, -189, 1198, - 551, -119, -73, -91, 2103, -619, 124, 128, - 2628, 192, 160, -110, 270, 1739, 1062, -568, - -73, -56, 328, 100, 384, -173, 83, 39, - -236, -25, -457, 53, -6413, 345, -459, -110, - 28, -127, -109, -593, 32, 141, -879, 254, - 2132, -410, -623, 1103, -2302, 528, 156, 28, - 81, 613, 602, 171, 500, -2356, 620, 17, - -523, -2961, -921, -107, -405, -230, -129, 18, - 363, -881, 1282, 1427, -363, 658, 205, -51, - 2835, -2003, 188, -26, 73, -231, 352, 74, - -490, -222, 2423, -341, -2762, -14, -56, -260, - -41, 33, 169, -190, 1248, -77, -2322, -607, - 3610, -104, -200, -90, -81, 719, -52, -359, - 394, -301, 66, -39, -56, -8192, 87, 56, - -291, 50, 231, 284, -211, -16, -86, -84, - -28, 52, 3, -51, 304, -224, 228, -374, - 458, -1958, -210, -2613, 401, -2128, -119, -12, - -60, -14, -8192, 53, 27, 113, 289, -7, - 22, 60, -192, 333, 72, -344, 238, 147, - -2235, 324, 124, 176, -415, 450, -476, -558, - -429, -246, -551, -287, 672, 2145, 8192, 161, - -165, -34, 193, -108, -137, -96, -68, 156, - 308, -182, 5, 438, -71, -27, -164, 187, - -110, 5786, -82, -130, -126, 197, -262, -182, - -118, -110, 121, -93, 235, -56, -99, -212, - -3013, -193, -10, -2944, 58, -135, -624, -170, - 84, 339, 115, -85, -1886, 250, 123, -104, - -374, -2241, 2454, -438, -168, 632, -136, -725, - -329, -394, -60, 19, 2795, 438, -796, 141, - -143, 132, 251, 37, 286, 1858, 39, 2381, - -9, -85, -110, 149, -415, 355, -172, -9, - -149, 554, -324, -4931, -537, -261, -585, -291, - 764, -92, -139, -8, -80, 65, -6, -26, - -81, 37, -14, 45, 115, 171, -321, 313, - 308, -4637, -128, -120, -174, 148, 768, 490, - 81, -175, -261, -136, 1501, 345, 25, -56, - -212, -324, -836, 207, -652, -752, 2406, -332, - 489, -275, -932, 284, 3103, -315, 614, -2711, - 1706, -1072, -163, -75, -1104, 163, -421, 1532, - -92, -163, -811, -118, -38, -754, 466, -314, - 232, -595, 3613, -30, 570, -62, 785, 1626, - 1080, 553, -407, 32, -105, 82, -156, -75, - 8063, -67, 114, -65, -65, -242, 98, -124, - 38, 441, -2645, -92, 69, 17, -3284, -278, - -278, 116, 567, -742, 182, -304, 432, 261, - 86, -4109, 389, 795, -138, 151, 111, -223, - 2392, 399, -135, -545, 182, -226, 61, 234, -}; - -static const int16_t cb1616sm1[] = { - -29, -13, -6217, -136, -196, 24, -228, -301, - -155, -37, -54, -91, -4, -130, -424, -89, - -181, 657, 110, -4526, -391, 762, 1033, -310, - -808, -282, -721, -690, 258, -259, 16, -555, - 2675, -379, -2580, 356, 198, -455, 95, -194, - -754, 383, -263, -873, 271, -107, -191, -28, - 11, -66, 91, 25, -215, 9, 152, 11, - -124, 66, 422, 521, 5401, 103, -179, -291, - -821, -1265, -396, 150, -69, -15, 154, 1504, - -445, 116, -136, -3528, 2819, -5, 174, 166, - 289, -60, 158, -701, 83, -636, -407, 194, - -240, -138, 124, -94, 132, -105, -106, 72, - 139, 101, 97, -7928, 6, 112, 164, -83, - -329, 41, 124, 389, -22, -194, 157, -378, - -2255, -431, 3176, -199, -310, 49, 483, -208, - -235, 11, 45, 637, 1220, 2309, 93, 514, - -1939, 136, 276, -165, 137, 2496, 56, 31, - 238, -538, -433, 690, -318, -44, 834, -1684, - -132, 2619, -157, 1959, -566, 119, 183, 227, - 2066, 401, -48, 1257, 604, 1306, 149, 273, - 586, -199, 2166, 257, 2047, -46, -377, -761, - -25, -454, -1592, -42, 432, -2312, 222, -528, - -87, -287, 532, 2906, -2011, 720, 554, 423, - -576, 425, 280, -894, -232, -179, 485, 628, - -2918, 405, 229, -2, -146, 127, -329, -243, - 194, 2443, -531, 592, -14, 1679, 292, -914, - -332, 2382, -3040, 297, -2856, -88, 236, -485, - 438, 241, -283, 448, 579, -660, 277, 233, - 201, 126, 15, -411, -560, -582, -389, -392, - -7, 238, 1, 344, -216, -4601, -457, 1027, - -114, 13, -301, 288, 172, -488, -124, -2721, - 100, -105, 434, -13, 2791, -827, 1600, -219, - -4992, -100, 411, 326, -608, -779, 94, 974, - 453, -1326, -236, 429, -189, 830, 32, 187, - 459, 2489, 476, 165, 3261, -445, 169, 179, - -113, 168, -393, 52, -383, -33, 73, 137, - -6021, -259, -121, -29, -46, -156, 68, -225, - 217, 152, -280, 7, 62, 3, 17, 295, - 221, -158, -5406, -335, 232, -454, -320, 467, - -45, 96, -170, -267, 1273, 287, 258, 536, - -695, -953, 1134, 428, 251, 3331, 717, -804, - 627, 1099, 120, 4, 42, 191, -9, 259, - -335, -337, -25, -56, 116, -228, -351, -463, - 5942, 193, -114, -64, -268, 300, 146, -15, - 657, 367, -2, -2911, 838, -251, -1, 2897, - -78, -609, -545, -588, 488, 1383, 486, 1820, - 126, 2971, -151, 11, 10, -349, -279, -260, - -265, 142, -683, -191, 172, 30, -293, -5103, - -61, -247, -38, 722, 275, -326, -34, 132, - 297, 3305, -46, 227, -1052, -1114, 562, 62, - -1618, 699, 362, -1624, -455, 150, -110, 61, - -266, -168, -168, -391, 136, -569, -772, -203, - 467, 20, -4747, -170, 142, -138, 129, 1719, - 1896, 210, -1008, 206, 585, -325, 295, 175, - -2542, -489, 121, -94, -38, -2766, -115, -3206, - -305, 320, -179, 503, 83, -72, -122, -52, - -181, 98, 39, -506, -2751, -93, -1, -59, - 2645, 248, -309, -203, 138, 324, -567, 696, - -493, 170, 2440, 919, -420, -3029, -335, -593, - -72, 536, -82, 202, 78, 510, 184, -2, - 227, -2830, 19, 1590, -281, 387, -46, 408, - -463, -536, 262, 2214, -115, -1614, -385, 203, - 32, -885, -2606, 2338, 97, 292, -449, 449, - -1038, -582, 0, -68, 211, -160, 62, -286, - -2466, -421, -48, 1903, -1037, -173, 1339, -591, - 152, -1231, 792, 524, 214, -92, 29, 181, - -225, -150, -1, 139, -8135, 238, -119, 189, - 34, -140, -188, 141, -112, 56, -176, 154, - 91, 5653, 298, -316, -23, 232, -74, -317, - -4, -630, -506, 105, -1655, -126, 2417, 113, - -95, -472, 134, 290, -755, 152, -1222, -58, - 981, -236, 8192, -154, 75, 218, -185, 107, - -10, 39, 265, -225, -87, 9, 123, -906, - -382, 2544, 44, -1985, -102, 407, -91, -1835, - -108, 122, 142, 169, 134, -721, -1530, -4, - -133, 45, 374, -1049, -76, 16, -357, 277, - 158, -2596, -4, -1484, -13, 2660, -198, 9, - -218, 408, -63, 177, -71, -195, 4293, -8, - 228, 34, -421, 695, -1409, 85, 2740, 350, - 44, 473, 141, -93, 144, -59, -220, -154, - -148, -168, -205, 3049, 229, 194, -107, 90, - -353, 508, -343, 473, -446, 457, -452, -116, - 3493, 504, 2152, -228, -1832, -463, -657, 555, - 657, 540, 546, 604, 2214, -68, 254, 563, - 267, 227, 92, -107, 143, 260, 23, 42, - 64, -67, 138, -167, 72, 457, 4958, 61, - -933, 1, 5341, -32, 89, 161, 504, 823, - 311, 11, -184, -574, -79, -1654, -74, -366, - 164, -363, 117, 53, 706, -701, -2966, 233, - 11, 165, 394, 462, -2632, 703, -291, -65, - -49, 4080, -862, -65, -19, -110, -872, 323, - 833, -154, 369, 475, 2211, 20, -212, 1711, - -24, -28, -58, 32, 1746, 41, -779, 614, - 508, 3050, 687, 423, -182, -484, -60, 242, - 3895, -565, -453, 110, 547, -961, 320, -34, - -347, -1963, -116, 730, -435, -34, 41, 26, - -51, 8192, -115, 312, 184, -148, -199, 157, - 153, 82, 99, 138, -32, -19, -64, -139, - 107, 43, 133, -87, 42, -148, 7080, -158, - -335, -249, -64, 81, 157, 813, -279, 2226, - -16, 1191, -705, 607, 205, -11, -1341, -548, - -2251, -326, -149, -2536, 139, -750, 73, -394, - -218, -35, 181, 925, -557, 226, -63, 2582, - -737, 164, 181, -167, -230, 413, 328, 406, - -287, -2992, 539, 1133, -85, -2162, -154, -357, - -245, -8, 162, -118, 111, 1275, 47, -314, - -2043, -2732, -1052, -28, 625, -810, -487, 40, - -131, 273, 105, 2605, -2974, 268, -19, -257, - 842, -662, 855, 505, 590, -243, 68, 6978, - 118, -101, 349, -232, -258, -318, 212, 55, - -686, -177, -173, -102, 480, 35, 149, 263, - -2838, -198, 942, 392, 135, 2980, 34, 92, - -237, -672, 224, -298, 298, 2128, 359, 254, - 150, -839, 1001, 3234, -169, 261, -302, 74, - -277, 498, 321, 194, -3275, -152, -2786, 33, - 70, 236, -222, 88, -393, 47, -636, 869, - -754, 842, -2326, -460, 133, 0, 264, 172, - -2955, -286, -243, 399, 882, -722, -382, 872, - -119, -65, -2403, -119, -246, -890, -185, 102, - -32, -573, 225, 3044, -484, -40, -809, 403, -}; - -static const int16_t cb2224l0[] = { - -3546, -433, -76, 46, 24, -641, 214, 114, - -779, -930, -57, -462, -569, -848, -413, 53, - 45, -3172, 2915, -734, 152, 487, -113, 246, - -196, -187, -136, 469, 475, 382, 213, -886, - -275, 313, 3148, -62, -773, 785, -24, -1499, - -65, -175, -1942, -325, 78, -15, -38, 2, - 6, -29, -16, 9690, -15, -49, -13, 12, - -21, 11, -45, -63, -528, 192, -137, 201, - 138, -154, 57, -88, -1695, 155, 105, 121, - 4249, -59, 467, -439, 4483, -130, -39, 262, - -21, -377, 441, -353, -768, 366, 23, 841, - 529, 195, 2722, 2892, -255, -67, 628, -498, - 33, 241, 212, -1020, -97, -723, 594, 35, - -31, 1459, 19, -75, -27, -1, 48, 28, - 267, -275, 3780, -515, -467, 36, -405, -272, - -1968, 60, 44, 449, -2877, -124, -1524, 1195, - 1042, 117, 115, -305, 225, 215, -357, 144, - 35, -23, 89, 2133, 2, 65, -27, -48, - -243, -216, -807, 700, 1258, 6, -140, 4, - -31, -21, 42, 67, 97, -2, 104, -10, - -7734, 134, -50, -95, -88, -269, 105, -18, - -229, 453, 1038, -2609, -2944, -57, 27, 372, - 59, -556, -87, -242, 114, 1083, -119, -139, - 175, 146, -55, 1689, 342, 501, 2722, -1273, - 1626, 868, -290, -145, 62, 194, -23, -179, - 1540, -85, 360, 254, 339, -681, 2081, 2730, - 838, -128, 31, -2133, -173, 483, -138, 2706, - 2007, 91, 293, -642, 35, 280, -132, 454, - -66, -6263, -24, 82, -31, -39, 5, 41, - 66, 239, 18, -57, 61, -117, 103, 16, - -1231, 1384, -164, 104, 370, -1891, 2237, -440, - -1399, -1394, 3, 274, 223, -30, -70, 579, - 361, 423, 355, -176, -164, -443, -306, -2382, - 713, -2987, -340, -691, 1407, -5, 439, -264, - -86, 1964, -17, 88, 175, 56, -119, 31, - 466, 1980, 176, 513, 1809, 17, 3000, 1861, - -71, 314, -255, 2041, 576, 203, 443, -392, - -539, -380, -685, -204, -161, 287, 378, -502, - 1898, 1540, 1073, 2282, 573, 867, 122, 1064, - -628, -564, 97, 280, -36, 1601, -90, -174, - -10, 45, -57, 159, -496, 641, -959, -91, - -90, 3057, 1680, -83, 80, 19, 63, -119, - 1, -72, 466, -335, 453, -177, 3930, -21, - 327, -199, -651, -38, -6, -13, 7, -77, - 1, 8, 40, -125, 36, -136, 272, 6266, - -3299, 3331, 24, 18, -71, 9, -79, -374, - -277, 128, -233, -175, -350, -216, 81, -693, - -49, 33, -44, -37, -4260, -70, 96, 177, - -319, 133, 178, -377, -45, 182, 156, -155, - -34, 10, 22, 53, -211, 4, 5740, 48, - -42, 114, 149, -30, 122, -106, -309, -148, - -82, 20, 130, 2734, -40, -596, 1309, 1163, - -1470, 396, -264, 884, 142, -1818, 67, -1, - 38, -52, -73, 1, 279, 143, 278, -45, - 1541, -886, -677, -2609, -88, -3766, -201, 237, - -40, 195, -50, -366, 88, 166, 403, 236, - -130, 205, -45, -8636, -13, -27, -50, 8, - 40, 21, 41, -36, -25, -40, -14, -14, - 42, 296, 2495, 372, -361, -501, 1951, -2141, - 220, -847, 98, 228, -250, 563, -1121, -29, - 2888, -196, 151, -19, -287, -2298, 65, -482, - -124, -186, 1215, 468, -781, -227, 621, 298, - -42, -44, -115, 0, 50, 179, 23, 9, - -65, -8, 10, -101, -4998, 77, 1181, -304, - 139, 250, -2257, -97, 847, 433, 385, -2411, - 800, -852, -528, 435, -953, -23, 4, 928, - -108, -634, -273, -879, 2566, -2609, 621, 807, - 295, -77, 627, -1114, -297, -109, 2103, -53, - -9, 44, 32, 339, 679, 77, -3186, -416, - 1234, -801, 472, 408, 153, 465, 1703, 879, - -2411, -553, 440, 2099, -899, -288, 310, 665, - -47, -148, 1457, 3932, -213, 243, -1763, -2, - 288, -425, -972, 478, -302, 552, -377, -352, - 179, -480, 1466, 2019, 2817, 5, 824, 13, - -384, -582, -297, -1165, 689, -120, 703, -118, - 663, 206, -49, -2853, -76, 32, 170, 11, - 42, -503, -1139, 1548, -287, -1112, 765, -455, - -35, 2452, 22, -134, 144, 1867, -149, 2771, - 19, 264, 700, -48, 286, -593, -2637, 408, - 2304, -14, 187, -135, -210, 745, 282, 724, - 861, 21, -414, 606, 836, -564, 212, 203, - 64, 4706, -30, -43, -85, -61, -90, 644, - -281, 287, -122, -340, -137, 36, -4, -22, - 8, 9486, -3, 4, 10, 4, 86, 58, - -8, 6, -105, -15, 15, -63, -58, -30, - 15, 0, -19, 78, -8267, -134, -8, -45, - 163, -19, 149, -298, -167, 34, 190, -39, - -2229, 2821, 126, 185, -791, -1229, 1003, -331, - 980, 659, -60, -60, -48, 20, 12, -167, - -60, -39, 66, 180, -22, -20, 84, -108, - 131, -10, -8493, -1, -18, -4, -53, 25, - -63, -14, 20, 25, -41, 40, -5, -2330, - -74, 59, -7, -154, -293, -64, -2702, 819, - 75, 977, -602, 1138, 160, 262, 26, -81, - 18, 5558, 118, -167, 98, 110, -5, -44, - -27, 72, 51, -189, 0, 1868, 743, -275, - 2530, 6, 180, -1019, -1307, 710, 303, -152, - -115, -1498, -501, -495, -103, -76, 78, -7, - -9337, -6, 31, -21, 16, -14, 57, 36, - -81, -67, -30, -535, 216, 313, 310, -157, - 2830, -914, 122, 1353, -1842, 298, -1165, -13, - -253, -100, -560, -61, 40, 24, 3, 56, - -18, 5709, 41, 13, -23, -55, -98, 214, - 109, -205, -45, 27, -26, 177, -290, 89, - 8, 1315, 3102, 1657, 210, -1032, 774, -211, - -581, -51, 896, 852, 331, 349, -474, -119, - -865, -145, 2270, 703, -1967, -2088, 610, -700, - 113, -231, 2062, -152, -599, -474, -38, -601, - 432, -983, -731, 744, -2880, 156, -240, -1903, - 2497, -89, -963, -2179, -1208, 189, 318, 150, - 204, 29, -167, -138, -93, 73, 292, -3225, - -310, -510, 173, -90, 154, 1831, 380, -1191, - -976, -1460, -514, 235, 13, -2950, 22, -95, - 228, 85, 10, 264, -3165, 46, -184, -782, - 143, -9, 37, 12, 108, -65, -64, 115, - 86, 5039, -55, -203, -163, -462, 77, -92, - 423, 139, 239, -5, 1887, 426, 729, 118, - -159, -2821, -124, 2147, -167, -1023, 92, -23, - 162, -159, -47, -3, 14, -34, 37, -29, - -97, 41, -92, -75, -6983, -224, 250, -80, -}; - -static const int16_t cb2224l1[] = { - -2888, -183, 3606, 0, 33, 99, -76, -264, - -351, -508, -546, -103, 252, -49, 46, -32, - 48, -245, 67, -2408, 340, 3153, -154, -280, - -440, 374, -224, -39, -720, -289, -136, -3095, - -98, -37, -86, 145, 51, 132, 773, -1158, - -330, -449, -141, -1831, 666, -2680, -110, -906, - -307, -3299, 287, 55, -521, -173, -431, -383, - 67, -28, 34, 247, 2814, 1479, 32, -2196, - -1625, 135, 72, 3, 634, 76, 502, -306, - -366, -120, -219, 1934, 372, -130, -113, 255, - -14, 30, -687, -576, 797, 306, -2360, -242, - 2062, 69, 2273, 26, -20, -21, -68, -69, - -4618, 60, -171, -235, -271, 175, -110, 147, - 100, 1628, -197, -2, -4002, 520, -1236, -21, - 62, -396, 513, -369, -168, 285, 561, 131, - 1347, 83, -101, 89, 206, 5, 4556, -23, - 1191, 39, 352, -158, 99, -195, -33, 481, - -446, -125, 181, 2678, 2860, -524, -239, 55, - -360, -358, -560, 93, 307, 285, 77, -295, - -90, 114, -45, 54, -328, 94, -222, -30, - -5004, -164, 100, 379, 208, 424, -11, 26, - 10, -26, -32, 114, 30, 18, -44, -221, - -184, -32, 0, -99, -9001, -7, -33, 1, - 41, -3, 13, 9, -46, -86, 47, 56, - 72, -7, 5, -1162, 101, 456, -217, 3440, - -220, 400, 100, 1503, 365, 655, -230, 42, - 1129, 767, 192, -16, -3440, -79, -236, 3, - -80, 51, -11, -984, -142, 29, 554, 339, - 1851, 105, -279, -2915, 116, 3090, -431, 233, - 337, 61, 927, 32, -174, 237, 255, -250, - 604, 115, 2036, 78, -79, -50, -349, 338, - 285, 169, 394, -49, 1194, -2966, 447, 57, - -2591, 415, -586, -2616, -197, -61, 596, -1159, - 130, -441, 356, 47, 1192, 496, -1801, -15, - -142, -23, 132, 21, 84, 234, -137, 23, - -147, -3254, 407, 107, 1132, 130, 74, 153, - 3148, 2184, -464, 1294, 222, 589, 457, -397, - -87, -605, -631, 311, -703, 110, 20, -23, - -75, 18, -43, -182, 8, -94, 151, 4989, - -619, 662, 82, 8, 69, -4, 126, -35, - -99, -277, -227, -2212, 3188, 1115, -467, -618, - -989, 681, 218, -25, -37, -9, 32, -46, - 97, 15, -23, -95, -6, 55, 19, 7904, - -14, -508, 3, 14, -12, -58, 28, 154, - 11, 271, -593, 344, -336, 3489, -41, -2998, - 622, -2739, 2796, 1536, 310, 176, -318, 399, - -70, -298, -509, 256, -381, -158, 322, -197, - 3, -53, 37, 98, -6136, -25, -54, 57, - 138, -74, 239, -46, -18, 29, -265, -2278, - 22, 110, -21, -147, 266, 85, -286, 137, - 3434, -485, 68, 475, -3, 159, -181, -237, - 1595, 759, 786, 1490, 926, -2841, -160, 1092, - -7, 130, 895, -345, -95, -31, -35, 139, - -98, 2106, 305, 672, -66, 349, 229, -1561, - -1694, -1786, -743, -76, -67, 1666, 76, 10, - -22, 60, -45, 5, 409, -458, 583, -405, - 2586, -264, 175, 633, 842, 3208, -1488, -802, - 40, -119, -197, -84, 1645, 328, 823, -175, - 342, 12, -217, 67, 124, -180, -106, -2877, - -336, 171, 185, 132, -2263, -75, -622, -631, - -2404, 176, -132, 35, 179, -1498, 182, 68, - 699, 597, -2728, 325, 52, 421, -863, 609, - 53, -159, 258, -307, 2919, 44, -826, -467, - 91, 542, 1883, 815, -682, 548, -419, 593, - 82, -2108, -158, -75, -524, 2440, -528, -469, - 723, -14, -1817, -487, 448, 4, -155, -70, - -1715, 34, -55, 134, 0, 19, 107, 419, - 334, 74, 446, 1241, -4288, 61, -65, 21, - 71, 133, 2, -88, -238, 322, -283, -6, - 404, 98, 78, -1951, 412, -1942, 418, 257, - -42, -2444, -97, 1491, 464, 346, 229, -154, - 96, 261, 29, 302, 39, -201, -40, -98, - -157, 335, -3624, -349, -573, 633, -116, -312, - -82, 263, -2, -101, -57, 1817, -424, 3, - -245, 386, 74, 609, 2171, -77, -2604, -1036, - -117, 1585, -2, 9, -23, 31, -12, 48, - 215, 84, 13, 219, 419, -275, 4373, -91, - -6, 18, 2228, -46, 157, -408, 2288, 654, - -725, -245, -10, -1182, 1726, 324, 367, 3013, - 3429, -140, 360, -122, -574, -165, 109, -330, - -82, 340, -133, 210, 355, -8, 47, -52, - 8064, 5, 60, -42, -95, -3, 91, -69, - -47, -42, 101, 118, -44, -16, -14, -9, - 27, 8, -33, -3, -9302, 27, 49, -6, - 61, 74, 204, 430, 252, -259, 73, 125, - 366, -458, -2846, 89, -2694, -106, -344, -702, - 809, 451, 69, 585, -1897, 608, -1138, 52, - 618, 106, 771, 2992, 266, 1007, 184, -486, - 36, 3317, -311, 38, 105, -89, 16, 97, - -88, 28, 183, -2834, -44, 387, -49, 467, - -2524, 77, -56, -3727, 81, -308, 63, -137, - 203, -77, 139, 254, -65, -264, -58, 631, - -2559, 739, -1343, 595, -117, -193, -2572, 322, - 267, 185, 669, -110, 641, 212, 45, -16, - 12, 14, -3, -12, 78, -48, -196, -128, - 179, 146, -7348, 177, -138, -48, 142, -33, - 34, -6037, 15, -105, 103, 136, -48, 217, - -169, 88, -31, 9, 24, 41, 1733, -2757, - -335, 1783, 988, -161, 1014, 633, -66, -1114, - 525, -266, 461, 1137, -26, -173, 89, 82, - -3365, 67, -198, -107, 44, 352, -793, 867, - -807, -166, 107, 4, 71, 61, 124, 27, - -2477, 178, -32, -172, 2895, 1301, 798, 707, - 267, -720, -403, 167, -157, 2572, -210, 527, - -312, -1664, -214, -1556, -332, 595, -1634, -58, - 203, -1777, -469, 24, 188, -59, -860, 879, - 15, 855, -1534, 2910, 534, -71, 276, 471, - 41, -25, 105, -37, -150, 110, 226, -277, - -4687, 574, 139, -152, -586, 67, -1082, 261, - -68, 25, -216, 110, 46, -3703, 281, 355, - -506, 80, -218, 164, -398, 75, -97, 5782, - 39, -68, 26, 76, 74, 38, -103, 105, - 44, 116, 187, 288, 90, 5847, -41, 28, - -19, 20, 129, -99, 258, 22, -28, -120, - -101, -121, 79, -180, -23, 22, -5, -60, - 63, 35, -8987, -11, 2, -15, -3, -28, - 47, 29, 241, 132, -166, -259, -48, 102, - 70, 2830, 3163, 285, -813, 0, 105, 176, - -455, 141, 1382, -481, -2282, 2971, -200, -473, - 37, -930, -1162, 930, 890, 412, 190, -160, -}; - -static const int16_t cb2224s0[] = { - -5789, 1229, -138, 1010, 823, -602, -987, -237, - 47, -29, 428, 210, 87, -11, -20, -261, - -3148, 1219, -2074, -132, -258, 707, -634, 878, - -486, 989, -276, -137, -263, 592, 1248, 474, - -293, -981, 2125, -653, -1451, -833, -1522, 387, - -269, 349, 698, 295, 870, 661, 1532, 202, - 654, 362, -1265, 3972, -651, 224, 213, -728, - -83, 575, -503, -766, 559, -657, 86, 941, - 1498, -72, 2297, 1413, -376, 697, -738, 384, - -807, -354, 1141, 374, 1186, -597, 222, 630, - -717, -1653, 106, -1377, -929, 982, -3469, -321, - -201, -1185, -147, -13, 268, 103, 2967, -2083, - -416, 702, 377, -1126, 92, 963, -494, -94, - -436, 1893, 1401, -40, -1464, -1608, 1980, 44, - 254, 676, 529, -891, -95, 9, -172, -129, - 158, -403, -1147, 1026, -410, 86, 2593, -1060, - -621, 480, 254, -780, 691, -1020, 79, -192, - -2264, -1219, -748, 602, 243, 338, 550, -444, - -130, 79, 24, 3396, 124, -572, 749, 976, - 33, -883, -368, -609, 694, -569, -560, 192, - 868, 644, 173, 86, -4302, 633, 7899, -360, - 478, 493, -306, 14, 244, 96, 71, -169, - 336, 346, 74, -52, 1779, 828, -252, 739, - -1005, -755, 31, -46, 200, 581, -11, 802, - 1104, 3252, -1053, 723, -491, -2492, -2330, -245, - 308, -1021, -312, 563, -85, 991, -16, 224, - -85, -957, 2262, -4585, -1475, 102, 310, 298, - -875, -6, -268, 8, -284, 324, -471, -224, - 133, 1502, -1714, -1095, -104, 809, 2584, -273, - -1014, -296, 130, 732, -259, -335, -745, -619, - -716, 247, 503, 862, -277, -137, -224, -4897, - 124, 277, 298, -40, 169, 678, 557, 4379, - 677, -2016, -506, -108, -47, 49, -115, -260, - -300, 206, 1196, -17, 202, 365, -808, -473, - -160, -609, 526, -1124, 1629, -2924, 713, -487, - -109, 540, -511, 221, -394, -1420, 1023, -460, - 424, -86, -875, -1557, -88, -244, -1597, -3015, - 355, 166, 330, -334, -325, 505, 3632, -1760, - 1626, -427, 573, 1197, -317, -566, -663, 460, - 338, -442, -597, 1565, -854, -534, -219, -128, - -2175, 739, 1064, 2050, -61, -349, 361, -375, - 1111, -122, -121, -164, -2573, 938, 1758, -15, - 884, 865, -630, -573, 994, 1112, -26, 9, - -30, 3893, -38, 1386, 605, 568, -680, 117, - 37, 572, 245, -53, -1030, -241, 397, 363, - -1632, -567, -26, -698, -2109, -1033, -1389, 1381, - -418, 402, -534, 9, 1143, 991, 693, 2557, - -1268, 1273, -192, 1225, 876, 472, 835, 509, - -452, -1519, 482, 1103, -626, -299, 1580, -1532, - 599, 2245, 503, -110, -1879, 978, -1158, -130, - -665, 448, -1247, 604, -528, -677, -711, 78, - -563, -349, -53, 261, 952, -338, -534, 43, - -2, -2555, 1976, 2393, 1715, 996, 5628, 1036, - 171, -28, -199, -83, -126, -35, -248, -393, - 36, 209, 77, -1793, 244, -108, -130, -41, - -578, -2347, -687, 1650, 131, -138, 407, -228, - -1348, -209, -841, 1332, -542, 220, -193, 843, - -103, 853, 261, -653, 217, -107, -113, -54, - -4151, -1303, -287, 4065, -376, -71, 43, -1481, - -359, -481, 78, 529, 689, -194, 178, 60, - -997, -1555, 1687, 345, 169, 266, 2894, 83, - -500, -425, -396, -245, 6, 517, 112, 129, - 725, -121, -404, 234, 47, -61, -122, 710, - -4283, 985, 56, -105, -45, 1043, 720, 73, - 321, 4452, -1614, 91, -620, -299, 506, 766, - -882, 650, -138, 123, -608, 210, -1582, -538, - -62, 246, 464, -332, -1560, 2271, 1559, -199, - -832, -1133, -797, 341, 1860, 1628, -1133, -607, - 637, -404, 437, -1148, 542, -474, -882, -610, - -1340, -159, 1524, 1424, 169, -6, 52, 447, - -5513, -592, 244, -294, 44, 164, -51, 147, - 202, -48, 139, 113, -399, -17, -173, -199, - 1, 17, -166, 15, -258, -7, 238, -5748, - -394, -852, -248, -46, 192, -32, -1033, -349, - 151, 483, 130, -1628, -3391, 1527, 694, -305, - 740, -357, -491, -186, -1649, -1394, -873, 213, - 652, -1975, 319, -1131, -103, -48, 673, 155, - -627, 1115, 469, -1122, 1901, -184, -237, -296, - -2887, -120, 211, 835, 57, -826, 1272, -255, - -937, 242, -525, 836, -334, 393, -624, 111, - -347, -178, -3441, 219, -352, 1831, -296, 587, - -357, -1099, 5, 313, -3806, -394, 814, -118, - -233, -23, -125, -21, -1414, 813, -403, 2482, - 442, -184, 934, 340, 472, 374, 1073, -283, - -2348, 477, -387, -713, 1071, -899, 252, -1299, - -502, -375, -410, -1785, 686, -605, -141, -871, - -1777, 2780, 53, -237, -237, 2701, 944, 44, - 595, 3, 1263, -1558, -2267, -998, 221, 355, - -319, -739, -1160, -594, 2977, 191, -41, -284, - 83, 484, 481, -73, -13, 138, -2761, -909, - -578, -139, -1056, 189, -645, -147, -61, -168, - 368, 130, 390, 4187, 101, 79, -45, 451, - -1374, -1941, -534, -301, -979, -668, -533, -2978, - 386, 574, -454, -4, 554, -120, 366, 83, - 1079, -351, 156, 389, 7724, 83, 102, -191, - -1059, -255, -86, 451, -211, 175, 774, 306, - -253, 2386, 1166, -2025, 223, 438, 1279, 1721, - -23, -91, 606, -1285, -775, -3228, -536, 543, - 877, 1140, -1616, -603, 550, -678, -462, 248, - 209, -515, -310, -2538, -2002, 231, -495, 319, - 538, 509, -113, -17, 143, -3062, -29, -52, - 299, 681, 595, 390, 530, -398, -969, 472, - -1145, 860, 4113, 329, -1183, -691, -605, 859, - 305, 986, -81, 2029, 408, 2, -2442, 59, - -85, -911, -285, -532, 28, 434, -2295, -76, - -2977, 51, 824, -1786, 2301, 622, -593, -9, - 643, 246, 427, 193, 51, 118, 4, 234, - 459, 31, -408, 710, -264, 144, -404, -476, - 278, -4836, -113, 382, -29, 177, 345, -33, - -17, -85, 6027, 72, -165, 544, -198, 75, - -278, -262, 155, 501, -305, -279, -439, 1506, - 827, -875, -2592, -1196, -1201, 149, 16, 547, - 1020, -616, 374, -193, -155, -3627, 231, 264, - -2143, 90, 419, 574, -795, 177, 328, 752, - -295, 210, -360, -1250, 2639, -3172, -13, -34, - 489, 484, -390, -159, -285, 27, 444, -252, - 265, 530, -2714, -340, -1543, 2330, -1152, -114, - 452, 304, -224, -451, -317, -579, 301, -567, - 1214, -594, -621, -2718, 59, 257, 410, -3, - 145, 70, 877, -3103, 244, -1134, 236, -1148, -}; - -static const int16_t cb2224s1[] = { - 8488, 277, 63, 173, 224, -30, -158, 64, - 133, -133, 234, 205, -65, 408, 249, -546, - -30, -1, -430, 80, 102, -450, -160, -5634, - 145, -406, -351, 37, 282, 232, -898, 430, - 3301, -1175, -559, 495, 2685, -21, -215, -87, - 728, -55, 235, 430, -250, -505, 506, -128, - -72, 3288, 1588, 291, 7, -39, -944, 478, - 1719, 168, -1085, 225, 330, 1480, -183, -597, - -6131, 668, -387, 672, -173, -55, 113, 40, - -113, -44, 341, -340, -594, -1001, 1757, 127, - -59, 537, -1834, 1401, 856, -1153, -234, 1232, - -562, 476, 110, 2188, 146, 119, 2119, -872, - 450, 597, -371, -1350, -996, -120, -495, 829, - 111, -897, -5445, -670, 390, -118, 4, 109, - 772, 495, 196, 410, -125, 812, 426, 900, - 436, 1155, -553, -1223, 275, 266, -891, 63, - -1267, 523, -548, -2445, 239, 1163, 72, -68, - -1576, 2212, -340, 1499, 494, -671, -73, -281, - 598, 1901, -1652, -845, 266, 795, -545, -574, - 19, -461, 371, 288, -3959, 421, 299, -121, - -2561, -65, 118, 181, -227, 719, -92, -2334, - -3178, -2497, -198, 58, 1279, -309, 152, -715, - 466, -316, 10, 98, 1568, -1015, -18, -435, - -42, 2606, 1971, -119, 705, 254, 443, 36, - 788, 1135, 1234, 2281, 942, 115, 581, -113, - -194, -694, 434, -30, 2835, -423, 436, 522, - 406, 1329, 1191, -2628, 421, -2601, 646, -202, - 637, 610, -584, 357, -1586, -499, -1230, 134, - -83, -1264, 2434, -58, -2924, 641, -285, 172, - -478, -402, 584, -1180, -137, -238, -151, -679, - -619, -495, 1044, 1281, -1180, -444, 376, 1969, - -693, -283, 618, 128, -2622, -90, -115, 672, - 1738, -459, 519, -924, 2582, 937, -555, 672, - 131, 31, 775, 307, -282, -527, -1299, -516, - 10, 239, -4069, 118, 10, -665, -15, -484, - 472, 262, 279, 677, -755, 1288, -1278, 403, - 666, -394, -1230, -2819, -221, 109, 603, 754, - 951, 488, -147, -107, -426, 1875, 2056, -129, - 239, -561, 81, -324, 243, 349, 197, -811, - -146, -929, 1193, 1433, -776, 3209, 434, -6, - 2465, -231, -57, 312, 899, -396, -170, -549, - 346, 135, 17, -596, 401, 269, 499, -64, - -321, -342, -132, -312, 5845, 276, -104, -9, - -50, -678, -478, -1125, -1477, 2058, 156, 538, - 451, 2572, 495, 101, 74, -753, 98, 685, - 2424, -1999, 1050, -280, -1030, 29, -178, -244, - -134, 130, -137, -103, -245, 2161, -446, -1016, - 464, 573, -473, 446, -3822, 942, -1261, -334, - 568, -528, -301, 415, -740, 661, -813, 849, - 1491, 774, -774, 1637, -977, -246, 647, -572, - -140, -2946, -654, -650, -311, 339, -165, 757, - 803, -958, 704, 171, 380, 763, 159, 2721, - -1599, 1006, -118, -597, 2985, 2699, 69, 395, - 523, 657, 438, 190, 72, 164, -268, -145, - 506, -550, 222, -3641, 5, -173, 60, -194, - 677, 686, 724, -107, 882, -339, 14, -54, - 555, 483, 1523, 119, -142, -394, -1683, -984, - 18, -108, -190, 141, 540, 281, -1238, -2195, - -341, -327, -1014, -990, 4694, 46, -1018, 360, - -671, -83, 218, 857, 144, -188, 463, -379, - -571, -865, -1345, -447, -18, -64, 5201, 132, - 90, -158, -132, 381, -85, -107, -103, 970, - -555, -1204, 1802, 1230, 253, 540, -372, -2347, - -386, 835, -705, -437, 941, 795, -182, -368, - 1088, 168, 256, 210, -667, 290, 1783, -636, - 165, -363, 638, -3527, 1872, 1997, 1503, -189, - -2587, -359, 384, 493, -384, -658, -1758, 993, - -306, 148, 198, 163, 430, -313, -149, -337, - 352, -354, 484, 358, -264, -4525, -560, -55, - 154, 374, -317, -426, 1446, -161, -285, -110, - 209, 299, 2329, 99, 1406, 1374, 993, 1178, - -413, -642, -103, 3678, -1829, -754, -1358, -349, - 648, -492, 755, 188, 114, -444, -930, -224, - 319, 212, 1223, -648, 593, 1293, -1289, 24, - -712, 2591, -494, 1503, -9, 534, 923, 1490, - 985, 491, 272, 988, 348, -503, -454, 893, - 409, -422, -1187, 3097, 602, -402, 462, 1598, - -219, 982, 319, 125, 558, -100, -261, 108, - -59, -3435, 76, -1065, -150, -1758, -1997, 1921, - 1239, 426, 507, 173, -856, -829, -538, 247, - -1203, 488, -1094, 453, -1104, 1021, 2185, -2855, - 427, 177, -778, -182, 641, -670, 91, 569, - 50, -90, 571, 108, -374, 174, 1997, 964, - 644, -428, -1868, 668, 171, 320, 676, 121, - -218, 1901, -857, -721, -194, -2433, -34, -1671, - 352, -644, 295, 571, 253, -288, -1786, 32, - 74, -73, -902, -1954, -1126, -3427, 168, -318, - 23, -755, -441, 201, -84, 499, 367, -153, - -426, 716, 650, -457, 80, -709, 859, -2098, - -723, -197, -1030, -253, 283, -1187, -899, 1403, - -117, -25, 7617, -63, -355, -283, -560, -85, - -358, -45, 63, 179, -193, 130, -294, -676, - -525, -907, -430, -627, -5267, -539, 257, 594, - -173, 890, 203, -33, -136, -803, 479, -56, - -634, 464, -919, -146, 306, 5, 198, -90, - -138, -337, 4826, -310, 259, 1651, -687, -1676, - 424, 2729, -966, -61, 386, 60, 769, -72, - -1652, 49, 106, 503, -1462, -1056, 892, 359, - 209, -129, 260, -130, -2081, 798, 488, 846, - -836, -366, 1786, -2237, -484, 72, -2680, -828, - -857, 920, 560, 930, -197, 56, -872, -34, - -355, 929, 35, -449, 514, 70, -1277, 208, - 353, 3654, -256, 134, -895, -184, 375, 402, - 1576, 1515, -100, -438, -679, 384, 1143, -24, - 100, -2818, 554, -219, 105, 652, -2778, -108, - 44, 306, 445, -470, -1151, -1170, 1305, -741, - 1223, -443, -838, 374, -3000, 72, -590, -587, - 3686, 76, -493, 246, 1348, -1215, 473, -244, - -304, 1937, -68, -626, 278, 392, 1167, -1899, - -309, 474, 226, -421, -95, -483, 105, -148, - 749, -430, -3057, -789, -1793, -1857, -158, -489, - -676, -204, 806, -930, -3192, -204, -106, -812, - 1159, 648, 119, -93, -205, -139, 280, -7786, - -388, -132, -12, -332, 32, -174, 100, 153, - -7, 289, -29, -984, -329, -592, 2568, 704, - 544, 66, 521, -661, -1632, -868, -310, 313, - -466, -347, -146, 197, 266, 765, -240, -201, - -265, -1129, -35, -563, -356, 172, 862, 3831, - 1547, -1618, -1445, -3726, 388, 548, -457, 143, - -38, 402, 255, 840, -703, -154, 776, -1038, -}; - -static const int16_t cb2224m0[] = { - -7078, 2846, 79, -111, -20, 330, 227, -36, - 305, 45, 81, 148, -13, 68, 364, -317, - -72, 2021, 28, 93, 328, -256, -181, 2547, - 235, -1102, 130, -577, -164, 1290, 1885, -171, - -147, -3247, 324, -72, -313, -62, 32, 284, - -138, -9, -146, 1709, -390, 1833, 289, 125, - 2369, 60, 223, -137, 642, -113, 204, 288, - -1516, -138, 228, 368, 219, -622, 273, 3211, - -215, -423, 139, 65, 85, -203, -953, 11, - 193, 294, 279, 3267, 246, -2377, -59, -324, - 136, -492, 23, -56, 79, 307, 115, -146, - 2229, 325, -1680, -597, -423, 2200, -44, 48, - 386, 396, -122, -36, 35, 9763, 33, -67, - 19, -34, 15, 41, -25, -30, -61, 20, - -121, 117, -155, -28, -65, -27, 40, 137, - 188, -211, -240, 71, -33, -4873, 1992, 56, - -2701, -1, 151, -96, 286, -398, -418, -221, - 295, -394, -119, -182, -124, 77, 7, -44, - 168, -34, -154, 257, 4, -114, 634, 131, - 4930, -118, -2364, 46, -204, -129, -3168, -138, - -489, 454, -96, 120, -447, 9, -230, 174, - 11359, 456, -261, -74, -249, -28, 149, -79, - -36, 211, -10, 213, -110, 337, -3800, 4, - -223, -18, 136, -290, -155, -235, 57, 447, - -495, -231, -15, -1036, -85, -154, -4421, -19, - -237, -1191, 12, -19, 2, -88, -84, 269, - -7, 431, -26, -2676, -100, 287, -31, -2916, - -160, -83, -198, 9, 183, -279, -68, -23, - -55, 2955, -121, -71, 183, -702, -323, 1689, - -132, 309, 136, -1217, 440, -125, -1671, 1569, - -161, -108, 232, 269, -516, 37, 21, -260, - -230, 564, -375, 224, 129, 4332, -120, 3306, - 153, -25, -260, -84, 123, 21, 5, -17, - -145, -44, 7, -1, 290, -2394, -182, 51, - 933, 1037, 26, 211, 187, -1783, 68, -749, - -52, 1428, -1571, -261, 34, -199, 722, -127, - -118, -114, -2385, 146, -1042, -71, -1475, -150, - -2195, 151, -29, 6, 96, -1213, 282, 219, - 466, 144, -300, 109, -74, 125, 2863, 2, - -2963, -218, 235, 3, 359, 319, 372, -500, - -271, 494, 2695, -65, -29, 47, 74, -34, - -95, -48, -76, -71, -2985, -30, -11, 26, - -176, 107, 96, 22, -60, 114, -70, -147, - -43, 6981, 110, -86, 33, 66, 8, -61, - 52, -169, 82, 233, 56, -115, -295, 241, - -1053, -3914, -79, 361, -869, -144, -144, -805, - 158, -278, 515, 4, -317, 917, -669, 3314, - 253, 1316, 259, 12, 8170, 15, 129, -200, - 120, -11, 34, -77, -13, 257, 79, 9, - 23, 54, 73, 0, -9972, 5, 7, 43, - 29, 4, -104, 43, -36, 76, -228, 1, - -77, -156, -69, -209, 84, -2826, 242, -1461, - -718, -14, 1784, 527, 226, 9852, 83, -15, - -389, 34, 51, -16, -46, -1, 232, 115, - 26, -42, -124, -78, 58, 3092, -2757, -111, - 223, -286, 23, -170, -166, -264, 331, -172, - -49, -26, 166, 2616, 128, 3118, 59, 844, - -121, -504, -193, -53, -95, 282, -21, -8, - -11, 58, -48, 9830, 25, -26, 53, 113, - 96, 125, 12, -64, 185, -31, 19, -251, - -307, -136, 1383, -37, -128, 56, 4303, -232, - -272, 44, -192, 531, -143, -697, -2291, 70, - 229, -432, -592, 1262, 906, -207, 1522, 261, - -7848, -39, -976, 150, 115, -139, 61, -26, - -211, 807, -25, 311, -98, -297, 133, 461, - -109, -6, -1031, 236, -2851, 86, 2184, -254, - -83, -119, 878, -107, -25, 1636, 1696, 1517, - 249, -41, -283, -66, 741, 704, -898, 302, - 470, 360, -7, -6002, 26, 268, -109, 150, - 202, 196, -262, -57, 160, 155, 7, 9, - -5770, 28, 127, 112, -76, -790, 45, -118, - 201, -831, 67, -81, 199, 296, 1692, -30, - -126, -121, 29, 387, 215, 269, -518, -232, - 155, 2735, -235, -82, -33, 3089, -3696, -39, - -51, 124, -220, 37, 51, -129, 194, -80, - 81, 0, -239, -1924, -244, 107, 372, 111, - 206, 418, 39, -118, -2059, -446, 1378, 661, - -2135, 122, -105, 60, 272, -91, -227, 48, - -3226, -88, -109, 199, 566, 158, 2412, -4380, - -177, 153, 252, 24, -323, 264, -116, -12, - -333, 99, -181, -124, 256, -131, -39, -45, - -88, 69, -26, -173, -4820, 286, -171, -82, - 431, 18, -827, -107, 142, 60, 300, 422, - 263, 61, 350, 85, 1088, -133, -1284, 70, - -4577, 5, 114, -23, 23, 2907, 174, 43, - 18, 33, -31, 320, -9, 290, 2, -7, - 39, -11, 52, 32, -4, 8454, 18, 10, - 67, 20, 22, -3, -209, -103, -212, -101, - -101, -420, -2837, -28, 398, 140, 1027, -187, - -2338, 406, -152, -288, 723, -412, -1851, 185, - 641, -190, 107, -7, -3194, -128, -382, 165, - -256, 85, 96, 155, -144, 431, -356, 342, - -2508, -2190, -265, -320, -1345, 27, -1981, -1949, - 95, -78, -456, -359, 382, -218, -102, 164, - 382, 907, 599, 665, 2843, 4275, 17, -156, - -264, 73, 104, -25, -120, 91, 84, 325, - 170, -65, -245, -23, 89, 52, 4651, 124, - 185, 30, 321, 145, 111, -1265, 128, -156, - 64, 24, -1934, 133, -84, -10, 34, 801, - -148, -88, 169, -1687, 419, 1739, -204, -70, - 185, 117, 379, -420, 145, -3650, -264, 1118, - 331, -818, -665, -420, 74, 32, -152, -226, - 6, 216, 4173, 23, 1230, 239, 2, -57, - -690, 516, 90, 58, -24, -61, 175, -2796, - -113, -270, 94, -2319, -158, -1075, -275, -647, - -3839, 37, 4267, 20, -49, -88, 72, -171, - -195, 45, -23, -159, -64, 110, -211, 42, - -211, 1591, 276, -3662, 213, 54, -180, 786, - -92, -329, 382, 344, 165, -63, 14, -7, - 66, 29, 8875, 43, -50, 65, 13, 15, - 48, -40, 114, 125, -27, 158, 3, 843, - 8, -646, 100, -3121, 1720, 88, 898, 346, -}; - -static const int16_t cb2224m1[] = { - 9581, -198, -100, -22, 237, -15, -101, -23, - 46, 129, 63, -143, 5, -307, -143, -9, - 27, 50, 40, 6048, 25, 58, -16, -161, - -109, -157, 137, 115, 121, 164, 4, -54, - 6477, -68, -120, -29, 45, -8, -13, 334, - -87, 105, -1460, 28, -334, -163, -64, -3629, - -71, 176, -195, 53, -1, -96, -560, -21, - 135, 178, -77, -4202, 20, 2544, -205, 85, - -332, 158, 61, -105, 398, -88, 14, 241, - -149, 62, -124, -136, -153, 27, 190, 2595, - 25, -2499, -530, 1809, -104, -2753, 298, 145, - -771, 139, 165, 2462, -502, 860, -174, 199, - 74, 163, -686, -25, 57, -103, -309, -360, - 39, -296, -2765, -319, -950, -678, -1159, -1743, - 1499, 1776, -176, 9, 44, -581, 69, 39, - 162, 326, -96, 329, -9, 1274, -2443, -105, - -50, 4212, -23, 146, -231, -22, -50, -128, - 11, 28, 116, -215, 46, 217, 204, 153, - -73, -156, -100, -31, 2632, -190, -2258, 199, - -1757, 194, 53, 38, -5723, 66, 169, 352, - -39, -150, -1, -462, 41, -98, -110, -40, - -5763, -190, -158, -1380, 205, -227, -402, 81, - -171, 407, -125, -320, -456, -317, 489, 698, - -308, 3989, -172, 402, 196, -457, -1238, -192, - -581, -63, -235, 153, -1094, -53, -45, -86, - 240, -192, -2660, 2356, 153, -60, 277, 33, - 198, -57, 1221, -2984, -327, -326, -48, 61, - 93, -34, -167, -311, 904, 348, 415, 57, - 2000, -77, 238, 40, -3072, -36, 283, -54, - -655, -250, -22, -569, -584, -18, 733, -251, - -72, -28, 80, -306, 211, 188, -149, 4596, - 305, 372, 351, -82, -184, -79, -65, 2688, - 2670, -54, -81, -170, 19, -88, 122, -117, - 33, 51, -29, -113, -2973, 46, -3294, 90, - 8, -180, -227, -62, 43, -25, 187, -380, - -29, -89, 138, -352, 231, 2632, 158, 1993, - -15, 350, 107, -982, -16, -1120, 136, -171, - -42, 2605, -186, 110, 167, 1673, 1140, -29, - -689, 81, 909, -455, 2979, 44, 1, -260, - 26, 28, -90, -568, -123, -175, 232, -38, - 2372, 111, 312, 529, -65, 331, 100, 488, - 12, -596, -497, 2311, -1097, 1242, -94, -2290, - -158, -2651, 16, -232, 3352, 24, -53, -83, - -5, -52, 205, -104, -294, 217, -196, -37, - -7, 0, -28, -45, 60, 13, 41, 111, - 142, -7331, -40, -200, 18, -166, -1266, -47, - -250, -592, -604, 33, 83, -204, -1131, -166, - 1348, -1337, 184, 50, -10066, 30, 24, -184, - 137, 53, 32, 87, -27, 151, 100, 10, - -47, 28, -138, 12, -2977, -376, 58, 168, - 1642, 144, 1039, -399, -807, 5, -1715, 12, - -142, -77, -306, 758, 674, -82, 3216, -369, - 60, 480, 276, -423, 5102, 3325, 169, 47, - 235, 37, 81, -86, -28, -56, -59, -205, - -126, 28, 279, -8433, 137, -26, -409, -19, - 106, -163, -76, -57, 235, 7, 131, -81, - -197, -318, 1281, 310, -2934, 972, -1335, 35, - -308, -93, -128, 433, 527, -193, -1303, 162, - -34, -87, -157, 262, 4999, 25, -311, -349, - 94, -262, 0, -219, 57, 12, -4, 10, - -17, 38, -320, 48, 156, 80, 5880, 48, - 45, 31, -1022, 31, 227, -727, -135, 261, - -21, -688, 307, 3196, 565, 627, -546, 237, - -2367, -33, 1622, -87, 1722, -201, 720, -539, - -288, -1012, 141, -388, -72, -20, -59, -2042, - -53, -101, 208, -233, -835, -16, 3092, 2, - 310, 94, -362, -163, -128, 30, -22, -145, - 420, -1, 322, -524, 2742, -276, 206, -2475, - 575, -653, -342, 1412, 1, 75, -14, 54, - 170, 66, 342, -261, 709, -75, 2240, -134, - 32, 665, 171, -134, 1822, 109, 569, 3129, - 168, -356, 53, 1259, -67, 43, 120, -124, - 2185, 2461, -17, -255, -349, -167, -158, -19, - 84, -732, -972, 286, 87, 4603, -160, 7, - 141, 1, 286, 310, -315, -99, 282, 384, - 68, 93, -1815, 63, -86, 121, -293, 210, - 115, 63, -174, 616, -1848, -124, 1275, 298, - 185, -267, 3516, -105, -162, -253, -434, -674, - -90, -2232, 38, 168, -261, 289, 70, 3714, - 4096, -81, 17, 56, 57, 68, -20, -146, - 28, -152, -17, -97, -131, 2648, 71, -3359, - 40, -277, 313, 85, -26, 41, -202, 76, - 8, -80, -160, -102, -17, 155, 189, 1552, - -3498, -446, -103, -232, -205, -574, -132, 169, - 206, 1689, 1043, -736, -178, -93, -2969, 26, - -251, -148, 139, 70, -325, 117, -3073, 9, - 43, -11, -380, -190, -314, -3012, 50, -330, - -26, 710, 153, 19, -2943, 58, -3052, -56, - 7, 40, 9, 321, -37, -461, -22, -374, - 57, -203, 16, -15, -25, -16, -37, -8, - -41, -116, 7964, 70, -59, 77, 200, 0, - -43, 118, -72, -67, 104, -6, 78, 171, - 13, -103, 793, 98, -4738, -204, 11, 30, - -72, 33, -62, 47, 157, 236, -147, -416, - -726, 578, 5, 4038, 162, -2, 2367, -138, - -185, 470, 3121, 70, 185, -22, -205, 37, - -63, -335, -397, 43, 10, -6557, -112, -254, - 106, -129, -236, 0, -250, 42, -128, 84, - -531, -27, 2259, -282, -21, -70, -408, 19, - -664, 945, -196, -1074, 1369, -40, -3233, 28, - 20, -2133, 125, 343, 113, 584, -14, 50, - -130, -464, 513, 807, -4474, -63, 57, 1120, - 64, -30, 346, 462, 129, 219, -30, 287, - 448, 384, 198, -359, 1097, -256, 828, -2635, - -314, 336, 506, -144, 194, 167, 1323, -273, - -4168, 2805, -118, -8, 136, -82, -212, 53, - -259, -61, 94, 214, 11, 29, -262, -69, - 24, 102, 45, -31, -186, 58, 641, 659, - -172, 3628, -192, -423, 34, 3, 45, 19, - 349, 117, -5, -4923, 99, -148, 180, 631, - 50, -204, 641, -92, 156, -1985, 1077, 201, - 56, -405, 710, -220, -1917, -273, -234, 100, -}; - -static const int16_t cb2224sl0[] = { - -3113, 97, 229, 309, -156, -226, -469, 582, - -3202, -336, 102, 20, 96, -960, 297, -227, - 592, -3352, 2798, -637, -133, 191, -407, 170, - -576, -203, -280, 808, 853, -502, -113, -1704, - -1025, 411, 2802, 233, -568, 360, -616, -1715, - 47, 391, -2117, -458, -291, -149, -82, 26, - -29, -88, -156, 7905, 32, -75, -154, -78, - -44, 155, -1, -338, -891, 170, -75, 155, - 226, -192, -328, -239, -574, -91, 95, -600, - 4271, 25, 990, -207, 4676, 59, -324, 884, - 363, 65, 423, -776, -906, -79, -4, 1475, - 549, -252, 3584, 3543, -409, 282, 278, 125, - -379, 125, -180, -123, -252, -316, -193, 347, - 53, 2009, 195, 152, -104, 233, -75, -546, - 564, -177, 3243, -865, -924, 518, -692, -381, - -1885, -110, -188, 1140, -2043, -438, -1721, 1019, - 1678, 13, 273, -751, 922, -291, -15, 75, - 232, -112, 60, 2702, 88, 175, -119, 43, - -549, -1094, -1879, 401, 1587, 1287, -41, 41, - -116, -23, 313, 168, 147, -101, -57, -115, - -6990, 54, -14, -240, -164, 127, 25, -703, - -361, 769, 1555, -2440, -2616, -192, 86, 769, - -29, -721, 554, -663, 327, 659, -31, -79, - 91, 365, -74, 1268, 115, 480, 3054, -1758, - 1704, 759, -657, -272, -329, 31, -145, -534, - 1265, 73, 435, -54, 480, -867, 2724, 2373, - 890, -314, -112, -2576, -598, 473, 121, 2764, - 1659, 105, 579, -416, -87, 158, 300, 447, - -281, -6109, 35, 217, 185, 56, -357, 151, - 108, -49, -282, -484, -220, -78, -141, 256, - -1095, 1812, -985, 1115, 555, -2116, 2317, -1141, - -792, -866, -119, 187, 615, -194, 73, -43, - 268, 437, 250, -52, 477, -249, -475, -2621, - 590, -2987, -603, -652, 971, -684, 337, -140, - -336, 2342, 390, -204, 295, 85, -44, 321, - 754, 2660, 61, 782, 1654, -76, 2727, 1590, - -1099, 354, 49, 2784, 443, -762, 828, -308, - -493, -755, -370, -336, -207, 388, 630, -127, - 1955, 1929, 1270, 2054, 525, 388, 562, 942, - -789, -453, 158, 995, -99, 2258, -317, -493, - 385, -90, -79, 199, -1187, 519, -254, 179, - 573, 2803, 2341, 407, 95, 515, 332, 1, - -6, -337, 142, -316, 418, 542, 3281, 10, - 604, -542, -1595, 43, 79, 10, 75, -122, - 100, -55, 212, -223, -353, -557, 490, 4870, - -3689, 3594, -145, -192, -47, -252, -380, -180, - -221, 656, 78, -188, 120, 135, -253, -437, - -208, -151, -504, 217, -3715, -150, 528, 121, - -1468, 383, 823, -55, -1167, -8, -198, -515, - -296, -24, 84, 129, -472, 7, 5071, -114, - -200, -16, -271, 59, -430, -142, -315, 90, - 273, -56, 370, 3342, -159, 235, 934, 1605, - -1499, 207, -1650, 1137, 396, -2250, 276, -320, - -317, -23, 276, -519, 163, 566, 366, -6, - 2262, -2035, -662, -3300, -133, -3811, -362, -348, - 113, 146, -79, -298, 238, 221, 99, 194, - 326, 325, -112, -8160, -59, -15, 8, -41, - -261, -20, -6, -68, -140, -41, 167, -125, - 129, 337, 2404, 281, -336, -475, 2085, -2646, - 572, -1308, 376, 114, -506, 1062, -575, -529, - 3347, -212, 520, 274, -163, -3058, -93, -203, - -932, -207, -36, 303, -117, 278, 287, 204, - 205, -228, -242, 227, 3, 611, -190, -458, - -44, -209, 122, -390, -4561, -139, 1378, -329, - 440, 989, -1782, -348, 1241, 967, -477, -2312, - 554, -970, -1103, 473, -771, -50, 150, 327, - 394, -267, -648, -680, 2376, -2543, 276, 1220, - 552, 10, 1399, -1498, -801, 9, 2351, -55, - 155, 327, 88, 864, 428, 179, -3234, 6, - 544, -647, -306, 132, 329, 1147, 1920, 1436, - -2107, -1122, 341, 2020, -432, -97, 117, 793, - 100, -693, 174, 3639, -570, 910, -2771, 231, - -148, -960, -1085, 57, 188, 744, -709, -441, - 533, -295, 1287, 2939, 2987, 885, 611, 700, - 364, -205, -855, -617, 48, -162, -244, -318, - 208, 772, -124, -2505, 454, 330, -220, 335, - -362, -899, -827, 2188, -40, -1638, 356, -160, - -127, 2886, -69, -41, 209, 1847, -236, 2752, - -24, 387, 354, -111, 526, -237, -2169, 1319, - 2211, 144, -348, -434, -319, 1373, 78, 906, - 701, 539, -134, 414, 496, -325, -36, 116, - 124, 4198, -35, -439, -208, -531, -100, 1453, - -175, 723, -908, -461, 87, 127, -91, -125, - -140, 8012, -186, 23, -93, 107, 176, 218, - 35, 193, 174, -27, -4, 77, -103, -199, - 116, -41, -80, 186, -6965, -188, 125, -54, - 43, 9, -49, -192, 69, -136, -24, -117, - -2244, 2289, 145, 226, -1161, -1950, 881, -152, - 1611, 1015, -174, -277, -158, 369, 49, -233, - 221, 275, 69, 108, 136, -124, 1, -470, - 376, 149, -7596, 55, 53, 213, -247, 80, - -217, -11, 189, 125, -17, -141, 165, -2890, - 14, 201, 106, 242, -254, -306, -3157, 459, - -10, 24, -271, 877, 437, -438, 18, -126, - -9, 5553, 63, 22, 55, 172, 21, -335, - 127, 160, 208, 121, 13, 1989, 676, -294, - 2208, -78, 634, -1518, -1037, 1309, 124, -39, - -322, -1420, -404, 377, -35, -14, 178, 110, - -8146, 26, -98, -153, -243, 145, 280, -8, - 29, -57, 85, -309, 281, 282, -47, -27, - 2827, -947, 141, 856, -2481, 406, -638, -362, - -1031, 230, -341, -119, -17, 1, 190, 41, - -15, 5111, 59, 74, 123, -282, -25, -300, - 4, -460, -216, 295, -217, 26, 227, 62, - 385, 748, 2923, 1946, 391, -1676, 599, 148, - -456, -96, 1066, 478, 117, 255, -169, -669, - -1939, -656, 2676, 677, -2020, -1314, 425, -525, - -89, -522, 2707, 153, 5, -207, 244, -1045, - 331, -1315, -82, 449, -2444, 326, -484, -2232, - 2380, -591, -999, -2552, -1581, 349, -440, 217, - 298, -729, -6, -396, -74, 110, -70, -3543, - -388, -51, 596, 126, 295, 2075, -123, -693, - -1072, -1779, -420, 127, 432, -3241, -231, -246, - 105, -437, -67, -119, -2941, -257, 47, -969, - 379, 618, -93, 7, 202, -425, -38, 140, - 458, 3599, 242, -24, -811, -624, -19, 524, - 2398, -300, 111, 376, 2015, 431, 125, 231, - -293, -2379, -634, 1842, -1, -1326, -610, -88, - 128, 80, 75, 30, 172, -235, 34, 206, - -79, 328, 128, -283, -6862, -101, 260, 68, -}; - -static const int16_t cb2224sl1[] = { - -3710, -340, 3183, 200, -124, 423, -417, -432, - 232, -808, 85, -145, 39, 196, -197, -60, - -154, -213, -320, -2941, 993, 3044, -508, 61, - -853, 75, 40, 873, -765, -365, -621, -2670, - 188, 57, -403, -230, -137, 40, 565, -1910, - -1120, -1019, -603, -1927, 150, -3089, 23, -416, - -199, -3265, 15, 128, -525, -531, 91, -39, - 578, -388, 315, 40, 2376, 1762, 2, -1475, - -1774, 111, 934, -459, 777, -582, 114, -218, - -82, -195, 165, 2171, 632, -67, 239, 345, - -257, 104, -34, -879, 488, -422, -2156, -823, - 1940, 699, 2911, -233, -125, -218, -111, -335, - -3475, -61, -71, -445, 249, -330, 102, 376, - -116, 2667, -453, 19, -4129, 90, -507, 236, - 418, 43, 79, 61, 296, 181, 190, 408, - 216, 198, 32, -81, 245, -157, 5555, -162, - 318, 179, 339, -463, -448, -254, -526, -192, - -427, 575, 588, 2792, 2683, -853, -566, 19, - -26, 106, -220, 518, 734, -233, 68, -604, - -231, 256, -187, -59, -405, 206, 331, -25, - -4837, -323, 146, 541, 723, 915, -144, 450, - 102, -371, 27, 88, -80, 276, 239, 101, - 157, -69, -14, 234, -8192, -18, -110, -52, - -8, 48, 79, -43, 153, 187, 211, -118, - -111, 238, 11, -2006, 680, 478, -695, 3078, - -30, 892, -23, 1512, -194, 423, -16, -318, - 895, 406, 634, 47, -3277, -205, -764, 297, - -357, -61, -188, -1547, -868, -174, 342, 261, - 1926, 88, -35, -3250, -20, 3168, -368, 778, - 376, 167, 598, 442, 134, 487, 164, -32, - 245, 436, 2067, 595, -578, 49, -163, 633, - 138, -279, -99, 118, 1141, -3168, 580, -90, - -3192, 551, -663, -2673, -55, 147, 1307, 9, - 15, 432, 307, 527, 1002, -469, -2380, -342, - -293, -73, -259, 410, 309, 76, -320, -161, - 282, -3300, -7, 160, 732, 484, -65, 147, - 2923, 2321, -840, 1933, 268, 684, 1172, -377, - -365, -568, -283, 492, -538, 409, -194, 17, - -297, -52, -123, -270, 161, -94, 92, 4495, - -396, 540, 229, -30, -108, 29, 1, 198, - 492, -572, -394, -2386, 2787, 885, -1175, -129, - -1137, 220, 148, 261, -65, -244, 1, 58, - 195, -49, -290, -94, -21, 105, 71, 6641, - -200, -407, -496, -75, 233, 222, 549, 363, - 188, 739, -869, 122, -355, 3326, 323, -2366, - 115, -3207, 2783, 2015, 148, 924, -153, -133, - -175, -287, 400, 73, -181, -174, 72, 45, - 219, -92, -11, 59, -5407, -362, -188, -120, - 239, 249, 133, -229, 158, 180, -575, -2386, - -354, 248, 532, -590, 615, -85, -69, 394, - 3052, -877, -320, 484, 218, -463, -202, -841, - 1729, 284, 1253, 2193, 526, -2444, -351, 1287, - -373, 387, 440, -203, 163, -153, 206, -57, - -96, 2616, -84, 552, 33, 705, -731, -843, - -2197, -2138, -570, 22, -264, 2143, 725, -132, - -392, 471, -245, 51, 739, -1057, 1049, -760, - 2701, 456, 20, 484, 595, 3248, -1415, -862, - 332, -417, 323, -431, 2082, 78, 684, -169, - 596, -228, -219, 172, 160, -180, -228, -3193, - -520, -100, -447, -629, -2178, -259, -246, -1788, - -2264, 223, 115, -74, 230, -2515, 212, -179, - 456, 209, -2379, -246, -345, -102, -559, 259, - -270, -426, 333, -358, 2866, -589, -1494, -418, - -160, -138, 2088, 683, -1313, 1061, -88, 916, - -148, -2329, -301, -271, -249, 2822, -525, -405, - 592, -322, -1328, -16, 135, -582, -676, -503, - -2162, -327, -237, 361, 166, 600, 1176, 1015, - 97, -5, 465, 2321, -4544, 202, -350, 313, - 149, 544, -420, 552, 183, 351, -1663, 688, - 238, 587, 907, -1719, 1267, -2325, 368, 236, - 296, -2608, 240, 997, 496, 105, 75, -179, - 235, 125, -40, 57, -22, -412, -464, -494, - -81, 576, -3461, -1037, -744, 1358, -856, -284, - -536, 387, -358, 184, -85, 2150, -1142, -124, - 119, 1242, 648, 711, 2161, -591, -1864, -672, - 62, 1879, -13, 55, 285, -167, 142, -130, - 322, 8, -35, -230, 632, -699, 4114, -500, - -189, -48, 2746, 47, 421, -1200, 2418, 460, - -306, 331, 164, -1358, 802, 453, 458, 3594, - 3065, -24, -134, -437, -892, -110, 241, -368, - 336, 673, -147, 130, 154, 89, 81, -341, - 7151, 175, 118, -227, -282, 262, 276, -118, - -118, -245, 7, 144, -87, -136, -146, -484, - 70, 221, -220, -13, -7638, 93, -38, -319, - -478, 26, -28, 281, -180, 182, -186, 90, - 192, 50, -2919, 153, -2651, 289, 47, -783, - 768, 384, 39, 194, -2358, 1242, -1679, 80, - 1292, 28, 682, 2807, 342, 466, 299, -380, - 376, 4466, 12, 553, 153, -447, 733, 99, - 8, -142, 606, -2364, 168, 167, -62, 404, - -3144, 352, 115, -3734, 360, -202, -462, -196, - 464, -412, 192, -363, -413, -405, 254, 357, - -2801, 1054, -1602, 642, -254, -430, -2259, -97, - 16, -311, 757, -64, 412, 339, -227, -216, - -29, 219, 67, 63, 26, -232, -138, -301, - 241, -52, -6118, 223, -379, -157, -221, -201, - -93, -5630, -286, -194, 133, 46, 151, 444, - -472, 103, -115, -259, -53, 673, 1744, -2374, - 359, 2541, 613, -393, 1235, 221, -117, -842, - 1166, 105, -142, 1426, 3, -423, 36, 398, - -2742, 723, -740, 985, 498, 431, -1312, 832, - -1644, 146, -69, -110, 420, -130, 335, 269, - -2865, -67, -88, 50, 2735, 1038, 973, 371, - 654, -169, -112, 579, -319, 2434, -760, 710, - 241, -1889, 39, -1807, -30, 1383, -1080, 449, - 639, -2478, -760, 559, 298, 56, -421, 818, - -442, 1558, -1610, 2136, -12, -11, 592, 73, - 77, -172, 77, 92, -113, 281, 581, -584, - -4448, 507, -195, 183, -508, 312, -724, 1043, - -18, -10, -776, -534, 249, -3178, 904, 1234, - -482, 382, -1040, -448, -579, 227, -82, 5628, - -165, 255, 109, -141, 7, -28, 63, 93, - -211, 0, 162, 581, -153, 5844, -66, 122, - -102, -90, -205, -181, 243, 312, 111, -435, - -105, -343, 272, -141, 6, -98, -16, -73, - -26, -125, -7627, -73, -66, 108, -175, 186, - -189, -102, -240, -37, -354, -260, -120, 30, - 87, 2560, 3157, 369, -662, 338, -503, -66, - -1405, 178, 1100, -683, -2618, 2459, -1291, -248, - -139, -683, -865, 1445, 165, 368, 507, -585, -}; - -static const int16_t cb2224ss0[] = { - -6880, 657, -621, 69, 219, -588, 681, 229, - 248, -302, -110, 734, 12, 253, -454, -890, - -3596, 778, -2600, -256, 529, 332, -69, 295, - -455, 982, -265, -70, -332, -367, 1494, 586, - -158, -1054, 2529, -313, -661, -1302, -2486, 476, - 5, 126, 581, 361, 1618, 650, 2033, 202, - 76, -265, -161, 3659, -800, 1069, -167, -1792, - 389, -580, 597, -268, 621, -1035, 710, 854, - 2004, -785, 2714, 1659, 785, 800, -80, 9, - -341, -1032, 789, 651, 1068, -609, 661, 747, - -928, -999, -1369, -1173, -416, 1596, -2800, 330, - 546, -1275, -746, -392, -529, -378, 3571, -2795, - -731, -183, -330, -1591, 371, 866, 323, -516, - -89, 2277, 1593, 960, -1726, -2229, 727, -415, - 189, 500, -145, -177, 550, 467, 240, 1131, - 474, -419, -1236, 674, -616, -519, 2439, -1213, - -650, 867, 974, -908, 1229, -512, 932, -495, - -2521, -865, -466, 8, -426, 912, -77, -236, - -407, 433, 128, 3653, 854, 243, 770, 191, - 224, -68, -453, -383, 279, -701, -691, 282, - -449, 1148, -783, 241, -5021, 643, 8113, -345, - 13, 90, -57, 475, 64, -268, -163, -100, - -95, 518, 577, 541, 2055, 358, -157, 360, - 280, -840, -1161, 500, 95, 302, -662, 1134, - 827, 3300, 695, 775, -798, -2651, -2891, -1123, - 555, -1125, 156, 328, 671, 751, -347, -972, - -392, -1216, 2725, -5152, -402, -15, 150, 31, - -182, -278, 245, 81, -3, -46, 310, -72, - -138, 1511, -1762, -1840, -364, 123, 2801, -16, - -543, -1312, 562, -262, 148, 521, -711, 61, - -863, 145, 329, 761, 76, -155, 101, -4986, - 192, 269, -364, -174, 640, -261, 629, 3638, - 397, -1757, -1177, 342, 388, 1089, 824, 115, - 150, 125, 806, 1271, -198, 800, -175, -897, - -649, -837, 690, -755, 1416, -2347, 1179, -781, - 826, 1567, -148, -156, -1036, -1572, 1248, -187, - 464, -260, -749, -1070, 85, -466, -2160, -2802, - 233, -181, 447, -482, 113, 548, 2957, -1600, - 1341, -559, 803, 2085, -807, -711, -1169, -456, - 657, -76, -147, 1932, -1054, -967, -1100, -49, - -2829, 1412, 929, 1207, 58, -146, 77, -458, - 538, -627, -12, 214, -2397, 692, 1284, 366, - 1286, 1997, -856, 267, 1866, 1236, 25, 254, - -1187, 3456, 283, 584, 2348, 604, -1130, 7, - 500, 232, -51, 120, -695, -930, 317, 67, - -1346, -500, 312, -1060, -2338, -1860, -1491, 1539, - -1707, 778, -653, -41, 401, 311, -13, 2155, - -1011, 1163, 712, 2090, 1336, -726, 574, 1200, - -1254, -1567, 723, 683, -877, -653, 1137, -1594, - 1127, 2641, 465, 259, -2095, 696, -405, 40, - -259, -808, -942, 395, -180, -1119, -966, -230, - -534, -114, 88, -661, 757, 75, -286, -119, - 924, -2925, 2483, 1662, 1823, 590, 4307, 810, - 447, 165, 243, -184, -162, 436, -126, -194, - 365, 601, -354, -1983, -211, -663, 276, 155, - -696, -2542, -830, 2374, -235, -585, -469, -478, - 21, 867, -1633, 1949, -949, -330, -546, 328, - -224, 1236, 266, -1117, 36, -61, 221, 153, - -3491, -1463, -237, 4676, -241, 273, 268, 347, - -393, -277, 168, 426, 155, -65, -605, -569, - -1416, -1303, 1248, 595, -148, 512, 3622, 291, - -444, -523, 616, 105, 101, 1357, 772, -337, - 494, 570, 15, 150, -400, 572, 590, 1674, - -4106, 940, 167, -327, -336, 696, 591, 362, - 279, 4489, -1325, 608, 294, -41, 549, 982, - -31, -184, 367, 77, -466, 398, -1928, -607, - 239, 55, 15, 1031, -486, 2788, 2151, -519, - -1197, -1144, 274, 671, 1620, 2079, -1555, -961, - 543, -11, 26, -627, 777, -581, -1060, -1177, - -808, 807, 2863, 607, 144, 195, -274, 18, - -5656, -355, -1026, 56, 116, -431, -493, 517, - 286, 353, 353, 199, -651, -863, -276, -556, - -562, -867, -143, -355, -323, -14, -54, -5354, - -43, -1592, 8, -543, 24, 94, -731, -545, - 705, -171, 504, -1078, -3367, 1349, 452, -148, - 1183, -1650, -1400, -246, -1032, -119, -309, -566, - 998, -3240, -444, -658, -605, -186, 491, 439, - -190, 688, -29, -965, 2562, -112, -329, -25, - -2593, 355, -53, 692, 12, -593, 1930, -804, - -82, 386, -632, 927, 1006, -229, -1147, -181, - -1075, -245, -3678, 904, -298, 2263, 50, 563, - 337, -1051, 173, 310, -3540, -615, -504, 749, - 192, -90, -113, -730, -1994, 802, -45, 2234, - 167, 289, 1722, -562, 682, 453, 1571, 171, - -2429, -441, -230, -1144, 985, -1602, 358, -685, - -23, -523, -529, -2438, 700, -624, 37, -1475, - -1318, 3292, 702, 394, -798, 2563, 1057, -335, - 614, 270, 3135, -1281, -2089, -250, -140, 45, - -517, -470, -1429, -172, 2637, 267, 55, -1037, - -174, 912, -865, -786, -406, 537, -2805, -642, - -1599, 888, -1044, -175, 312, 28, -1157, -240, - -181, 298, 521, 3802, -87, 93, 48, 1336, - -1071, -1870, 339, -1106, -944, -1036, 361, -3719, - -147, 625, 326, -122, 407, -217, 396, 273, - -2, -315, -262, 632, 6868, 228, -267, 207, - -29, -274, 192, 63, -353, 588, 550, -3, - 156, 2115, 1580, -2366, 306, 633, 1354, 2313, - -360, -345, 270, -499, -976, -3685, -1305, 907, - 1431, 1545, -1334, 18, 1159, 229, -124, 157, - 470, -105, 700, -1786, -1895, 795, -1052, -278, - 745, -111, -45, 694, 599, -3469, 552, -70, - -222, 45, 896, -251, 1, 250, -769, 301, - -1151, 1313, 4314, 710, 680, -169, -663, 40, - 399, 1171, 581, 775, 936, -488, -2918, 155, - -169, -1560, -862, -473, 783, -72, -1791, 567, - -2109, -156, 1250, -1486, 3253, 61, -50, -374, - -277, 942, 111, 607, -316, 197, -748, 871, - 612, -242, -296, 53, -193, 1233, 11, -962, - 505, -4492, 21, 754, -150, 451, 183, 881, - -652, -159, 6384, 170, 271, 1035, 401, 48, - -463, -240, -95, -625, 613, -91, -1138, 1172, - 542, -1483, -2638, -1396, -1173, 612, 512, 1355, - 977, -362, -22, -17, 124, -3178, -532, 352, - -2691, 610, 569, 740, -1603, -5, -492, 704, - -436, -96, -595, -1495, 2730, -3089, -164, 565, - 1300, -477, -569, 1069, 294, -233, -133, 708, - 150, 388, -2108, -1042, -1603, 2275, -1722, 561, - 140, 507, -899, -281, 162, -1297, 1504, -158, - 193, -730, -944, -2484, 615, -30, 32, -354, - -383, 86, 329, -3434, -382, -1604, -299, 208, -}; - -static const int16_t cb2224ss1[] = { - 8192, -187, -471, -201, 185, -465, 976, 257, - 83, -530, 310, 676, 341, 48, 265, -351, - 306, 280, 302, 48, 496, -339, 424, -5250, - -253, 604, -317, -289, 278, 573, -579, 79, - 3218, -574, -377, 276, 2831, -287, -254, 332, - -225, 42, 162, -457, -959, -1421, 683, -59, - -33, 3362, 393, 606, 249, -873, -930, 1224, - 1469, 37, -1592, 1665, -582, 1729, 284, 106, - -4753, -120, -475, 867, -444, -203, 431, -11, - -526, -324, 732, -1070, -160, -611, 1808, -297, - -536, -194, -822, 1224, 2220, -2330, 72, 1004, - -787, -149, 557, 2925, 29, 809, 2397, -1143, - 648, 904, -568, -707, -839, -274, -1322, 1177, - -467, -482, -5181, 234, 223, 354, 386, 737, - 1273, 234, -353, 31, -8, -392, 85, -234, - 1366, 1449, 120, -695, 838, -622, -96, 382, - -1421, 612, -173, -3199, -150, 474, -394, -561, - -1171, 2541, -271, 2513, 670, 285, 636, -452, - -202, 1319, -2182, -935, -586, 243, -813, -41, - -53, -1041, 212, 58, -3424, 111, 268, 964, - -3231, -500, 867, -191, 207, 543, 383, -1509, - -2712, -2752, 201, 428, 721, 498, 19, -747, - 67, 87, 500, 1200, 2244, -1158, 466, -1032, - -153, 1197, 2737, -324, 2002, -338, 89, -428, - 78, 575, 330, 2013, 175, 305, 567, -539, - 17, 384, 485, 860, 3330, 173, 586, 649, - 388, 963, 1820, -2610, 251, -2966, 1383, -153, - -146, 564, -718, 998, -1283, -566, -619, 394, - 459, -1233, 2566, -357, -2601, 98, -929, -367, - -501, 96, 1217, -1695, -324, 393, 261, 1745, - -1095, -751, 924, 1044, -337, -1243, 393, 2454, - -1499, -245, 902, 925, -2126, 167, 838, 638, - 2296, -294, 306, -715, 2794, 1522, -339, 21, - 318, -95, 1334, 75, -173, -91, -2012, -920, - -801, 334, -3363, -348, 550, -911, -261, -1073, - 185, -425, 431, 515, -339, 1817, -1589, 241, - 548, -337, -471, -3532, -1166, 888, 141, -277, - 1353, 310, -654, 198, -516, 2951, 2251, -534, - 701, 237, 20, -597, -301, 3, 410, -456, - -581, -1254, 1052, 1321, 165, 3108, 477, 196, - 2716, 85, 5, -34, 721, -562, 4, 84, - -793, 744, 243, 134, -385, -129, -122, -128, - -333, -483, -604, 269, 6209, 3, 515, -63, - -634, -551, -795, -1696, -2210, 2184, 348, 30, - 413, 2531, 214, 214, -186, -72, -552, 958, - 1727, -1639, 618, -61, -432, 365, -753, 15, - -14, 33, 976, -940, -355, 3318, 677, -1938, - 21, 881, -326, -83, -3355, 1483, -1211, -674, - 166, 139, -276, 158, -736, 1038, -1005, 1129, - 1219, 1115, -392, 558, 96, -188, 314, 536, - -423, -3262, 395, -130, 1099, 304, -181, 853, - -160, -1272, 428, -179, 634, 608, -173, 2690, - -2191, 1385, -518, -416, 3239, 3250, 313, -23, - 200, 643, -639, -17, -208, 27, -182, 262, - -203, -671, 157, -4131, 383, -404, 337, 51, - 431, 92, 138, -438, 29, 337, 488, -252, - 656, 509, 2037, -635, -1074, -1115, -2135, -772, - -386, -214, -654, -441, 1661, 542, -383, -1720, - 22, -103, -1474, -1288, 4361, 282, -1252, 734, - -858, -556, 294, 243, 293, 133, 848, 65, - -727, -887, -1314, 443, -96, -422, 4268, 672, - 142, 608, -442, 843, 365, -866, -157, 780, - 107, -888, 2089, 1769, 73, 739, -15, -1730, - -1235, 920, -1713, 163, 552, 1479, -692, -755, - 1430, -193, -276, -264, -690, 772, 1403, -40, - 679, -260, 642, -3562, 962, 2053, 1348, 36, - -2974, 155, 303, 821, -944, -179, -967, 632, - -725, 411, -447, -463, 694, -337, -146, 59, - -1, -416, 12, 524, -497, -4682, -745, 625, - 1011, 20, -462, -503, 2012, -475, -27, 85, - -1190, 534, 2250, 87, 2591, 1195, 1665, 423, - -813, -571, -372, 2601, -2013, -853, -734, -403, - 793, -549, 1243, 312, 722, -1013, -1434, -749, - -571, 494, -88, -129, 1331, 806, -1227, 326, - -1164, 2487, -59, 2346, 583, 519, 368, 793, - 1178, 661, 140, 1226, 378, -429, -1214, 1438, - -319, -77, -1495, 3598, 361, 21, 39, 1930, - 198, 1050, 531, 274, 32, -499, -349, -5, - -133, -3324, -379, -742, -250, -1618, -1536, 2084, - 1369, 765, -132, -324, 406, -2198, 314, 502, - -1431, 759, -729, 320, -2120, 1484, 2468, -3283, - 4, 272, -2, 492, 91, -803, 48, 691, - 375, 87, -508, -725, -632, 268, 2929, 1302, - -11, -628, -2225, 723, 533, 909, 934, 682, - 350, 1509, -707, -1142, 106, -2174, 342, -965, - 456, -655, 1137, -553, 415, -418, -2631, -121, - 237, 3, -1123, -1555, -1413, -3333, 717, 115, - -1030, -1007, -819, 130, -851, 281, -43, -473, - -1091, 326, 869, -377, 278, -148, 418, -2104, - -422, 623, -1777, 633, 1033, -2031, -1221, 4126, - -60, -16, 8025, 243, -340, -599, -501, -289, - -219, -104, -230, 464, 191, 18, 345, -65, - -68, -481, 625, -822, -4011, -516, 741, 734, - -316, 530, 122, 945, 371, -298, 1194, -250, - -167, 392, -95, -151, -1, -486, 189, 90, - -140, 30, 4485, 581, 54, 1905, -895, -2032, - -174, 2473, -688, -104, -315, -376, 830, 296, - -548, 754, 195, -901, -1548, -1931, 792, 510, - 294, 153, 619, -1034, -3038, 1134, 142, -29, - -806, -118, -29, -2314, -159, 770, -2899, 23, - -1045, 1037, 1496, 1104, -527, 135, -281, -310, - -59, 202, -346, -612, 206, 27, -456, 758, - 67, 3547, 867, 227, -3, 573, 1440, 421, - 170, 1491, -691, -43, -8, 784, 307, 557, - 618, -2387, 566, -396, 182, 877, -2666, -163, - 553, -155, 691, -188, -1584, -1085, 1033, -308, - 1356, -570, -721, -232, -3145, 104, 511, -964, - 2783, -685, -168, -51, 1554, -1816, 2431, 327, - -440, 1174, -265, -36, 120, -397, 1094, -1254, - -973, 574, 1085, -139, -751, -529, -240, 25, - 1137, -467, -3471, 338, -806, -2028, 94, -98, - -336, -537, 1189, -880, -3607, -168, -59, 100, - 309, 1097, 295, 262, 106, -8, 210, -7461, - 395, -248, 461, 490, -326, 264, 105, 13, - -160, 608, -443, -1331, 835, -1342, 3507, 763, - 966, 101, 1047, -469, -1455, -1080, 28, 99, - -44, 270, -752, 130, 2, 57, 358, -409, - 2, -658, -812, -899, 155, 141, 2101, 3616, - 40, -1957, -1028, -4137, 212, 1580, 578, 1019, - -512, 167, 366, -580, 448, 216, 79, -149, -}; - -static const int16_t cb2224sm0[] = { - -4334, 1434, -228, 1477, -1329, 230, 686, -558, - 486, -188, 424, -454, -568, -141, -326, -132, - -39, 2488, 9, 631, 513, 460, -417, 2656, - 633, -1404, -81, -283, -287, 480, 2558, -19, - -158, -2699, 405, 276, -639, -151, 529, 241, - -941, -796, -213, 1125, -391, 2515, 78, -177, - 2677, 217, 955, -687, 867, -485, -121, 1023, - -1572, -591, 139, 798, 1262, -467, 722, 2643, - -237, -1048, 386, -432, 180, -788, -178, 234, - 403, 267, 312, 2661, 585, -2775, -686, -88, - -16, -1243, -445, -259, 303, 298, 285, 277, - 2355, 163, -2399, -416, 115, 2277, -707, 194, - 283, 1183, 23, 119, 97, 8192, -40, 67, - -101, 151, 169, 21, -147, -160, 55, -207, - 550, -36, -500, -32, 225, 206, 72, 179, - 464, -406, 52, 696, -18, -4827, 1547, -516, - -2275, 855, 430, -523, 83, -1633, -1898, 285, - 202, -645, -167, 102, -124, 382, 24, 236, - 830, 324, -84, 491, -95, -154, 767, 25, - 4741, -574, -2576, -297, -250, -346, -2867, -64, - -1119, 1007, -883, 457, -328, -854, -981, -55, - 6922, 569, -307, 261, -100, -832, 129, 416, - -154, 681, -136, 1152, -144, -26, -2266, -320, - -141, -897, 544, -206, 845, -590, 88, 211, - -1761, -574, -653, -2788, 252, -266, -4252, 295, - 97, -2112, 209, -144, 655, -89, -369, 591, - 205, 1137, 30, -2907, 88, 92, -240, -3106, - -16, -398, -576, -720, 421, 427, -423, -195, - -18, 2503, -133, -918, 104, -512, -489, 2623, - -314, 215, -103, -1014, 761, 382, -1456, 1719, - -980, 248, 55, 644, -1945, 42, -162, -35, - -852, 1993, -189, 664, -149, 3132, -50, 3438, - 550, -234, -566, 434, 64, 379, -169, -291, - -718, -608, 31, -207, 651, -2567, -790, 906, - 518, 1740, 373, 1158, 114, -2044, 285, -1136, - -373, 932, -2185, -488, 148, 3, 724, 623, - -568, -359, -2748, 751, -1098, -858, -1140, -253, - -2377, -402, -312, -398, -47, -2618, 816, -568, - 1274, -158, 118, 107, 181, 394, 2758, 80, - -3057, 20, -279, 110, 482, 1010, -162, -1081, - -56, 685, 2207, -10, 82, 440, 593, 43, - 1010, -853, -624, 288, -3045, -426, 9, 132, - 104, 157, 466, -118, 116, 226, -214, -219, - 299, 6093, 122, 7, 174, 444, 200, -42, - -4, -313, 99, 218, 292, -159, -409, 523, - -1357, -4098, -96, 968, 8, -172, -444, -1040, - 755, -476, 967, 175, -100, 1689, -813, 3175, - 369, 1828, 248, -161, 6693, 631, 536, -125, - 274, -467, 259, -427, 130, -523, 361, 584, - 27, 60, -57, -30, -8192, 148, -64, 217, - -308, 163, -116, 89, 108, 191, -129, -149, - 128, 60, 575, 253, -385, -2937, 888, -1402, - -543, -607, 2639, 156, 251, 6966, -147, -382, - -388, 39, 476, 260, -1048, 575, 401, -245, - -441, 121, 389, -666, 95, 2919, -2212, -765, - 169, -161, 184, -320, -315, -497, 136, -470, - 479, -541, 712, 2966, 519, 2595, -77, 1089, - 18, -697, -616, 241, -54, 388, 461, 368, - 144, -149, 181, 7699, 11, 3, -368, 65, - 304, 358, -29, 255, -162, -169, -470, -16, - 198, 92, 2137, 233, 273, 255, 4078, -279, - -194, -274, 101, 45, -225, -716, -2522, -188, - 10, -590, -745, 894, 1976, -48, 2302, -4, - -4691, -67, -1325, -506, 605, -297, 317, -271, - -176, 1706, 541, 1, 31, -580, 103, 148, - -122, -141, -849, 76, -3094, -67, 2775, -38, - -598, -314, 793, 40, 324, 1474, 1986, 1505, - 832, -504, 739, -1233, 1201, 695, -1363, 670, - 805, 696, -137, -4977, -306, 137, -885, 455, - 1021, 600, -1711, 536, 235, -149, 31, -5, - -3747, -405, 394, 140, 102, -1576, 190, 408, - 663, -2075, -747, 466, 631, 807, 1867, -655, - 102, 341, 435, 551, 500, 426, -650, -88, - -26, 2672, -1791, 34, -86, 2963, -3330, -793, - -307, 277, -584, -240, -141, 258, 708, -242, - -499, 808, -104, -2061, -518, 684, 889, 406, - 259, 211, 462, 428, -2597, -1147, 1729, 683, - -2173, -167, 392, 440, 599, -815, -624, -368, - -2962, -172, 845, 423, 362, 711, 2131, -3899, - 84, 147, 826, -399, -637, 1132, 108, -480, - 230, 265, -423, 48, 11, 239, -599, -281, - 10, 541, -397, 142, -4322, 1172, -257, -101, - 292, -321, -401, 60, -309, 468, 267, 611, - 438, -638, 2194, 346, 1421, -1192, -3109, -170, - -3336, -49, -69, -75, 184, 3094, 591, 82, - -373, 140, -22, 848, 124, 589, 157, -4, - 260, -177, 147, 73, -284, 6253, 111, 302, - -74, 356, 381, -547, -16, -275, -500, 93, - 344, -346, -2837, 364, -43, -592, 1741, -702, - -2247, 848, -203, 168, 758, -849, -2454, 562, - 1104, -169, 463, -398, -2759, -299, -903, 647, - -62, -124, 301, 337, -201, 463, -86, -139, - -2189, -2424, -942, -376, -2043, -80, -1791, -1580, - 513, 29, -1115, -582, 1214, -642, 355, 240, - 285, 1759, 1209, 862, 1707, 3353, -223, 245, - -515, -928, 794, -190, -282, 1097, -32, 1675, - 857, -730, -15, 102, 356, -309, 3867, 24, - 93, 899, -608, -497, -215, -2244, 735, -194, - 102, -51, -1939, 846, 74, -116, 7, 1981, - 512, 233, 574, -2508, 83, 1966, -251, -96, - 532, 97, 897, -1120, 390, -3192, -652, 2045, - 193, -880, -398, -148, 548, -281, -19, -987, - 467, -326, 2777, 195, 1560, 1034, -828, 102, - -1531, 1292, -126, 539, -247, 36, 55, -2487, - -297, -362, 482, -2241, -1021, -1535, -244, 38, - -3416, 141, 3408, 35, -67, 95, 333, -427, - -235, -128, 304, -548, 337, -349, -330, 23, - -450, 1657, 327, -3087, 695, -273, -1090, 1262, - -111, -868, 1516, 269, 119, 192, 14, 200, - 141, -395, 7145, 48, 334, 143, -139, 154, - -102, -312, -2, 283, 238, -30, 626, 1328, - 242, -416, 442, -3050, 1388, -100, 1215, 817, -}; - -static const int16_t cb2224sm1[] = { - 8192, -13, 346, -52, 5, 131, -294, -167, - -65, -347, -438, -559, 57, -86, -223, -224, - -251, 629, -58, 5249, 127, -464, 644, 210, - -154, -480, 165, 211, 13, 318, 152, -173, - 5451, 235, 170, -100, -6, -460, -249, 390, - 54, 993, -1637, -288, -978, -197, 234, -2877, - -570, -151, -82, 772, 199, -385, -1899, 345, - -25, 527, -477, -2918, 385, 2784, 78, -524, - -759, 795, 433, 511, 856, -275, 511, 136, - -444, 151, 233, 208, -589, -375, 282, 2886, - 30, -2749, -930, 1079, 86, -2285, 980, -229, - -1369, 93, -80, 2314, -170, 1224, 397, 405, - 463, 1014, -377, -90, -269, -82, -376, -773, - 684, -94, -2893, -323, -644, -849, -1892, -2244, - 417, 2165, -164, 221, 454, -2337, 142, 99, - 418, 486, -49, 97, 138, 2221, -2301, -156, - -578, 3963, 196, 140, -374, 180, 451, 354, - -952, 946, -479, -874, -159, 145, 290, 240, - -240, -233, -418, 226, 2878, -571, -2491, 741, - -1438, 557, 197, -370, -4720, 379, 32, 821, - 39, -545, -141, -1507, 192, -1150, 905, -1095, - -5028, -169, 533, -23, 371, 162, -1198, 465, - -369, -14, -861, -656, -701, -296, 31, 450, - -387, 3060, -696, 597, 14, -1019, -2741, -208, - -1186, -338, 712, -64, -344, 41, 327, 9, - 576, -349, -2808, 2428, 433, -566, 908, -108, - -145, -1011, 201, -3042, -327, 210, -368, 230, - -310, -400, 12, -1034, 1734, 992, 1842, 1022, - 2162, 588, 366, 154, -3078, -587, 1096, 215, - -1072, -784, 472, -1089, 94, 487, 18, 72, - 34, -15, -374, -607, 316, 830, -146, 4377, - -301, 390, 838, 121, -110, -143, -93, 2988, - 2914, -352, -353, -744, -115, 99, 495, -343, - 309, 1261, -519, 101, -2662, -44, -3139, -491, - 1142, -323, -50, 776, 86, 187, 480, 271, - -167, 1, -267, -99, 991, 2492, -152, 2423, - -225, 34, 576, -1486, -236, -375, 160, -176, - -145, 2525, -131, 194, 317, 1215, 1553, 295, - -1408, 130, 2279, -1185, 2671, -137, -324, -23, - 26, -779, -431, -4, 488, -186, 174, -119, - 3062, -149, -168, 191, 169, 1124, 301, 1471, - -409, -999, -166, 2174, -1405, 992, -179, -2606, - -71, -3151, 92, -976, 3091, -322, 310, -374, - -779, 599, -55, 425, -697, 63, 27, -38, - 86, 170, -11, -616, -97, 525, 78, 14, - 684, -5556, -308, -444, 266, -396, -1665, 86, - -722, -1087, -921, -525, 3, -439, -1600, -37, - 2038, -2672, -187, 361, -8192, 425, 365, 54, - 343, -703, 253, 284, -57, -327, -154, 392, - 99, -181, 213, 395, -2412, -303, 182, 82, - 2311, 45, 1801, -209, -988, 42, -1430, 38, - -721, 118, -163, 1279, 2184, -18, 2851, 274, - -363, 297, 150, -220, 3653, 3135, -381, 335, - 254, 378, -52, 52, 328, -383, -61, -802, - -409, -49, 49, -8192, 362, -48, -430, -54, - 255, 243, -525, 14, 152, 10, -392, -301, - -594, -539, 1200, 626, -2979, 233, -1504, 664, - -728, -1293, -491, 394, 1317, 298, 169, 214, - -429, -1083, 42, 389, 4751, 510, 299, -542, - 456, -852, 30, 208, -63, -131, 72, -425, - 73, 213, -287, -277, 43, 128, 5528, 165, - -316, -135, -576, -583, 217, -1298, 47, 134, - 103, -1894, 148, 3406, 880, 964, -697, -94, - -1626, 223, 1256, -514, 2079, -529, 1917, -1452, - -616, -605, 385, -963, 395, 105, -154, -1627, - -214, 40, 969, -708, -1492, -824, 2457, 275, - 404, 876, -781, -1029, 34, 72, 229, -137, - 264, -387, 305, -57, 2908, -143, -249, -2473, - 202, -1467, -364, 2094, -521, -70, 260, 132, - 465, 71, 982, -36, 1792, 306, 2907, -55, - 254, 421, 231, 140, 1727, 474, 761, 3153, - -18, -356, 414, 2218, 564, -247, -510, 67, - 2390, 2531, 240, 117, -487, -310, 261, 222, - -286, -861, -2180, 480, -75, 4769, -407, 248, - 227, -224, 302, 901, -1200, -728, 1025, 734, - -336, 115, -1726, -179, 131, 43, -357, 364, - -681, 283, -189, 715, -2793, -692, 1367, 916, - 28, -500, 3094, -543, -627, -709, -506, -1094, - 34, -2464, 434, 257, 357, 10, -390, 3206, - 3483, 137, 147, 180, 231, -260, -707, -818, - 476, -528, 656, 824, -8, 3073, 362, -3034, - -199, 47, 694, -252, 819, -147, -479, -32, - 530, -141, -91, 251, -154, 376, -603, 2305, - -2853, -622, 316, -680, 402, -819, 323, 471, - -47, 1772, 1507, -1052, -685, 18, -2509, -418, - 377, -31, -412, 105, -906, -267, -2806, -189, - -97, 198, -802, -82, -658, -2980, 795, -447, - 646, 1037, 486, -689, -2654, 55, -3534, 540, - -68, 502, -90, 277, -87, -497, 24, -246, - 400, 392, 348, 76, -345, -231, -71, 155, - -7, -226, 6553, 371, 261, -290, 88, -44, - 311, 470, -5, 182, -105, 56, -324, 267, - 241, 327, 966, 218, -4695, -968, 27, -352, - -315, 202, -204, 435, 360, -539, -375, -527, - -1157, 1010, -241, 4171, -292, 66, 2343, 310, - -682, 595, 3040, 539, -118, -573, -128, 952, - -172, -547, -285, -1, 345, -5701, 345, -153, - 77, 349, -225, -364, -655, -270, -716, -825, - 27, 55, 2179, -154, -275, 359, -501, -992, - -665, 1538, -218, -1159, 2176, -845, -3018, 105, - -459, -3146, 67, -197, -293, 539, 115, -74, - 119, -158, -89, 1449, -3006, 104, 651, 886, - -310, -242, 1219, 1805, 176, 2235, 579, 294, - 634, 1345, -1, -454, 755, -1030, 1760, -2404, - -406, 894, 614, -74, 113, -1325, 1843, -392, - -3239, 2440, -54, 222, 1349, -695, -1009, 434, - -468, -509, -280, 462, 228, 573, 213, 55, - 325, 557, 100, -721, -674, 600, 795, 1567, - 407, 3273, -58, -1330, 349, -181, 417, -503, - 911, 350, -681, -4502, -127, -26, 330, 618, - 241, -147, 284, -226, -127, -2692, 484, -146, - -18, -416, 755, 85, -3119, -404, 0, -478, -}; - -static const int16_t cb4432l0[] = { - -3764, -227, 184, -258, -1713, 122, 410, -32, - -244, -1337, -328, -20, -236, -359, -13, -52, - -75, -260, 426, -96, -37, -38, 117, -938, - 487, 60, 286, 571, 368, -551, 198, -102, - 15, -11, 4535, -127, -241, 114, -77, -316, - 302, 195, -149, -73, 357, -128, -23, 34, - 319, -97, 189, 5918, -20, -134, -47, -249, - 7, 3, 116, 7, 48, 47, 92, 19, - 14, 31, -388, -329, -1878, -944, 958, 632, - 1973, 182, -130, -193, 2309, -868, 63, 260, - -12, -89, -88, -208, 127, -168, 237, 74, - 1153, 925, 2292, 2992, -35, 204, 766, -930, - -87, 341, -101, 501, 35, -182, 112, 91, - -28, 79, 193, -73, -71, 52, 82, -427, - -147, -69, 4722, 468, -187, 98, -295, 292, - -991, 43, 98, 225, -555, -595, -66, -181, - 91, -152, -3, 89, -219, 356, -375, -114, - -1546, -620, 648, 1946, 39, -608, -942, 103, - 179, 170, -2350, 157, 1132, -944, -283, 64, - -393, 15, -90, 761, -185, 644, -360, 5, - -5212, 106, -136, -40, -159, -40, -120, -43, - -8, -195, 208, -179, -295, -63, 19, 32, - -104, -23, 132, 660, -460, 237, 523, -676, - -378, -81, -184, 2718, 64, 531, 2119, -1564, - 614, 933, 6, 65, -50, 55, 243, -539, - 1168, 953, -283, 45, 476, -346, 2285, 1892, - 615, -521, 23, -2079, 57, -11, 208, 1029, - 371, 28, 170, -63, -167, 184, -217, 76, - -320, -2747, 542, -2098, -407, -10, -876, -1477, - -306, 565, 57, -49, -111, 185, -250, 120, - -186, 214, -520, 463, 792, -2420, 2760, -383, - -783, -1097, -441, -535, 1070, 78, 96, 122, - -193, 516, 114, 100, -413, 100, -23, -153, - 1267, -4210, -742, 228, 659, 399, -169, 412, - -81, 1056, 4, -254, 173, 109, -218, 196, - 64, 26, -113, -60, -8, 15, 5497, -76, - 169, -294, -394, 596, 379, 12, -64, -203, - -138, 41, -249, -53, -44, -19, 55, -34, - 99, 36, -70, 8, 46, 2787, 842, 1917, - -693, -424, 151, 464, -1162, 1027, 148, -1027, - -173, 328, 23, 792, -184, 395, -684, 229, - -139, -7, 2788, 404, 43, -1508, -590, 6, - -184, 904, 475, -37, 276, -361, 1924, -188, - -113, -1334, -176, 11, -34, -70, -68, 95, - -433, 225, 437, -451, 471, -272, -385, 2793, - -2685, 544, 881, 409, -789, 700, -5, -144, - 66, -17, 504, -397, 264, 74, -81, -1803, - 444, -573, 633, -391, -3339, 192, 484, 1126, - -306, 153, 303, 61, -253, -255, -57, -277, - -88, -100, 32, 79, -1320, -857, 3080, 1178, - 323, 353, -149, 1316, -399, 236, -129, 231, - 323, 696, 59, 1217, -567, -268, 642, 384, - -327, -47, 466, 1530, 1092, -1176, 612, 257, - -143, -270, 487, -62, 332, 1089, 961, -706, - 938, 78, 97, -2805, -1088, -871, -273, 87, - -345, 148, 113, 167, 97, 31, 68, -47, - -53, 53, 29, -5723, -53, -12, 241, 92, - 131, 139, 48, 102, -26, -47, 664, -580, - -7, 1287, 2531, 1061, -710, 24, 1389, -1742, - 254, -1147, 539, -150, -24, 495, -204, -171, - 955, 202, -111, 147, -1458, -3973, 421, -416, - -544, 392, 1419, -178, -168, -53, 50, -537, - -7, -346, -289, -52, -38, -259, -115, -136, - -138, -89, -205, -661, -4429, -110, 380, -721, - -180, 127, -1371, -78, 276, 319, 229, -934, - 267, -353, 44, 65, 449, -32, 159, -11, - -22, -571, 100, -676, 2892, -2740, 907, 511, - 248, 441, -62, -517, -347, -235, 319, -8, - -140, 309, 258, -106, 215, 1, -3252, 426, - 455, -2213, 1031, 430, 746, 367, 602, 187, - -147, -200, 97, 555, -107, -249, -71, 101, - 59, -94, -64, -33, 221, 184, -791, 671, - -191, 284, -1311, 402, -29, 250, -190, -503, - 38, 106, 586, 4767, 526, 147, -182, 249, - 146, 17, 293, -1095, 1079, -161, 141, -2, - 681, -275, -171, -4504, 61, -105, -306, -66, - 229, 20, -102, -93, 334, -189, 5, -6, - 417, 2551, -63, -852, 1608, 1820, 670, 1592, - 102, 203, 147, -767, -147, 310, -718, 175, - 551, -98, -202, 309, 70, 81, -55, 1518, - 222, 338, -356, 349, 97, 86, 495, -233, - -121, 2936, 200, 935, -381, 2474, 53, 494, - 248, -139, -45, 100, -1287, -181, -370, 311, - 287, 3016, -96, -128, 2146, 567, -383, -551, - -96, 144, 495, 428, -32, 137, 27, -272, - -149, 9, -61, 177, -5236, 91, -837, 611, - -279, -74, 652, 14, -178, -82, -89, 347, - -245, 647, -62, 49, -215, 29, -55, -27, - 178, 79, -19, -59, 177, -152, 0, 189, - -10, 128, -115, 33, 61, -106, 56, -13, - 135, 116, -5772, 157, 43, 26, -11, 102, - -4, -52, 208, -186, 198, 99, 81, -29, - -103, 193, -35, -84, -4, -111, -5251, 84, - 71, -85, -77, 55, 234, 38, 0, -35, - 60, 5875, 98, 36, -219, -17, -419, -136, - 47, 34, 55, -21, -17, -1, 72, 94, - 52, -3, -703, -1437, -518, 557, 121, 356, - -345, -717, -438, -279, 13, 70, -95, -2, - -4170, 40, 136, 17, -153, 8, -149, -27, - -559, 268, -237, -82, -220, -921, -588, -150, - 3481, -1906, 647, 675, -455, 598, -386, -52, - -7, 222, -201, 90, 54, 75, -283, 118, - -375, 5768, 20, -126, -141, -99, 64, 116, - 16, -58, 0, -31, -15, 250, -104, -30, - -144, 115, 12, 117, -482, -1709, -436, 122, - -246, -7, 271, 1961, 154, 149, -86, 147, - 258, 531, 1760, 914, -1196, -1800, 812, -621, - 125, -161, 1361, 50, -651, -1307, 360, -785, - 205, -156, 294, 21, -3484, -18, -79, -266, - 770, 307, 29, -765, -250, 183, 55, 131, - 1452, 260, 224, 221, -347, 360, -352, -2188, - -664, -503, 313, 406, -251, 3268, 210, -46, - 129, -276, 343, -143, 104, -55, 461, 17, - -576, -287, -289, 33, -2500, -85, -428, -1137, - 918, -245, -490, -260, -270, -133, -591, 199, - -294, 2784, 102, 19, -109, -745, 91, -524, - -44, 28, 252, -511, -80, -146, 271, 519, - -216, -2280, -411, 3699, -368, -538, 427, -158, - 114, -50, -589, -340, -180, 703, -186, 487, - -649, 668, -916, -436, -3684, -1016, 877, -65, - -153, -62, -148, -17, -106, 142, -73, -1, - -68, 567, -658, 815, 2270, -563, -519, -226, - -223, -282, 584, 240, -1522, -1935, 1169, 880, - 127, -1276, -127, 399, 63, 25, -1297, 2131, - 592, 1652, 2609, 69, -581, -179, 947, 597, - 150, 35, 0, -255, -232, -728, 239, 91, - 130, -234, 231, 56, -2181, 1774, -2196, 1633, - -1065, -662, 777, -175, -128, 267, -7, 51, - 27, -133, 95, -500, 188, -167, 94, -176, - -29, -65, -161, -141, -694, -968, 594, -269, - -422, -472, -731, 1210, -816, 2142, -1321, -1746, - -149, -983, 1310, -839, 762, 284, 99, -31, - -1169, -84, -1119, -55, -720, -944, -1115, -271, - -1032, 1064, 187, -1013, 2987, 26, -209, 516, - -8, 107, -24, 188, 278, -53, 624, 460, - -275, -1881, -2001, 851, -1740, -407, 1643, -352, - -17, -528, -538, -175, 179, 416, -297, 54, - 132, -491, -76, 34, -440, 175, 2065, -2006, - -164, 38, -403, 902, -129, 215, 1545, -414, - -1183, -532, 578, 248, -308, 189, -563, -345, - -949, -279, 1693, -959, 101, 783, 9, 1641, - 1494, 167, -294, -538, 951, 115, 590, 105, - -847, -1003, 464, -368, -1268, 641, 254, 243, - 488, 2636, -1209, -272, 437, 445, 781, -463, - -415, 538, -811, 588, 1083, 206, -547, 171, - -585, -744, 343, -604, 395, -76, 910, -523, - -108, -449, 625, -325, -1079, 273, -1473, -1096, - -137, -565, 2077, -623, 214, -342, -273, 769, - 1137, -879, -731, 56, -1098, 211, 822, 579, - -839, 164, -600, -80, 61, 316, 644, 1445, - 891, -1796, -1798, -162, -1631, -492, -626, 593, - 544, 66, 63, -857, -1273, 406, 1665, 899, - -467, 87, -117, -469, 126, 30, -931, 1446, - -190, 388, -1608, -316, -2199, -127, 484, -51, - 56, -524, 1524, -103, 1231, -740, 717, -861, - 823, -665, -1790, 411, -690, 303, -1615, 63, - -232, 19, 1090, -96, 137, 80, -1027, 581, - -61, 672, 133, 444, -767, 766, -42, -3174, - -270, -23, -126, -1111, 67, -1367, 4, 315, - -53, -90, -165, 48, -1657, -117, 392, 356, - 792, -610, -618, -219, 446, 102, 374, 207, - 1026, 2480, -461, -782, 1161, -1351, 1032, 486, - -308, 290, -272, 899, 1912, 36, -624, 286, - -428, -623, -665, 12, -621, -1985, -34, 468, - 318, -467, 127, -972, -39, -663, 2307, -26, - 406, -468, -657, -1404, -342, 2356, -395, -1422, - -1243, 465, 90, -665, -280, -290, -21, -1752, - 280, 271, 395, 240, -402, 55, 1077, 148, - -309, 1818, 483, -1293, 43, 261, 566, -131, - 947, -815, -872, -1021, -1001, -395, 263, -555, - 78, -2193, -360, -76, -1029, -493, -464, 1339, - -53, 750, -671, -1349, 133, -70, 114, 501, - 766, -816, 703, -992, -122, -520, -1323, -2539, - -365, -35, -555, -888, 1515, -191, 1322, 1633, - -674, 451, -1246, 270, -868, 703, -394, 106, - -779, 754, 650, 1066, -417, -1305, 149, -165, -}; - -static const int16_t cb4432l1[] = { - -3867, -448, 2202, 129, -100, 393, 37, -267, - -156, 23, -274, 222, 33, -191, 104, -140, - -50, -28, -148, -181, -22, 6, 489, 993, - -2764, 1191, -773, 781, -460, 843, -77, -1417, - 390, 124, -203, 205, 662, -16, 569, -963, - 609, -155, 64, -293, 2649, -2533, 70, -472, - -482, -1732, 235, -5, -485, 116, -177, -104, - 314, -355, 118, 25, 921, 285, 130, -94, - 77, 121, 1068, -435, 1407, 447, -427, -1096, - -757, 258, 19, 3236, 702, 362, -928, -348, - -150, -784, -687, -388, -176, -38, 16, -14, - 1017, 879, 935, 1280, 1014, -85, -256, -103, - -3384, -928, -200, -406, -175, 304, -54, 195, - -78, 676, -356, -167, -165, -56, -3133, 156, - -171, -684, -698, -135, 230, -30, 32, 542, - 1959, -124, -76, 162, 182, -174, 1011, -97, - 678, 10, 188, 30, 1086, -262, -157, 250, - 241, 233, -584, 3276, 2126, -50, -207, 637, - -440, 331, -434, 251, -267, 269, -392, 68, - -244, 8, 928, 827, -1096, -309, -356, -375, - -3204, 422, 695, 2, 240, 595, 641, 582, - 342, 42, 7, 539, -64, -116, 82, 16, - 26, -136, -122, -114, -5814, 22, -272, 10, - 113, 186, -422, -95, 309, 308, -118, -208, - 52, -175, 12, -106, -6, 20, 58, 6053, - -101, -20, 10, 70, 189, 57, -11, 210, - 83, 239, -6, -79, -233, -59, 31, -30, - -62, 64, -38, 25, -78, -202, -215, -115, - 1477, 255, 101, -2575, 186, 3140, -46, -45, - 53, -183, -89, -412, 183, -222, 50, -237, - 96, 35, 1684, -521, -169, -436, -295, 1390, - 261, 27, 163, 352, 68, -3677, 12, 310, - -599, 331, 138, -333, -269, -130, -44, -14, - 265, -626, 258, -59, 31, -17, 222, -10, - -364, 280, -183, -235, -217, 73, -67, 114, - 196, -5132, 269, 159, -6, -36, -248, 274, - -328, 2712, -393, 2763, 507, -110, -166, -84, - -72, -1111, -19, 370, 25, 5, 156, -32, - 237, -57, -106, -22, 370, -229, 1099, 4297, - 152, 72, -56, 347, 64, -501, -57, 178, - 175, -14, -84, -626, 555, 155, 20, -75, - 20, -33, -254, -125, -9, 150, 91, -7, - -45, 239, -109, 72, -66, -172, -211, 6063, - -205, 171, -75, 50, -75, 22, 109, 21, - -58, 58, -105, -432, 310, 3782, -18, -1071, - 19, 20, 1455, 337, -257, -288, -52, 519, - 43, 80, -175, -218, 9, 176, -28, -418, - 200, -514, 351, 119, -5920, -96, -33, -289, - 74, 26, 120, -37, 113, 47, -145, -17, - 334, 46, 47, 19, 274, 172, 159, -404, - 3151, -408, -559, 987, -178, 253, -90, -498, - 1454, 1183, 392, 762, 220, -1207, -220, -69, - -85, 22, 1644, 1858, 725, 1084, 0, -257, - 290, 1712, -151, -188, -390, 638, -327, -2185, - -322, -1116, -150, 120, -140, 198, 162, -83, - 1321, 232, 242, -52, -456, 778, -288, 65, - 2431, 37, 85, -489, 862, 2776, 260, -72, - 792, 100, 17, -210, 588, 49, 600, 246, - -258, 128, -51, -492, -395, -489, 50, -5308, - -67, 314, 124, 46, -188, -64, -101, 51, - -535, 108, 56, -4, -191, -923, 485, 578, - 1320, 228, -535, 310, 227, 395, -1441, 2660, - 226, -392, 221, -686, 1749, -175, -904, -571, - -129, 154, 2622, 609, -247, -240, -893, 98, - 291, -2277, 411, 260, -160, 2061, -203, -437, - 359, 21, -101, 19, 49, 15, -98, 82, - 3, -555, 164, -152, -58, 38, 175, -439, - -37, 68, -21, -181, -5556, -27, 8, 48, - 21, -151, 381, 3, -152, -74, 202, -29, - 1863, 1713, -922, -1976, 551, -1522, 525, -116, - 146, -1730, -238, -72, -183, 126, 234, -240, - 82, 138, -60, -131, -2226, 226, -702, 183, - -81, 462, -2851, -1419, -1005, 124, -81, -252, - -65, 147, -58, -179, 306, 154, 122, -69, - 69, 11, 115, 296, 3340, -501, -2580, -804, - 9, 591, -86, 88, 127, 588, 183, 48, - 79, -38, -199, 63, -140, 29, 88, -28, - 259, 69, 1743, -531, 110, -18, 776, -18, - -177, 112, 36, -243, -208, 528, -47, 4709, - 107, -125, 140, -1, 22, 15, 416, -194, - -267, -49, 43, -3, -308, 214, -128, 140, - 5372, -123, 70, 275, 210, 182, -147, -131, - -84, 69, 116, 29, -401, -162, -236, -173, - 378, 45, -12, -77, -6209, -103, 126, 54, - -19, -20, 43, 64, 92, -8, -12, 118, - -123, 58, -3628, -414, -2147, 76, 95, -99, - 357, -10, 278, 4, -608, 504, 105, -72, - -109, -92, -55, 367, -167, 40, -34, 76, - 220, 3434, -366, 191, 248, 29, 187, -177, - 155, -348, -341, -2466, 272, -136, 510, 139, - 81, 184, 33, -299, 92, -44, -402, -583, - -725, -400, -159, 751, -225, 377, -160, 1556, - -2652, 685, -1077, 1276, 332, -257, -1449, -282, - -231, -145, 58, 173, 421, 271, 401, -186, - 79, -258, 127, 252, 214, 96, 157, 195, - 205, 118, -4771, -95, -164, 217, 477, -51, - -4, 8, 1450, -51, -52, 952, 675, 929, - -273, 475, 9, 282, -249, 236, 746, -1407, - -272, 1845, 692, -105, 2690, 168, 1, -1, - 157, -599, 305, 255, -2252, 45, -199, 119, - -3489, -161, 6, -263, -259, 338, -251, 61, - 153, -124, 432, -7, 131, 5, 305, -322, - -3283, -32, -336, -273, 2243, 863, -1, 681, - -365, -246, -152, 375, -133, -15, -208, -104, - 89, 128, -135, 44, -255, 549, -2751, -48, - 270, -2584, -549, -631, 445, 182, -198, 743, - -215, -60, -400, 1383, 167, -65, 250, 146, - 185, 22, -484, -161, 86, 1758, 964, 404, - -2574, 1026, 6, -516, -724, 315, -1891, 311, - 2, 339, -39, 324, 299, -497, -12, 179, - -1242, 364, -185, -197, -1474, 232, -490, 4042, - -105, 887, 31, 539, 235, 75, -112, -200, - -31, 74, -76, -16, -20, 38, -159, -143, - 114, -77, -110, 28, -18, -84, -27, -53, - -82, -224, 75, 0, -46, -64, 44, -112, - 84, -85, -6030, -24, 661, -474, -178, 8, - -1023, -396, 199, -19, -50, -93, 385, 209, - -1227, 2492, 2163, 986, -1359, 399, 848, 681, - -829, 211, 696, -599, -1398, 1951, -113, 374, - -17, -1113, -1708, 1294, 666, 1774, 623, 259, - 105, 961, -87, 43, -463, 65, 155, -26, - -31, -1477, -508, 1091, -1463, -524, -1853, 1354, - 434, 86, 893, -871, 151, -1887, 205, 423, - 857, -55, -11, -39, 341, 61, 1158, 2650, - 899, -2491, -593, -843, -1399, -15, -713, -171, - -195, -523, -46, 243, 117, 241, -8, 140, - -149, -191, 70, 134, -1158, 1933, 1135, -2284, - -1049, 1717, 378, -155, -37, 171, -692, -280, - 918, -786, -123, 558, 571, 39, -315, 62, - 27, 59, 708, -134, -200, -168, -134, 148, - -142, 25, 164, -282, 284, -95, -35, 376, - 165, 367, -335, 271, 249, -4520, 176, -36, - -216, -1303, 375, 92, 602, -889, -390, 284, - 78, -1318, 1259, 1865, 1498, 2063, -234, -840, - -391, 88, 168, -235, -74, 31, -239, 1221, - 71, -1637, 1513, 68, 2201, 1513, -1099, -622, - 426, 343, -330, -648, 381, -156, 27, -31, - -92, 133, 210, 103, -155, 2061, -366, -1173, - -31, -274, -713, -471, 509, 1044, 208, 403, - 486, -66, -521, -1883, -180, -537, 1283, -98, - -1464, -456, 508, -619, -546, 685, 944, -85, - 311, 1172, -194, 1406, -99, -827, 1506, 396, - 196, -1534, -1181, 1588, 1250, 47, 1034, -171, - -1247, -98, -120, 1181, -2195, -384, 945, 627, - 26, -248, 1372, -671, 214, -649, -17, -44, - -500, -559, 577, -601, 32, 421, 531, 344, - -1233, 145, 348, 614, -560, -244, -357, -202, - 814, -494, -2320, 308, -2277, -481, -518, -431, - -851, 43, -204, -26, -742, 1083, -130, 2002, - 1642, -1156, 1746, -529, 937, -544, 416, -741, - 763, -232, 509, 243, -458, 78, -130, 143, - -123, 71, -666, -105, 31, -1061, 441, -48, - 411, -1547, 155, -730, 439, 1624, 873, -611, - -470, 2348, -157, 1184, 678, -174, 542, -95, - -12, -405, 237, 322, -1194, 1903, 1496, 357, - -34, -661, -1024, 2236, 860, -256, 617, 756, - -485, -273, -589, 536, 214, -286, 782, 418, - 346, -462, 443, 1056, -914, -304, -564, -332, - 1823, 2079, 93, -975, -891, -1089, -720, -1127, - 702, 300, 787, 374, -78, 1070, 691, 1339, - -797, 57, 482, 432, 748, 1538, 673, 1885, - -504, 1913, -190, -135, 881, -139, 84, 379, - -176, -129, -331, -34, -690, 282, -563, 51, - 71, -714, -103, 1074, -651, -582, 1388, -320, - -1115, 1547, -1088, -65, -2634, -201, -653, 116, - -238, -218, 476, 1417, 1671, 1135, -1025, 614, - -662, 127, 863, -117, 726, -971, 1382, -286, - 465, 1195, -715, 862, -1256, 105, 37, -1190, - -442, -1777, 50, 162, 1577, 580, 762, 253, - 92, -308, -1238, -161, 295, -150, 1733, 1831, - -527, -527, -28, 70, -359, -1590, 860, -221, - 47, -1201, -254, 39, 780, -326, 1097, -1019, - 834, 362, 357, 41, 693, -1099, -2687, 614, - 270, -128, -322, -1149, 631, -46, -343, 1495, - -896, -864, 1545, 200, -922, -1133, -637, -1231, - 484, -796, -743, -371, 999, 1300, 173, -19, -}; - -static const int16_t cb4432s0[] = { - -2558, 2751, -440, 1200, 1067, -725, -492, 588, - 234, -209, -108, -230, 223, -231, -235, -132, - -51, 88, -290, -214, -99, -60, 175, 2546, - -991, 907, 446, 635, 284, 707, 238, 220, - -308, 259, 8, -435, -2207, -1487, -1579, 46, - 285, -249, 154, -370, 37, 42, 1524, -1853, - 1393, 1204, 126, 1751, 82, 136, 363, -2411, - -782, -128, -818, -232, 765, -173, -127, 732, - 260, -101, 868, -249, 290, 32, 645, 55, - -1742, -1077, 392, -568, 629, -920, -243, 791, - -604, -363, 117, -1360, -15, -245, -3655, 54, - -297, 10, 124, 11, -1114, -567, 3882, -2042, - -1120, -42, -114, -914, 419, 307, 44, 277, - -101, 429, 170, 187, -528, -705, 348, -19, - 180, -76, 91, -1861, -181, -171, 804, -730, - 222, -184, 349, 191, -125, 14, 4270, -467, - -272, 29, -216, 212, 426, -222, 11, -16, - -852, 101, 576, 178, 351, 647, 90, 179, - -681, -187, 77, 4115, -976, -726, 711, 763, - 572, -1166, -46, -445, -103, 135, 294, 300, - 10, 737, 386, -399, -349, -52, 5393, -107, - -32, -229, -154, -181, 82, -68, -13, -77, - 48, 75, 117, -50, 254, 233, 98, 75, - -2218, -2214, 1491, 832, 225, -1057, 267, 539, - 1963, -245, -353, 454, -430, -54, -747, -58, - -438, -90, -64, 277, 214, -105, -47, -1301, - -404, -1179, 682, -4093, 764, -270, -342, -367, - -1378, 6, -83, 429, 398, 61, -149, 180, - 31, 169, -218, 152, -71, -38, 2605, 679, - -175, -533, 1787, 611, 484, -322, 158, -561, - 125, -35, -42, -190, 529, 449, 157, -3105, - 106, 168, -8, -66, -80, 1463, 1136, 4793, - -98, -432, 538, -145, 241, -158, 105, -372, - 39, -160, 92, -223, 81, 245, -142, -162, - -167, -297, -49, -98, 582, -5178, 1130, -271, - 567, -251, 55, 487, -303, 31, -25, 87, - -70, 154, -23, -221, 70, 208, 48, -137, - 46, 59, -9, -1397, -970, 224, 714, 161, - 24, -307, 1295, 1467, -155, -505, -521, -244, - 503, -25, -989, 3664, -148, 12, -135, 218, - -159, -156, -769, -421, 553, 715, 697, -181, - 1426, 425, -39, -103, -4558, 171, 347, 161, - 170, 128, -210, -35, 31, 125, -264, -135, - -100, 2685, -230, 2062, 1618, -99, -874, 926, - 757, 380, 404, -73, 30, 29, 462, 725, - -389, -246, 20, 150, -234, -58, -183, 10, - 156, 482, -232, 124, 115, 180, -615, -395, - 330, -85, -435, 3279, 1493, 686, 1157, 245, - -1067, -1953, 23, 796, -540, 175, 56, -1931, - 89, 705, -342, 551, -1999, 1951, -2305, -497, - -266, 275, -1503, 351, -355, -353, 236, -358, - -271, -40, 136, 217, -13, -45, -2091, 1141, - 730, -1888, 1131, 660, 1271, 439, 2597, 92, - 319, -91, 62, 316, 287, -260, 121, -33, - -117, -22, -79, -170, -164, 1486, 134, -62, - -36, -3367, -235, 1221, 1239, 78, -54, -489, - 268, -560, -774, 851, -973, -62, -174, -138, - -459, 390, -22, -42, 83, 1339, 1307, 462, - -3768, 511, 300, -525, -787, -89, 675, -2074, - 37, -48, 252, 598, -332, 67, -187, 2, - -106, -35, -148, -186, -542, 799, 2363, -155, - -665, -2867, -209, -200, -80, 1682, 1082, 2, - 516, -481, 276, -1, -220, 54, -12, 259, - 161, -148, 566, -1489, -731, 1262, 499, -816, - 115, 4057, -71, 701, 39, -132, -223, -16, - 229, -2, -40, -61, 234, 405, 108, 304, - -62, -396, 1369, -1438, -2045, 1954, 759, 969, - -166, -235, -115, -68, 1923, 1815, -776, -855, - 34, -63, 17, 87, 223, -145, -130, -16, - -313, -1704, -458, -332, 420, 1332, 676, 878, - -3847, -360, 427, 537, 651, -167, -451, -197, - 277, 136, -201, 517, 10, -156, 35, -927, - 1250, -173, 1004, -169, 322, -140, -559, -4656, - -343, -264, -61, -12, 195, -10, -123, -23, - -20, -6, -367, -102, -215, 41, 838, 1513, - 552, -1609, -753, -763, -656, -633, 14, 35, - 141, 117, -121, 857, -1494, 578, 2546, 1034, - -676, 571, 817, -218, -111, 1424, -51, 878, - -2860, -257, 104, -526, 782, 708, 2350, -500, - -342, 219, -406, 836, -117, 288, -415, 798, - 14, -311, -455, 3, -410, -144, -30, -977, - -145, -2466, -957, 1370, -3201, -327, -85, 149, - -580, 198, 350, 140, -104, 327, -128, -178, - 58, 294, 50, 1814, 581, -909, 287, -267, - -3992, 61, -860, 258, -271, -223, 237, -291, - -3, 66, 110, -620, 319, -62, 177, 364, - 110, -163, -921, -863, 251, 4922, 280, 121, - 128, 209, -126, 578, -56, 41, 124, 350, - 245, -465, -67, 5, 651, 147, 200, 0, - 21, -609, -332, -3, 247, -412, 128, 42, - -1405, -301, -341, -484, -491, -55, 361, -100, - -30, -405, 643, 4249, -31, -91, -10, 6, - 425, -350, -1501, 817, -1348, -201, -345, -3643, - 235, 691, 332, 219, 199, -398, 130, -50, - -190, 89, -23, 100, 1327, -200, 146, 482, - -624, -479, -391, 188, 129, 614, -335, -564, - 1021, -107, -199, 145, 201, 571, 1276, 4253, - 58, 121, 295, 38, 26, 47, -1333, 1138, - 3125, 357, -72, 347, 276, -272, 120, -77, - 535, 247, -71, -2054, -1860, -73, -62, 266, - -30, 183, 17, -46, -7, -140, 997, 526, - -47, -59, 1540, 373, 162, -150, -107, -74, - -278, -37, 4268, -21, -269, 359, 111, -115, - -5, -206, -87, -44, -517, 54, -2859, 189, - -297, -863, -918, -929, -543, 25, -2866, -79, - -1101, -275, -410, -458, -75, -211, -420, 96, - 467, -66, -15, -580, -420, -586, -7, 109, - 236, 227, -488, 106, 258, 76, 78, -8, - -199, -4888, -134, -205, -33, -243, -19, -10, - 157, 129, 120, -928, 604, -345, -47, -430, - -257, 273, 81, 1949, 490, 272, -205, 2460, - -54, 103, -2924, -529, -211, -60, 279, 220, - -57, 342, 209, 984, -1410, -3363, -1028, -1301, - -1293, 227, 1142, -1068, -512, 758, 364, 46, - -358, 16, 257, -158, -253, -182, -2, 181, - 1475, 1574, 215, -968, 246, 369, -273, -717, - 546, 74, -3872, 293, 98, 130, -244, 41, - 143, 699, -56, -126, 67, 54, -2, -878, - 2334, 883, 215, -1979, 246, -759, 499, 248, - 751, -202, 580, -3018, 359, -139, 210, -47, - -168, 89, -659, 259, -54, -40, -490, -169, - -769, 569, -171, 64, -845, 519, 1251, -71, - -459, -4436, 257, -334, -826, -183, 115, -408, - -77, 544, 173, -258, 48, 331, 1735, 1035, - 2793, 1154, -1901, 275, -109, -1185, -403, 1332, - -282, 36, -367, 21, 27, 362, -425, 217, - 150, -304, 192, 53, -1100, 27, 628, 698, - -634, -25, 84, 8, -103, 533, -301, 218, - 4350, 119, -109, 309, 24, -352, -147, -274, - 156, 85, 9, 1706, -854, 2012, -1573, 112, - -673, -1538, -91, 415, -1525, 866, 1493, -621, - -396, 277, -604, -363, 114, -360, -252, -18, - -31, -77, -591, 2483, 535, -1520, -1057, -2189, - -51, 798, 276, -1426, 72, -303, 402, 111, - 327, 272, -8, -216, 189, 1282, 152, -45, - -33, 1524, 2301, -341, 1992, 939, 1678, 1011, - 114, 167, 586, -500, 40, -473, -274, 596, - 1237, -126, 205, 254, -284, -367, -119, 64, - 1915, 437, -585, 1, 402, -271, -984, 530, - 267, 3634, 495, -219, -728, -67, -1340, 983, - 122, 6, 110, -166, 111, 102, -139, -2499, - 753, 1011, 1755, -1252, 872, -510, -1844, 1388, - -782, 287, 461, 36, 77, 437, -361, -216, - -415, 158, -77, -123, 57, -93, 3408, 504, - -942, 434, -648, -251, -420, -387, 1373, -229, - 236, -191, 3, 204, 612, 393, -285, 560, - -164, -199, 303, 146, 93, 1248, 2425, 1001, - 1261, -239, 1085, -1878, -375, -544, -995, -192, - -319, 542, 280, -716, -1323, -67, -34, 252, - -36, 206, -126, -28, 26, -1135, 2799, 527, - -47, -2008, 509, -232, -953, 332, -386, -108, - 290, 507, 578, -809, 375, 850, -1413, 831, - -137, 259, 25, -1075, 407, 1784, -1539, 1658, - 1450, -969, 467, 4, 785, -595, 912, 34, - 91, 286, 1035, -524, 276, -322, 11, 651, - 733, 243, 45, -145, 357, 524, -697, -259, - -757, -1057, 181, 1324, 148, -502, -64, -379, - -746, 1385, 395, 184, -749, -197, -3375, -546, - -4, 532, -270, 687, 501, 285, 401, 431, - -1888, -639, 655, -325, 1896, -1883, 53, -1018, - -1475, 802, -486, -68, 232, 1337, 428, 232, - 1754, -1687, -518, -372, 508, -1269, 327, -900, - -468, 1127, 1397, 1597, 837, 659, -617, 99, - 264, -460, 296, 44, -295, -209, -174, 1105, - 896, 1065, -174, 5, 845, 1311, 1370, -2548, - 351, -660, -24, -1089, -787, -1312, -22, -585, - -197, 749, 293, -112, -169, -23, 3, 1151, - 529, 1173, 224, -1517, 930, -52, 268, -1282, - -559, 466, -528, 1506, -231, -337, 993, -1314, - -250, -3042, 57, 19, 15, 1812, 697, -389, - -201, 647, -723, -1098, -177, -225, -2694, -495, - -431, -238, 388, -1731, 997, 227, -765, -222, - 94, -611, 35, 187, -935, -1470, 1013, 1051, - -378, 311, -710, -566, -532, -369, -1599, 553, - 167, 450, -1068, 2834, -125, 601, -113, -503, - 40, 14, -36, -220, -1543, 867, -612, -1834, - 888, -1791, 1296, -229, -593, -760, -197, 428, - -1290, 892, -62, 1113, -1228, -965, -90, -300, - 288, -133, 779, -1211, -627, 268, 180, 913, - 2230, -413, -146, -217, 170, -1157, -1551, 877, - 75, 1784, -174, -230, -757, 1243, 625, -49, - 114, -218, -409, 195, -1165, 1492, 213, 1100, - -101, -957, 1016, 663, -704, 817, 94, -279, - -256, 469, -75, -123, -2954, 948, -407, 275, -}; - -static const int16_t cb4432s1[] = { - 5416, -223, -123, 156, -33, 185, -144, -108, - -199, -68, -36, 11, 37, 124, -301, 58, - -21, 155, 99, -10, -78, -26, -70, -3160, - -1037, 98, 155, -373, 834, 652, -277, -429, - -529, -103, -358, 187, 1161, -157, 147, -400, - 461, 156, 237, 481, -67, 99, 939, 1179, - -659, 1337, 578, -489, -481, -427, -622, 131, - 1826, -734, -995, -5, -461, 514, -83, -271, - -2928, -86, -382, -205, -133, -386, -195, -67, - 508, 586, 607, -910, -181, -2046, 1212, -179, - 23, 408, -1929, 2044, 2160, -879, 74, 179, - 72, -164, 47, 162, 1497, 826, 2978, -912, - 454, -618, -1907, -501, -494, -299, 96, -138, - -114, -51, -171, 445, 1144, -187, 217, 224, - 402, 13, 42, -58, -1692, 4162, 1272, 970, - -278, 327, 88, -31, -182, 279, -610, 78, - -432, -147, -142, -725, -17, -95, 388, 133, - -61, 28, -1365, 1441, 606, 411, 923, -332, - 1843, 1934, -1451, -514, -283, 768, 940, -428, - 31, 1105, 248, -78, -1477, -367, 404, 68, - -178, 17, 691, -265, -105, 1681, -476, -1307, - -3434, -1700, -524, -871, 472, -171, 237, 104, - -142, -231, -292, -285, 266, -259, -166, -97, - -432, 4003, 1220, -356, 2110, -220, -465, -48, - 117, -178, 290, -21, 205, -19, 321, -343, - -328, -57, 215, -345, 304, 2, 10, -2071, - 185, 433, 212, -1165, 112, 242, -294, -162, - 1107, 1176, -396, 1400, -2600, -434, -640, 457, - 100, -268, 809, 128, -236, -66, -94, -842, - 82, 163, 227, -2641, -485, 291, -326, 42, - 234, -648, 1355, 3016, -1403, -71, 188, 792, - 15, -16, -522, -75, 106, -824, 1133, 947, - 477, -642, -531, -808, 4100, -34, -407, 133, - 33, 15, 63, 72, -223, -15, -491, 38, - 47, 258, -236, 192, 1628, 173, -2116, 687, - 295, -74, -183, 95, 529, 149, -372, 182, - 1317, 21, -1424, -3156, -111, -96, 580, 284, - -274, 41, 145, 1314, 79, 1830, 262, -325, - -16, 169, -245, -2038, 1959, 892, 946, 303, - -171, -432, 883, 34, -238, 2463, -294, 25, - 24, -106, -45, 509, -154, 496, 109, 115, - 169, 702, 396, -97, 657, -251, -112, -114, - -144, -230, 517, -190, 4885, -45, -152, -9, - -170, -2021, 541, -905, -2015, 2588, -936, -20, - -300, 384, 433, -123, 119, -505, -126, 295, - 526, -1352, 450, 142, -126, -115, 1, -140, - -734, 672, -147, -660, -747, 652, 161, -163, - 51, -616, -1974, 1413, -3145, 922, -1289, 215, - 182, -838, -171, 107, -333, 34, 216, -307, - -359, 496, -343, -325, -2552, -1573, 588, -441, - 1296, -3075, 119, -131, 54, 206, 278, 106, - -100, 112, 220, -49, -80, -229, 1051, 3271, - -1300, 324, -31, -1025, 1659, 1526, -161, 669, - -56, 430, 201, -535, -126, -9, -380, 222, - 212, -345, -282, 195, -41, -1235, -593, -593, - 1557, 71, 1023, -831, 545, -875, 161, -772, - 99, -190, 1616, 338, -251, -201, -3104, -774, - 4, -121, 178, -80, 652, -1018, -441, -343, - -236, -240, -244, -26, 2192, 75, -1348, 3771, - -22, -850, -251, 316, 132, -21, 63, 104, - 152, 185, -40, 275, -1356, 482, 3081, 571, - -481, -1387, 815, 1285, -352, -98, -41, 573, - -307, -1879, 427, 196, 169, -26, -232, -98, - -411, -231, -2034, -969, 271, 1421, -1485, -407, - 1404, -343, 861, 888, -11, 202, -245, -397, - 104, 229, 309, -2757, 315, 416, 393, 194, - -176, -663, -166, -229, 244, -152, 183, 24, - -205, 97, -255, -299, 123, -12, 53, 102, - -362, 371, 223, 46, 132, -5177, 157, -92, - -1114, -28, 135, -831, 627, -428, -1116, 421, - 761, 458, 3256, -167, 355, 2045, 113, 234, - -154, 20, -39, 61, -81, 63, 98, -171, - 1727, -1193, 2103, 416, -421, -575, -636, -114, - 700, -260, 1610, -336, 521, 2591, -738, 43, - 103, -63, -335, 168, 110, 41, 1995, 3554, - 1443, -53, -206, 992, 767, -372, 141, -24, - 173, 60, -237, 69, -173, -73, 137, 167, - -164, -159, 312, -151, -78, 619, -192, 689, - -69, -2805, -259, -288, -231, 28, -1682, 2316, - 2298, -336, -131, 59, 542, -218, -281, -214, - -41, 116, 138, 8, -297, -45, -215, -167, - 1587, -1061, -1976, -445, 401, -2392, -42, 581, - -519, -230, 1461, 542, 113, -634, 1776, 332, - 191, 5, 174, 1939, -26, -242, 120, 230, - -986, 3501, -1125, -89, 3, -580, -219, -255, - 37, -119, 94, -17, -297, -176, -434, -234, - 55, -63, -1167, -492, -1753, -3397, 185, -794, - 689, 819, -32, -836, 335, -133, 724, -299, - -318, 424, 558, -654, 119, -447, 140, -100, - 72, -872, -1432, -203, -40, -14, -59, 550, - 85, -53, 5007, 258, 401, -184, -313, -170, - 66, -185, -82, -61, 210, 48, -204, -96, - 130, -562, -1700, -1037, -3926, -884, 1115, -6, - -100, 842, -450, 877, 76, 568, -623, 27, - 73, -195, 328, 41, -24, 124, -77, 1499, - 540, -1064, 4517, -22, -35, 839, -48, 253, - -259, 96, 409, 90, 26, -177, 365, -48, - -324, -26, -23, -83, -77, -80, 1599, 1486, - 266, 659, 236, 231, -16, 359, -163, 455, - -999, -1169, 2453, -599, -945, 4, -2110, -174, - -736, 344, 232, 142, 32, -99, 763, 133, - -325, -56, 1635, -439, 843, 2, -1704, -13, - 771, 3680, -89, 182, 4, 42, 394, 404, - 82, 312, 91, 141, -1577, 1765, 3141, 625, - -271, -2122, 423, 353, 489, 606, -290, -190, - 486, -131, 118, 236, 248, -209, -2, -162, - -95, 95, 170, 278, -2233, 549, 34, -846, - 3595, 445, -400, -65, 131, -14, -16, 611, - -116, 1293, 98, -680, 189, 217, -15, -549, - 131, 8, -768, -1082, 841, -346, 129, -33, - -778, 322, -2508, -2128, -1895, -2021, -27, -42, - -51, -536, 239, -1, 78, 105, 48, 79, - 207, 422, -181, 18, -94, -152, -181, -5012, - -187, -3, -118, -397, -84, -49, 129, -276, - 188, 45, -146, -235, -109, 83, 32, -79, - 2039, -616, 257, -1575, -1756, -2364, 222, 195, - -1138, -290, 58, -641, -252, -11, 402, -31, - -1040, -592, 676, -118, -231, 94, -123, 1642, - 1404, -334, -728, -3425, 382, 111, -194, 677, - 177, -182, 434, 860, -1022, 84, 1214, -733, - 300, -2, -259, 140, 35, 96, 1164, -1476, - -757, -74, 239, -203, 1796, 1207, 1732, -3029, - -610, 658, 490, -465, 136, 56, -614, -612, - -123, 93, -151, 162, 56, 502, 1634, -1825, - 45, 1033, 1554, -2380, 1615, 1317, 786, 387, - -255, -423, -44, -246, -213, -149, 107, -74, - -94, 45, -204, 13, -1959, 936, 2023, 1000, - 1031, 112, 574, 323, 163, 947, -657, 492, - -2624, -44, 739, -305, -31, 247, 270, 213, - -46, -90, 43, -1504, 931, -61, 4045, -863, - 389, -386, -130, -374, -583, -800, -900, 158, - -455, 169, 134, -164, 54, -117, -185, -90, - -203, -41, -811, -2082, 169, 287, -378, -15, - 231, 83, 89, -187, 198, 18, 178, -18, - 527, -40, 94, 54, 79, -4356, 248, 162, - -94, -1431, -31, -2048, 651, 1231, -508, -1089, - -1255, 766, 1673, 357, 13, -813, -2403, 179, - -470, 65, -339, 154, 9, 56, 246, 66, - -2308, 1443, -947, -744, -2473, -1248, -113, 1017, - -608, 149, -182, 41, -524, 16, 285, -268, - -781, -57, -346, 194, 256, -51, 107, -484, - -190, -125, -645, 487, 314, 74, -555, -1012, - 325, 76, 233, -205, -189, -48, -4593, -122, - 10, 121, -91, 108, -49, 254, -1662, 2500, - 87, -1540, -200, 287, -329, -50, -401, 182, - -1300, 689, 915, -224, -768, 471, -339, 133, - 407, -344, 99, 96, 111, 1224, -1431, 2069, - -282, 127, 397, -119, 1332, -1299, 744, -535, - 800, 327, 874, 700, -424, -1596, 1365, -651, - -151, 113, 102, -24, 464, 125, 911, -1583, - -372, 747, 2, 429, -47, -64, 34, 1700, - -741, 343, 728, -226, 1889, 78, -515, 2827, - 77, -66, 108, 515, 90, 2227, -678, 1301, - -974, 122, -983, 2357, 64, -1479, 186, 1436, - -245, 204, 460, 191, -677, -335, -200, -135, - -106, -101, 1112, -2733, -641, 73, 1265, -1281, - -1332, -743, 675, 129, -1144, -1169, 331, -143, - -87, 809, -891, -848, 246, 243, 97, -170, - 36, -1109, 102, 1055, -1395, 1384, 1155, 439, - -1549, -300, -2069, 1014, 187, -782, 980, -971, - -345, -583, -66, -138, -317, -124, 48, -152, - -98, 92, 2446, 128, -1232, 2148, -337, -615, - 467, 1573, -613, 857, 303, 422, -1340, -420, - 305, -626, 94, -496, -386, -129, 243, 27, - -200, -1373, 1468, -2040, 151, -675, 65, 1464, - -432, 545, 269, -510, 584, -1935, 970, -319, - 1465, 490, 263, 555, -256, -49, 315, -242, - -394, -312, -88, 201, -121, -302, 172, 49, - 234, 59, 327, 155, 199, -187, -41, -74, - 52, -31, -59, -5574, -121, 282, 343, -125, - -200, -575, 1328, 155, -1928, 250, 702, 21, - -2718, -153, -102, 2131, 612, 432, -1072, -457, - 222, 427, 144, 149, -433, -1573, 1337, -650, - 176, 13, -1273, 280, -751, -236, 453, 204, - -1595, -2896, -272, 233, 485, 82, -139, -528, - -140, -399, -56, -274, -335, 176, -756, 243, - 2250, -305, 721, 1711, 7, -1230, -1590, -1872, - -137, -714, 263, -1643, 362, -266, -176, 64, - -36, -63, 687, -483, -1488, 709, 929, 1349, - -1245, 645, -1619, 735, -651, 1850, 1031, 159, - -625, 838, 242, -396, -397, -41, 1237, 304, - 81, -94, -736, 578, 1279, 1064, 81, 1900, - -179, 224, 266, -429, 734, 500, 995, -882, - 1563, 1813, -519, 758, 532, -27, 27, 453, -}; - -static const int16_t cb4432m0[] = { - -6132, -262, -273, -1250, -577, 984, -430, -410, - -464, 577, -578, -178, -32, 369, -624, 267, - -68, 474, -480, -225, 166, -409, 437, 4633, - 98, -1560, -464, -869, 103, 193, 461, 72, - 292, -245, 1102, 417, -325, 461, 74, 43, - -120, -213, 333, 160, -468, -212, 31, -81, - 6516, 182, 201, -212, -66, -49, -266, 148, - -108, 98, -46, -11, -59, -20, -20, 2332, - -294, -560, 198, -647, -47, -638, -3877, 11, - 834, 547, 47, 2541, -126, -5, -366, 339, - 3, 2, -66, 60, -526, 914, 321, -658, - 3605, 59, -2392, -655, 384, 775, 366, 327, - 356, 386, 751, -375, 38, -205, -15, -442, - -212, -1241, 1913, -421, -755, 45, -1637, -36, - -2435, 1504, -1248, -763, -664, 133, -123, 814, - 241, -243, -446, 66, -131, -213, 2036, 1294, - -2138, 677, -1042, -771, 294, 371, 474, 85, - 1403, -2618, -478, -537, 275, -826, 349, 84, - 264, -272, -61, -705, 175, -972, 868, 25, - 4183, 881, -639, -833, -757, -1063, -991, -257, - -137, -619, -285, -454, 77, -169, 316, -45, - 4362, -203, -2132, -424, -820, -503, 340, 340, - -612, 648, 2, -342, 81, 630, -1518, 235, - 216, 210, 665, 231, 130, -879, 38, 675, - -136, -48, 540, -234, -152, -169, -5745, -294, - -24, 8, -129, -8, 308, -14, -16, 147, - 62, 70, 248, -2014, 76, -190, -328, -1899, - -353, -140, 836, -365, -112, -3945, -736, 467, - -258, 601, 617, 74, 62, 394, 180, 1151, - -810, 36, 457, 406, 75, -8, -5004, 2335, - -108, -123, 299, -335, 112, -499, -268, -185, - 461, 208, -38, -164, 764, -504, 272, 4853, - 396, 265, -1133, -433, 769, -458, 1005, 645, - 81, -172, 385, -56, -130, -393, 128, -73, - 31, 2038, 127, -436, 123, -2525, 282, -448, - -489, -295, -14, 85, -462, -49, 262, -93, - 238, -148, -3953, -414, -259, 33, -892, 459, - -2186, 60, 444, -610, 844, -486, -299, 219, - -433, 19, -1183, 276, -29, 388, 3327, 102, - -914, -221, 486, -892, -550, 190, 151, -141, - -336, 194, -242, -224, 405, 879, 1600, 349, - -2082, -38, -514, 18, -3574, 161, -142, -38, - -1815, 540, 228, 33, 164, 1074, 4, -278, - -58, 4085, -295, -795, 31, 494, 555, -250, - 22, -202, -312, 92, 109, -238, -448, -622, - -1511, -4346, -417, -706, 37, 1157, -96, -199, - -59, 285, -43, -217, -22, -95, 103, 2242, - 244, 45, -74, -7, 366, -79, -359, -286, - 188, -14, 34, 49, 245, -108, -84, 88, - -333, -216, -79, 15, -5710, -36, -102, -552, - -213, -8, -356, 515, 212, -265, 80, 316, - -1163, -561, -517, -714, -375, -4176, 73, -666, - -363, -28, 1248, -68, 478, 2648, 642, -710, - -555, -744, -166, -744, -596, 138, 499, 59, - 453, -583, -290, -11, -48, 4174, -252, -74, - -78, -62, 449, -265, -818, -357, 171, -513, - 72, 106, -45, 649, 145, 5558, -60, -136, - 69, -172, -134, -66, -68, 100, 683, -427, - 795, -407, 345, 4930, -838, 361, 279, -190, - 173, -341, -9, 722, 383, -140, 123, -269, - 154, 31, 335, -465, 311, 46, 4535, -131, - 90, 151, 287, -11, -526, -614, -2253, -321, - -93, -550, -128, 25, 303, -139, 19, 0, - -3255, -161, 276, 103, -245, -515, 816, -1042, - -1449, 1693, -627, 1287, -837, -727, -80, -478, - -337, 116, 1, -270, -567, -311, -407, -1656, - -216, 196, 3004, -285, -521, 1510, 1818, 1392, - 42, -44, -244, -349, 959, -183, 25, 58, - 43, -345, -310, -8192, -84, 311, -60, -348, - 125, 33, -79, -138, 88, 138, -121, -37, - -211, -118, -142, -37, -132, 181, 162, -1423, - 1781, -3453, 1261, 134, 670, 1218, 761, 292, - -146, -825, 672, 737, 293, 433, 245, -392, - 46, 598, 257, -234, -1201, 718, -4549, -573, - -696, -224, -85, 75, -268, 244, 1817, 341, - -166, 436, -386, -1247, 22, -112, -55, -451, - 106, 388, -32, -254, -2400, -373, 892, 334, - -4114, -307, -107, -316, 41, -214, -403, -56, - -469, -246, 120, -237, 266, 43, 3257, -3925, - 291, 239, 752, -411, 162, 437, 159, 256, - 37, 71, -79, -136, -475, 124, -208, -216, - -245, 16, 40, -459, -4320, 340, -1462, 914, - 10, 490, 436, 162, 271, -238, -38, 2219, - 25, -141, 405, 107, 235, 282, -55, -7, - -3429, 565, -1095, -678, 1979, 233, -874, 592, - -474, 680, 402, -738, 21, 274, -321, 655, - -348, -546, 510, 62, 23, 4722, 572, 423, - -256, 473, 1240, -997, -899, -53, -73, 332, - -902, -771, -335, 0, 769, -587, 592, -703, - -600, -77, -94, -207, 792, -133, -758, 500, - -14, 330, 22, -281, -5460, 152, 607, 337, - -39, -118, -80, -51, 228, 65, -6, 540, - -3515, -1712, -449, -157, -164, -195, -1655, -1285, - 90, -517, -116, 11, 1402, -162, -64, -103, - 46, 302, 37, 71, 2903, 2952, 780, -487, - -297, -426, -369, 150, -129, -233, 813, 1639, - 190, 310, -311, 320, 94, -247, 1484, -32, - 70, -220, 560, 372, 54, 205, 96, -3567, - -680, 1683, -2377, 17, 548, -266, 257, 656, - 331, 205, -121, -814, 139, 326, -370, 625, - 2035, 818, 775, -1165, -41, -4258, 41, 1109, - 984, -885, -43, -314, 204, 204, 95, 407, - -351, 101, 133, -929, 899, -6, 384, -177, - -330, 240, 90, 78, -318, -455, -5, -365, - -61, -80, -72, -4850, -338, -384, 30, 181, - -2721, -767, 3217, 453, -226, -582, 283, 135, - -103, 265, 494, -1444, -120, 70, -976, -67, - -90, 660, 366, -609, 32, 205, 73, 51, - 346, -6, -120, -10, 300, 32, 270, 139, - -55, 453, 5712, 353, -145, 176, -168, 216, - 205, -30, -304, 1085, 221, 464, -426, 1662, - -1397, -1114, 301, -1058, 3553, -388, 743, 696, - -893, -296, -57, -254, -251, -178, 417, 82, - -988, -3566, 2171, -1312, -954, -23, -1349, 480, - 566, 24, -643, -292, -68, 303, 73, -81, - 296, 7, 371, 94, 1718, 498, -774, 857, - 1014, 358, 436, 210, -3481, -202, -416, 59, - 1987, 137, -476, 32, -627, 193, 368, -3, - -290, -3035, -352, -455, -609, -175, -5, -600, - -181, -249, -2551, 226, 105, -249, 1851, -86, - -1203, 214, -57, -505, -522, -247, -154, -40, - -17, -523, 333, -1777, -354, -1568, -3492, 1032, - 1577, 90, 153, 534, -106, -538, 102, 3, - -198, -99, -23, 835, 3495, -1099, 44, 732, - -350, 926, -472, 533, 1529, 54, -844, 1295, - 573, 414, -23, -71, 279, -891, 287, 126, - 1456, 973, 456, 1608, -646, -1244, 452, 651, - 694, 855, -235, -503, 745, -544, -3512, -138, - 678, 473, 220, -273, -9, 265, -1874, 397, - 1196, 284, -963, 298, 318, -2309, -162, 322, - -1250, -16, -1004, -5, 2800, -64, 72, -482, - -162, -412, -2922, 774, -335, 238, -1144, -134, - 1428, 558, 1969, -659, 902, -1698, 793, -858, - -613, 998, 253, -336, -348, -80, -117, -264, - 355, 808, 784, -559, 2030, 1952, -244, -1130, - -986, 1883, 1171, -493, -326, -880, 2588, -243, - -204, 194, -172, -65, 2026, 424, 587, -317, - 2550, -601, 203, -669, 475, -676, -1492, 27, - 41, -1078, -299, -630, 177, -164, -429, -246, - -357, 1191, -867, -1363, 1621, -110, 916, 217, - -1269, 622, -434, -1113, 888, -41, 1020, -1774, - 46, 80, -483, -892, -61, -472, 193, -192, - 2000, -103, 740, -223, 2493, 422, 2508, -331, - 470, -1233, 47, 595, 795, -465, -320, -163, - 128, 6, -209, 603, 536, -416, -1455, -87, - -1191, -98, -281, 1003, 1421, 388, 1163, -1146, - -81, -299, 2518, -1072, 207, -443, 506, -220, - -346, 98, 2119, -416, -2268, -498, 109, -1342, - -335, 1125, -712, 156, -1088, -2092, 1164, -500, - 113, -17, 551, -199, 262, -27, -692, -629, - 204, -1448, -1606, -1554, 289, 382, -691, 1229, - 414, -1746, -1198, 1113, -386, 310, 1354, -12, - -284, -569, 46, -558, 1495, 172, -899, 617, - 827, -365, 100, 1008, 136, 2111, 10, 2320, - -291, 364, -401, -408, -528, -612, 127, 1218, - -384, 129, -1603, 438, 1029, 2536, -150, -1432, - -856, 1068, 773, -762, -808, 676, -693, 404, - 145, 4, 27, -148, -318, -1019, -277, 1404, - 880, -1135, 861, 903, 739, 303, 139, 1918, - -952, 801, -306, -2439, -3, 442, -590, -1034, - 178, 430, 153, 1853, 1997, 742, 1745, -608, - -237, 160, 523, 950, 82, -1468, -1592, 807, - 719, 618, 319, 57, 235, 287, 1344, -50, - 324, -182, -365, -381, -377, 1989, 147, -573, - 1246, 1769, -473, -178, 961, -1297, -750, -1428, - -1246, 789, 158, 612, 17, -292, -227, -142, - 64, 51, -16, -301, -287, -60, -404, -267, - 109, -108, 189, -438, 48, 95, -5059, -42, -}; - -static const int16_t cb4432m1[] = { - 7567, 273, 268, -74, 201, 274, -149, -146, - -262, 243, -273, 63, -127, 135, -160, 231, - 120, 209, -91, -218, -38, -1206, -468, -159, - 278, 536, -995, -60, 22, 1041, -550, -121, - -241, -664, 427, -416, -1395, -732, 152, 3247, - -67, -154, -2430, 421, -405, -558, -73, -2887, - -272, -60, 365, 745, 287, -622, -1103, 412, - 266, 82, 61, -2172, -379, 529, -125, -1482, - 319, 643, 222, -508, 2451, -970, 71, 237, - -280, 202, 983, -223, -307, -130, 217, 3209, - 49, -30, 275, -12, -260, -3959, 1219, -104, - -2700, -201, 54, 851, -590, 691, -254, 408, - 296, -48, -364, 216, 16, 220, -415, 218, - 83, 43, -4032, -1359, 25, 15, -279, -2092, - 794, -433, -195, -162, 606, 166, 87, -316, - 508, 242, -359, 687, -178, 14, -2969, -500, - -1041, 3234, 679, 170, -791, -127, -630, -16, - -19, 181, -2, -185, -172, -88, -118, -167, - 128, 121, 239, 321, -125, 217, -7260, -157, - -161, -347, -257, 102, -1181, 71, -379, -205, - -268, 144, -174, -106, 305, 23, -47, 202, - -110, 660, 54, -2963, -119, -1371, -2823, 1171, - -726, 690, 534, 161, -435, 753, 58, 227, - 241, 138, -76, 473, 193, -1926, -2183, -2526, - -1428, 284, -1270, 336, -1458, 208, 41, -356, - 345, 153, -273, -166, 500, 42, 120, -35, - -81, 56, 1747, -3050, -2029, -764, -947, 888, - 422, 374, 143, -318, -225, 604, 343, -91, - 1626, 75, -211, 160, -667, -195, 38, -446, - -1269, -108, -959, -616, -530, 554, 2865, -156, - -358, -429, -261, 23, 511, 340, -548, 2347, - 105, 12, -32, 164, 170, -168, 268, 2587, - 3511, 612, 329, 159, 456, 273, -452, 168, - -394, 799, -58, 160, -480, -257, 242, 167, - 46, -1433, -1631, 50, 852, 509, 864, -381, - -306, -698, 261, -702, -19, 4113, -38, -153, - -11, 405, -441, -120, 139, -265, 225, 342, - 199, 2085, 237, 278, 252, 1537, 119, 182, - -174, -193, 2486, 87, 2903, -311, -304, 273, - -217, -256, -264, -675, -819, -188, -615, -1183, - 495, -154, -687, 2423, 197, -63, -146, 1151, - 896, -1129, -58, 1114, -1644, 1219, -648, -71, - -130, -2643, 533, -218, 3942, -83, 208, -724, - 198, -643, 590, -944, -56, -420, 115, 23, - -414, -144, 295, 219, -36, 393, -174, 91, - 290, -7066, 158, -275, -70, -119, -1, 302, - -262, -73, -61, 110, -196, -25, 87, -446, - -159, -6, -107, 115, -7562, 5, -33, 284, - -106, 34, -140, 160, -304, -272, -169, 25, - 93, -205, 28, 169, -165, -34, -50, 343, - 2204, 1440, 817, -1921, -590, -527, 81, -364, - -354, 163, -1058, 1977, 244, -75, 1201, -207, - 293, -289, -105, -121, 3588, 925, -2, -201, - -860, 917, 100, 265, -200, -44, -529, 351, - -579, -103, 186, -3622, 52, 181, -259, -411, - -4, -328, 380, 517, 306, 57, 340, -65, - -263, -311, 494, 326, -6136, 747, -141, 296, - 217, -2, -125, 8, -88, 254, -2934, -259, - 946, -905, 653, 436, 3393, -147, -157, 27, - 166, 299, 8, -16, 643, 114, 217, 57, - -21, -298, 19, 129, 1721, -134, 2337, 781, - -483, -748, 118, -330, -226, -3762, 222, -417, - -154, -24, -13, 1138, 210, 357, -122, 257, - -369, 863, 13, -320, -439, -433, 3469, -869, - 116, -2772, 202, 1065, -130, -287, 142, -288, - 54, 318, 131, -16, 84, 238, -361, 934, - 1341, 37, 130, -412, 146, -724, -3, -823, - 2555, -1263, 11, -147, 3164, -83, -39, -127, - 258, 26, -1181, 3339, -676, -30, -56, 691, - 867, 715, -903, 293, -205, -392, -22, 529, - -76, 2201, 433, 134, 1338, -18, 85, 3128, - 33, 924, 257, 1662, -769, 321, -449, -374, - -58, -597, -1670, 97, 222, -998, 404, -155, - 133, 358, -250, -125, 163, 6027, -228, -116, - -61, -878, -693, 710, -516, -191, -27, 443, - 83, -174, -695, -117, -107, -53, -142, 92, - -145, -114, -62, -710, -3192, -872, 3284, -521, - -36, -948, 252, -253, -143, 260, 109, -24, - 262, -169, -196, 195, 105, 27, -135, 1722, - 1862, -513, -270, -144, -414, -59, 91, -288, - -96, -56, -204, 273, 170, -171, -62, -4993, - -125, -67, -50, 226, -275, 600, 105, -217, - -450, -87, -20, -353, 24, -74, 167, 1881, - -4260, -144, 48, 92, 187, 319, 341, 22, - -4, 405, 147, 237, -120, 122, -237, 56, - -515, -153, 333, 834, 401, 210, -5516, 7, - 127, 147, -140, -479, -26, -1669, -21, -147, - 60, 387, 565, -140, -5827, -269, -1119, -324, - 118, -199, -11, 105, -49, 150, -148, 178, - 182, 162, 150, 68, -227, 3, 221, -330, - -23, 65, 6262, 71, 48, -41, -10, -1, - -44, -255, -50, -138, -109, -54, -31, 492, - -214, 239, -194, 35, -6348, -148, 9, 25, - -123, 84, -448, 241, 148, -35, 52, 35, - 7, 99, -16, 57, -43, -256, 3336, 373, - 211, -513, 2328, 86, -274, 386, 74, -174, - 624, -1037, -1154, 36, -209, -1028, -101, -412, - -103, -267, -107, -126, 163, -394, -1097, -100, - -1575, -542, 3326, -2149, 547, 626, -278, -414, - -781, 486, -186, -159, 138, -187, -821, 419, - 393, -4266, 828, 431, 86, 745, 1313, 1484, - 260, 52, 163, -455, -1071, 186, 522, 288, - 421, 18, 97, 1267, 200, 2637, -189, 729, - 746, 203, -639, -843, 2164, 671, 84, -2384, - 430, -161, 404, 166, -33, -17, 591, -227, - -3849, 1579, 175, -718, 99, -410, -844, -239, - 32, 212, 163, 480, 843, -379, -621, -317, - -424, 113, -262, 44, -93, 529, 144, -218, - 140, 3257, -575, -2697, 144, -83, -186, -44, - 977, 153, -230, -1530, 234, 212, 212, 331, - 412, -125, -3, 422, -329, -2181, 1406, 363, - -90, -86, 329, -267, -4462, -189, -87, 154, - 66, -200, 37, 80, -109, -199, 125, 1983, - 260, -438, -2417, 3259, -974, 453, 41, -77, - -538, 1123, 119, 120, 254, -239, -134, 33, - -384, -407, 27, 465, 1810, -910, 980, -15, - -1307, -919, 1880, -327, -303, -198, 149, 413, - 2176, 2269, -707, 343, 360, 169, 148, 182, - 104, 163, 857, 291, -153, 303, -679, -386, - -868, 2283, -320, 167, 3257, 1741, 338, 467, - 209, 207, 834, -226, -479, -120, 1674, -61, - 696, -93, -1327, 2176, 716, 402, 1688, 2219, - -339, 779, 366, 358, 241, -695, -272, -136, - -48, 36, -269, 862, -616, -118, -2028, 1678, - 1971, 115, 290, 71, -765, 31, -2874, 122, - 13, -424, -281, -320, 233, -1032, 40, -186, - 1208, 274, -2310, -1594, 289, 230, 1264, 962, - -310, 23, -548, 12, -38, -2734, 664, 37, - 346, -620, 266, -98, 82, 2369, 963, -1391, - -451, 833, 82, 175, 448, 1874, 345, -440, - 155, 130, 94, 326, 3223, 234, -163, -384, - -354, -539, 827, -9, 530, -226, -21, 332, - -2298, 3221, 1470, -282, -800, 231, 314, -998, - -1051, -648, -434, 743, -72, 119, 91, 414, - 379, 1370, -637, -998, 851, -2904, -266, -1652, - -1356, -1339, -1679, -181, 245, 731, -231, -2, - 221, -182, -325, -411, 346, 246, -2629, 1736, - -361, 24, 229, 1168, 747, 309, 425, -128, - -320, -496, 109, 1496, -70, -797, 37, -271, - -39, 906, -62, -194, 1753, 311, 689, 1354, - -1035, -973, -438, 1166, 2197, -99, -380, -274, - -1565, 447, 100, 349, 485, 653, 744, 50, - -582, -123, -1396, 156, -27, 349, -1067, -1382, - 1388, -1061, -554, 894, -80, -783, -1500, -736, - 897, 1158, -1386, -40, -280, -819, -672, -895, - 994, -308, -466, -578, 455, -1536, 879, -448, - 542, 1508, 850, -2465, 816, 641, -427, 310, - -168, -41, -908, -302, 1513, -29, -1144, 588, - -1703, 1144, 2623, 90, 284, 866, 335, -351, - 419, -745, 879, -183, -824, -1713, -34, -15, - -913, 37, -460, 778, 2130, -145, -153, 1761, - 1420, -243, -32, -877, 140, -700, 612, -2053, - 321, -78, -165, 200, 526, -1002, 2176, -1022, - 1436, 298, -21, -1378, 515, 304, 974, 1722, - 2054, 661, 425, 282, 471, 438, 70, 169, - 1587, -2076, -40, -702, 264, -146, -1499, -863, - -1775, -1059, -490, 92, 631, -1194, -1031, 335, - 257, -1299, 241, -270, -325, -322, -37, 0, - -685, 897, 984, -909, 1556, 1281, 1367, -1269, - -1591, 415, -1156, -374, -110, 1552, -695, 74, - -167, -473, 1421, -611, 175, 1521, 1322, 436, - 1969, -787, 1041, -730, -598, 188, -794, -531, - -2198, -317, -11, -8, -407, 198, -1180, -1675, - 174, 981, 467, -149, -890, 263, 1030, -121, - 2147, -135, 1975, -634, 431, -238, -695, 1338, - -172, 110, 147, -334, -726, 65, -873, 667, - 997, -1118, -339, 144, -700, 1303, -207, -609, - -1617, -765, 839, 505, -36, -58, -2894, 226, -}; - -static const int16_t cb4440sl0[] = { - -3624, -495, 158, -246, -529, -813, 689, 504, - -527, -2216, -198, -323, -690, -591, 175, 262, - 243, -3676, 2648, -986, 166, 243, 301, -700, - 324, -324, 13, 362, 222, -470, 30, 20, - -46, -147, 4050, -97, -560, 284, 317, -1611, - 655, -416, -1582, -675, 389, -124, 150, -27, - 325, -84, 48, 7474, 97, 105, 19, 38, - 133, 19, 28, 25, 40, 34, -59, 22, - 11, 27, 21, 5, -1596, -428, 439, 353, - 2288, -18, 357, -274, 2582, -126, -90, 71, - -9, -704, 205, 22, 44, -120, -43, 517, - 817, 1370, 2151, 2818, -470, 90, 395, -1243, - -345, 959, 19, -1, 123, -108, 347, 25, - -138, 15, 119, -117, -146, 142, 183, -254, - -276, -174, 5980, 283, -317, 70, 51, -15, - -2447, -79, 234, 736, -2600, -641, -1162, 376, - 959, -250, 701, -40, -102, 204, -38, -24, - -893, -387, 339, 1338, -91, -655, -864, 78, - 299, 228, -2732, 234, 1995, -1321, -139, 500, - -316, -140, 2, -80, 186, 11, 16, -69, - -7534, 85, -263, 189, -7, -1, -67, -68, - 3, 24, 391, -3299, -2952, -121, -393, 103, - -60, -113, 141, 185, -119, 240, 270, -392, - -105, 9, -39, 2529, -17, 353, 2966, -855, - 1042, 1294, 132, -257, -257, -496, 112, -179, - 424, 486, -63, 77, 275, -198, 2026, 1657, - 913, -255, -147, -1748, -5, 418, 356, 2022, - 927, -295, 194, 165, 28, 109, 13, 209, - -133, -2802, 420, -1873, -648, 309, -1172, -1825, - -36, 840, 280, 44, -118, 128, 34, 241, - -1005, 1160, -303, 318, 726, -1716, 2625, -950, - -839, -1257, -901, -238, 1123, 131, 252, 1, - 440, 1455, -14, -274, -461, 87, -515, -2299, - 928, -2867, -804, -215, 680, 147, 80, 215, - 15, 1339, 141, -95, 134, -35, 122, 53, - 429, 168, 476, -45, 745, 236, 4229, 318, - 247, -201, -372, 2289, 161, 431, 337, -707, - -1024, 121, -1773, -795, -1187, -401, 394, -1431, - 1526, -35, 432, 2929, 90, 1880, 628, 1298, - -552, -498, 207, -97, -1431, 1105, 29, -739, - -56, 62, 94, 537, -732, 1255, -766, 200, - -365, 2846, 2139, 435, 92, -710, -512, 360, - -339, 1021, 474, -132, 405, -440, 3435, 75, - -254, -2443, -880, 325, 343, 285, 230, -431, - -191, 215, 201, -443, 93, -81, -131, 2981, - -2986, 1003, 437, 434, -386, 17, 222, 70, - 173, -550, 267, -121, -43, 114, -11, -795, - 561, -147, 187, -198, -4969, 50, 59, 674, - -853, 163, 71, -205, -284, -50, -28, -1412, - -105, 262, 272, 565, -824, -541, 3381, 430, - -81, 228, -426, 978, -294, 422, -538, 13, - 9, 430, 180, 2329, -564, -1082, 1740, 1108, - -2011, 11, 343, 868, 723, -806, 342, 339, - -141, -173, 186, 50, 297, 705, 783, -593, - 1609, 212, 528, -2547, -863, -2457, -876, 164, - 162, 365, 68, 30, 11, 48, 47, -285, - -64, 166, -21, -6880, -191, -226, 89, -1, - 22, -93, -6, 44, 282, 52, 294, -690, - -147, 372, 2247, 804, -637, 54, 2385, -1799, - 315, -929, 692, -65, -54, 218, -752, -519, - 2171, 177, 907, 22, -778, -2656, 62, -418, - -434, 307, 1906, -280, 196, 76, 58, -46, - 70, -367, -67, 50, 125, 77, -547, -287, - -97, -10, -84, -271, -4856, 10, 490, -560, - -21, 66, -2469, -322, 1021, 936, 625, -2520, - 1144, -373, 270, 804, 603, -91, 262, 659, - 9, -324, 50, -712, 2705, -3016, 594, 87, - -88, 697, -205, -799, -128, 37, 504, 59, - -274, 655, 672, -20, 1294, -221, -2954, 198, - 674, -1676, 863, 324, 968, 731, 1125, -41, - -149, -303, 223, 1370, -67, -194, -1, -194, - 251, -459, -39, 4477, 113, -74, -386, 214, - -72, -77, -1593, 511, -461, 752, -559, -476, - 204, -722, 1050, 2080, 2468, -154, -208, 964, - 103, -58, 390, -1863, 910, -307, 209, -32, - 663, 103, -133, -3137, -423, 259, -605, -242, - 139, -391, -488, 77, -266, -1694, 397, -659, - 237, 2068, -3, -867, 870, 1647, 645, 1848, - 68, 382, 455, -551, -87, -99, -2926, 372, - 2438, -1166, -6, 521, -195, 1259, -162, 917, - 140, 275, -273, 133, 318, -25, 252, -119, - -132, 3120, 397, 398, -420, 1756, 666, 2176, - -141, 271, -51, 22, -494, -36, 57, 308, - 222, 3585, 16, -265, 2628, -24, 162, 13, - -240, -96, 620, 331, -449, 710, -123, -105, - 23, -170, 20, 256, -5228, 398, -186, 272, - 129, 175, 598, -16, -502, 11, -215, 28, - -110, 3570, 68, 199, -2535, -933, 781, -762, - 325, 18, -438, -319, 473, -677, 176, 290, - 0, 67, -6, -156, 31, 35, -131, -127, - 24, -100, -6826, -117, -53, -40, 99, -50, - -93, 31, 34, -251, 186, 487, -203, -662, - -182, -96, 239, 308, 338, -86, -4871, 264, - -48, 314, -66, 100, -188, 151, 24, 198, - 4, 5046, -47, -654, -43, 41, 109, 103, - -262, 93, -118, -63, 58, 2088, 336, -320, - 2326, 548, -810, -1315, -864, 461, 171, 76, - -1109, -1510, -874, -620, 97, 88, 40, -4, - -7295, -128, -39, 23, -100, -9, -74, 112, - -151, 67, 21, 53, 2, -29, -33, 52, - 3287, -2178, 626, 339, -817, 349, -1187, -550, - -390, 57, -41, 295, 756, 185, -215, 17, - 3, 7502, -134, -122, -31, -53, 91, -170, - -71, 133, -34, 57, -112, -5, -66, 17, - 1, 2328, 3714, 214, -123, -839, 9, -62, - 54, 70, -18, 817, 186, -61, -252, 37, - 98, 9, 2010, 738, -1651, -1924, 1106, -624, - 143, -548, 847, -198, -140, -691, 478, -758, - 56, 54, -7, 209, -2665, 109, -127, -134, - 2099, 333, -602, -2217, -743, 346, 74, 216, - 579, 223, 61, -30, 57, 94, 224, -2595, - -566, -851, 246, 314, 65, 2857, 114, -760, - 77, -611, 119, 181, 4, -2556, 127, 138, - -164, -219, -116, 157, -3143, 197, -98, -1040, - 235, -332, -424, -152, -338, -33, -220, 207, - 254, 5469, -102, -390, -125, -420, 113, -233, - 329, -34, 109, -171, 103, 50, 58, 96, - -500, -2317, -259, 2178, 109, -2030, 759, -780, - 448, 678, -384, -271, 213, 334, -271, 23, - -1121, 636, -1103, -482, -3059, -1200, 1160, 109, - -232, 541, -788, 130, -166, -300, 664, 233, - -97, -29, -286, 33, 1272, -298, -382, -242, - -199, 47, 479, 224, -1761, -1904, 1780, 1439, - -681, -1973, -118, -90, -148, 247, -758, 1936, - 182, 1373, 2346, 120, -758, -476, 1789, 1177, - 611, -394, -14, -39, -994, -674, 1049, -41, - 836, -391, 942, -1040, -1437, 1376, -1916, 1129, - -1018, -653, 1284, -72, -166, 321, 194, -142, - -151, -77, 251, -162, 732, -790, 107, -292, - -675, -4248, -51, -86, -299, -495, 413, -128, - -455, -105, -842, 881, -492, 1241, -1432, -1296, - -52, -430, 2533, -1765, 838, 84, -24, -798, - -428, -154, -658, 37, -388, -591, -931, -433, - -1837, 1363, -683, -717, 3115, 104, 0, 1104, - 208, 148, 404, 101, 18, 217, 58, 49, - 4, -49, -195, 187, -239, -21, 294, -138, -}; - -static const int16_t cb4440sl1[] = { - -3057, -853, 3212, -334, 5, 224, 63, -250, - -345, -102, -289, -115, 75, -99, 206, -8, - 19, 96, -254, -2566, 334, 2773, 136, 199, - -1076, 347, -187, 481, -64, 654, -9, -1094, - 196, 40, -95, 5, 163, -135, 253, -1053, - 316, -231, 24, -2307, 1480, -2052, -18, -459, - -550, -1860, -15, 98, -1406, -66, -250, 21, - 497, -404, -54, -228, 2477, 2011, -145, -1957, - -426, -906, 608, 15, 1453, 218, -79, -636, - -1005, -332, 304, 2338, 1356, 81, -1201, -170, - -126, -1177, -1644, -1046, 16, 182, -328, -347, - 346, 591, 418, 623, -110, -342, -227, 10, - -5055, -411, 128, -103, 87, -28, -133, 196, - 333, 1785, -479, -442, -2892, 453, -2292, -19, - -383, -44, -435, -193, 503, 130, 4, 144, - 2184, -245, -7, 458, 82, -76, 3052, -375, - 1299, -76, 364, -145, 372, 36, 59, -39, - 48, 385, -230, 2764, 2956, -741, -372, 428, - -504, -220, -821, -47, -49, 609, -62, 56, - 6, 216, 376, 519, -512, 54, -318, -183, - -4563, 297, 795, -182, 108, 234, 404, 218, - -123, -17, -192, 170, 349, 134, -91, 43, - -135, -24, -6, -32, -6681, 50, -138, -89, - -18, 15, 24, -416, 356, 311, 83, -267, - 81, 209, -155, -368, 396, 358, 232, 4696, - -347, 724, 112, 10, 331, 358, 197, 54, - 824, 646, -214, 113, -4425, 184, -11, 101, - -313, 186, 253, 169, 78, 52, -70, -108, - 1669, -22, -18, -2600, -27, 2806, 288, -106, - 506, 176, 616, -299, 58, -30, 1, -220, - 400, -177, 874, 70, -36, -274, -139, 1148, - 372, 40, 236, 505, 619, -4002, -95, -48, - -2854, 114, -69, -2805, -401, -9, 203, -1011, - 472, -1066, 412, -220, 245, -183, -27, 35, - -762, 312, -137, -292, -242, 896, 172, -345, - 106, -4490, 506, 569, -11, -352, -108, 334, - -165, 2389, -895, 2761, 467, 201, 150, -516, - 39, -1105, 4, 587, -152, -764, -184, -15, - -137, -30, -12, 7, 382, -461, 1577, 3519, - -173, 1370, 80, 499, 344, -771, 123, -13, - 288, 233, 111, -2472, 3952, 771, 216, -505, - -446, 531, -230, 103, -72, 34, 61, 249, - -175, 353, 83, 51, 169, -97, -60, 7827, - 95, 75, -13, 201, -27, 103, -11, 1, - 3, 121, -73, -28, 7, 2908, -209, -987, - -129, -341, 2840, 889, -147, -521, 123, 95, - -239, 552, -738, 279, -66, 0, 16, 116, - -45, -28, -43, -38, -7627, 30, -52, -209, - 281, -46, 23, -24, 56, -25, -23, -2534, - -107, -46, -93, -49, 238, -25, 96, -356, - 3483, -459, -414, 205, 102, 202, -150, -116, - 1785, 1399, 793, 543, 685, -2837, 255, 362, - -96, 410, 926, 1068, 416, 558, -169, 246, - 138, 2136, 39, -96, -605, 279, -130, -2741, - -1101, -935, -20, -227, 453, 1261, 103, 275, - 358, 43, 197, -23, -251, 322, -22, 233, - 2560, -214, 2, -101, 645, 2864, 287, -479, - 904, -65, 73, 224, 2418, -95, 428, -678, - -278, 71, -545, -571, -566, -181, -212, -2947, - 222, 780, -365, 124, -2703, -198, -69, -246, - -3056, -184, -598, -75, -145, -690, 380, 194, - 485, 214, -484, 54, 163, 363, -924, 1684, - 201, 34, 236, -539, 2374, -150, -490, -1313, - -61, 317, 2123, 315, -551, -26, -328, 207, - 253, -3015, 166, 109, -662, 2466, -157, -740, - 751, 254, -788, -369, -6, 100, -211, 107, - -309, -39, -47, 279, -126, -91, 97, -705, - 235, -231, 182, 283, -5097, -68, 285, 49, - 50, 637, 111, 39, -386, 923, 223, 115, - 1638, 1214, -640, -2168, 482, -2228, 857, 172, - 15, -2207, -89, 335, -18, 295, 718, -956, - 26, 604, -436, 2856, -1131, 98, -754, 243, - 9, 29, -4028, -1725, -1741, 432, -211, -60, - -535, 201, -273, 111, 444, 607, -250, 122, - 98, 159, 97, 281, 3071, -412, -2849, -721, - -14, 960, -43, 794, -427, 297, 478, 379, - -47, -22, 69, -60, -30, -732, 2456, 170, - 142, 6, 2520, -644, -201, -16, 1602, -20, - -293, 542, -451, -167, -9, 14, 1052, 2707, - 2980, -117, 479, -202, -92, 36, 904, -66, - -1088, -31, 75, -62, -110, -29, 112, -102, - 5217, -85, 14, -191, -202, -175, -71, 182, - -231, 275, 144, -1, -202, -13, -29, -19, - 70, 39, 46, 56, -7608, -53, -104, -61, - 44, 23, 1, -157, 42, 12, 38, 37, - 331, -609, -2516, -174, -2491, 258, -256, -926, - 983, 100, 83, 173, -965, 650, -304, -97, - 98, -166, 534, 2570, -611, 493, 103, -98, - 148, 3081, -131, 285, 13, -367, 205, -53, - 41, 29, -154, -2657, -51, -312, 134, 50, - -1514, 634, 411, -2885, -391, 365, -373, -54, - -74, -151, 80, 152, -91, -64, -209, 1134, - -2921, 316, -951, 1124, 713, 2, -2212, 31, - 164, -260, 103, 36, 229, 111, -23, -65, - -37, -220, -108, -30, 86, 17, 87, 205, - 163, 63, -5763, 254, 178, -18, 1760, -380, - 1453, -3151, 710, 106, 66, 387, 235, 463, - -295, 688, -124, 322, -193, 82, 1012, -2033, - -656, 1362, 805, -747, 2527, 470, 43, -1001, - 100, -83, 161, 74, -1128, -307, -82, -197, - -5470, 226, -327, 137, -131, 471, -432, -16, - 243, 224, 168, -164, -58, 125, 23, -2, - -2752, 268, -92, -466, 2876, 874, 182, 540, - -407, -338, -396, 562, -376, 536, -225, 160, - 44, -1501, -246, -1062, -378, 446, -2448, -124, - 499, -2297, -353, -637, 395, 598, -747, 418, - -495, 5, -1014, 2138, 289, -75, 301, 944, - 66, -457, -459, -253, -2, 678, 367, 116, - -2901, 436, -239, -303, -973, 384, -2574, 6, - -225, -164, -440, 627, 388, -3074, -263, 156, - -805, 381, -9, -112, -1481, 536, -711, 3770, - -496, 908, 483, 474, 298, -424, -793, -203, - -334, 134, -91, 208, -73, 5440, -316, -304, - 249, -1, -98, -214, 190, 242, -57, -38, - 244, -219, 30, -224, 66, -30, 22, 24, - 24, -109, -7594, -115, 90, -147, -83, 21, - -257, -52, 134, -49, 92, -117, 30, -8, - -636, 1551, 2207, -66, -1962, 212, 567, 969, - -1595, -562, 355, -467, -861, 937, -148, 15, - -68, -1516, -2118, 1477, 777, 1458, 976, 522, - 325, 957, -130, -132, -918, 448, 1088, 102, - 142, -644, -284, 687, -665, -132, -1870, 1387, - 733, -84, 920, -508, 53, -2183, 254, 565, - 2056, 97, 57, 219, 688, -344, 659, 2033, - 963, -1717, -290, -934, -2119, 57, -1452, 24, - -639, -739, -232, 170, 28, 359, -312, 310, - -103, -1067, -953, 1081, -857, 1926, 1364, -1719, - -863, 1832, 786, 55, 166, 383, -1373, -347, - 1710, -908, 91, 1257, 2013, -592, -1337, 1431, - -90, 617, 549, -356, -68, 134, -48, -133, - -176, -18, -65, 23, 84, -23, -36, -4, - 230, 297, -204, -150, 86, -4965, 742, 40, - 32, -1070, 149, 38, 302, -329, -386, -57, - 45, -1622, 1425, 1817, 1568, 2202, 7, -1192, - -201, -42, -62, -170, -32, -117, -38, 229, - 44, -226, 155, 70, 747, 259, -261, -120, -}; - -static const int16_t cb4440ss0[] = { - -3021, 2048, -450, 1147, 1487, -796, -657, 459, - 609, 63, -153, -1174, -144, 37, -176, -160, - 43, -31, -2577, 88, -797, 1179, -707, 3154, - -543, 875, 116, -40, -150, 326, 293, -112, - -73, -34, 61, 8, -2251, -1551, -2507, 6, - -52, -5, -323, -313, 1076, 920, 1116, -1100, - 1103, 310, -144, 904, 149, -59, 636, -1508, - -378, 381, -917, -868, 1388, -1225, -68, 1491, - 685, -220, 3253, 48, -504, 192, 114, -11, - -1718, -916, 660, -240, 767, -1061, 332, 591, - -477, -278, 25, -1485, 55, 216, -3238, -19, - -320, -148, 273, -876, 22, -529, 3263, -2535, - -756, -133, -481, -1024, 34, 418, -415, 412, - -92, -90, 161, -49, -1699, -2737, 2923, -243, - 122, 87, 984, -377, -37, 128, 350, -444, - -98, -52, 14, -14, -86, 255, 1997, -1239, - 42, 247, -15, 16, 405, 302, -17, 84, - -4033, -12, 254, -365, -205, -162, 329, 31, - -1158, -210, -376, 3958, -1601, -1128, 737, 731, - 300, -785, -777, -403, 463, -226, -109, -277, - -70, -53, -856, -785, -997, 71, 5565, 317, - 447, -279, -357, 254, 93, -47, -206, 133, - 88, 272, 7, 44, 2229, 1666, 234, 519, - -1996, -1195, 549, 449, 174, -1010, 622, 425, - 2288, -9, -390, 612, -40, 32, -1867, -673, - -70, -1174, 106, 134, 354, 61, -144, -290, - 82, -604, 202, -3954, 248, -76, 7, 224, - -1844, 99, -146, 206, -335, 243, 25, 60, - 186, 117, 67, -137, 119, 46, 4563, 45, - -46, -2, 874, 533, 216, -38, 185, -540, - -191, -163, -126, -108, -184, 193, -39, -4768, - 111, -89, -61, 17, 1064, 1678, 894, 4334, - 139, -892, 317, -351, 417, -87, -22, 195, - 20, 140, 234, -197, -268, -5, -1618, -756, - -119, -1749, -704, -943, 421, -3488, 871, -468, - 656, 266, -79, 325, -303, 45, -3, -31, - 1140, -707, -1578, -1434, 290, 327, -1365, -2913, - 1048, 38, -136, -871, -572, -30, 186, 343, - -30, -157, 1301, 1913, -515, -842, -723, -84, - -340, 270, -918, 3213, -1530, -394, -184, -60, - -391, -27, -110, 84, 104, 419, 1201, -810, - 1546, 39, -914, -334, -4257, 427, -95, -426, - -94, 256, -148, 246, -80, 9, -462, -1125, - 644, 3541, -140, 2346, 1045, -335, -867, 809, - 432, 386, -6, 159, 70, -10, 218, 43, - -2229, -607, 537, -924, -3038, -943, -968, 1261, - 28, 197, -285, 61, 137, 69, -2, -251, - 111, -19, -314, 2064, 960, 1529, 1056, 926, - -319, -1617, 1305, 1473, -867, 684, 1357, -834, - -66, 477, 74, -15, -1769, 1925, -2448, -1777, - -507, 264, -1740, 176, -518, -58, 32, -108, - 165, -68, 189, 35, 40, -85, -1152, 255, - 36, -1922, 1500, 1415, 841, -92, 3305, -110, - 3, -219, 167, 573, 219, 310, 27, 195, - 359, -244, 538, -2042, 355, 656, 51, -199, - -204, -3611, -396, 839, 743, -241, -80, -210, - -101, 28, -1399, 1062, -955, 54, -630, -178, - -376, 212, 237, -219, 47, 805, 216, 26, - -4334, 455, 4, 4, -1587, 95, 1186, -3101, - -140, -862, 916, 2063, 211, 96, 337, -185, - -195, 424, 1207, -31, -162, 206, 2485, -46, - -451, -1778, -40, 144, -155, 2884, 803, 396, - 1196, -635, 297, -76, -121, -162, -206, -149, - -2204, 1035, 232, -815, -49, 1006, 553, -407, - 161, 3650, -264, 370, -418, -28, 141, -177, - -113, -90, -315, 626, 62, 1392, -1815, 336, - -1276, -402, 486, -1060, -1848, 2610, 826, 485, - -250, 39, 208, 14, 2555, 2869, -813, -2074, - 337, 601, 855, -655, 566, -707, 189, -77, - 137, -510, -282, 79, 42, 73, 62, 650, - -4732, -486, 354, 420, 828, -645, -492, 388, - 753, 18, 2, 766, -212, 126, -43, 45, - 447, -283, 607, 251, -166, -10, 48, -5850, - -251, 128, -205, -95, 90, 90, 67, 24, - -50, -48, -167, -3231, -2926, 1831, 199, 484, - 169, -614, -135, -374, -418, -239, -89, -121, - 45, 75, -11, 16, -1058, 354, 1633, 589, - -1223, 1218, 842, -1146, 2186, 374, -363, 216, - -2153, -429, 429, -597, 93, 148, 1849, -797, - -162, 31, -325, 343, -323, 161, -373, 684, - -367, -452, -4306, -88, 28, -56, -59, 43, - -49, -1998, -956, 1331, -4214, -129, 30, 79, - -90, -129, 109, 130, -160, 409, 105, 298, - 208, 178, 1724, 731, 773, 128, 817, -425, - -4046, 180, -782, -116, 191, -259, 181, -31, - 162, 43, -41, -69, 1463, -1769, -2, -442, - -636, 1495, -218, -123, -58, 3616, 454, -475, - 247, -383, 304, 185, 155, 40, 1104, 1046, - -8, -736, -1155, -115, 3925, -257, -35, -599, - -437, -135, -256, 55, 214, -88, 215, -57, - -1097, 183, -501, -608, -135, 148, 405, 295, - 96, -513, 1013, 4350, -162, -61, 427, 315, - 24, -77, -1278, -167, -1774, -133, -323, -4339, - 732, 597, -30, -103, 79, -241, 177, -388, - 7, 44, 175, -143, 5030, 277, 58, 42, - -222, -133, -319, 6, 240, 217, -238, -198, - 218, -43, 439, 49, 37, 106, 1123, 2196, - 158, 171, 458, -932, -435, -2783, -300, 444, - 2317, -146, -339, -162, 157, -216, 1, 66, - 987, -190, -728, -3188, -3167, 378, -1, 158, - 459, 78, -42, 386, -133, 155, 294, 359, - -29, 78, 1763, 780, 1019, -330, 179, -51, - -393, 338, 4422, -296, -392, 170, 2, 52, - 253, 150, -191, 139, -371, 161, -2202, 156, - 37, -1004, -384, -466, 23, 183, -3701, 97, - -1293, -355, -83, -63, -26, 69, -1817, 641, - 2996, -16, 2011, -406, -647, -652, 332, 788, - 484, 918, -440, 1246, 165, 52, -260, 31, - -255, -7237, 14, 90, -135, 122, 14, 154, - 5, -78, 111, -254, 154, -23, -24, -83, - -9, 49, -426, 1657, 99, -36, -191, 2625, - 655, -20, -2723, -977, -222, -48, 155, 41, - 20, 194, -73, -26, -1206, -3517, -471, -815, - -1144, -371, 1353, -1069, -1238, 829, -227, 487, - -297, -101, 914, 100, -17, 115, -806, -798, - 585, 1097, -1, -792, 818, 29, -256, -417, - 942, 68, -4165, 34, -408, -252, 55, -77, - 246, 2055, -4, -313, -661, -836, 559, -393, - 2043, 153, 286, -2700, 98, -177, 1201, 99, - 308, -73, 1441, -3902, 730, -1610, 886, -599, - -126, 473, 43, -252, 45, 95, -291, 101, - -307, 259, -149, 26, -510, 498, 1403, -78, - -1039, -2551, 773, -1176, -1525, -405, -259, -283, - 398, 2080, -199, 62, 239, -26, 960, 582, - 2516, 799, -2127, 325, -253, -1652, -965, 1413, - 8, -119, 396, -342, 277, 541, 186, -142, - 1210, -732, 798, -47, -557, -12, 63, 537, - 148, -128, 328, 290, 203, 361, -328, -64, - 4004, 197, -640, 996, -93, -2314, 76, -914, - 1437, -964, -1735, 984, -578, 1389, -1025, -66, - -120, -1211, -32, 5, -1215, 771, 1621, -934, - -984, 148, -1592, -446, 19, -976, -1709, -1113, - -218, 191, -279, 2183, 10, -37, -842, -1582, - -92, 558, 227, -702, -365, -576, -100, 670, - -305, 285, 48, -329, 253, 3878, 156, 70, - -1008, 641, 1541, -234, 1440, 421, 1088, 735, - -206, -83, 460, -139, 107, -1160, -6, 2087, - 1894, -117, 962, 113, -990, 93, -29, 579, - 1217, -52, -342, -451, 670, 202, -1070, 837, - -132, 3507, -59, -114, -691, 208, -1170, 1089, - 305, -200, 603, -1301, -942, -1631, 1291, -2727, - 414, 80, 815, -443, 54, -34, -1141, 1301, - -1199, 372, 102, -257, 70, 450, -55, 80, - -227, 218, 264, 739, -52, -200, 3873, 83, -}; - -static const int16_t cb4440ss1[] = { - 6875, -104, -66, 161, 57, 24, -4, 76, - -122, -100, 31, 188, -119, -50, -244, 49, - 1, -100, 555, 253, 433, 633, -163, -5345, - -170, -217, -49, -29, 331, 633, -87, -46, - -29, 44, -174, -74, 2188, 434, 660, -593, - 1548, 379, 1443, 1676, -63, -2125, 246, 534, - -463, 872, -169, -12, 33, 211, -409, 408, - 1514, -189, -277, 391, -361, -35, 145, -362, - -4669, 212, -97, -65, 387, -81, 70, 36, - 448, 303, 332, -1077, -258, -1353, 1185, -50, - -12, -74, -2101, 2429, 1817, -939, 393, 169, - -22, -36, 1219, 3237, 816, 452, 1807, -646, - 407, -447, -1778, -370, -528, -127, 104, 416, - -121, -134, -62, 20, 1751, -640, -222, 950, - 1603, 555, 9, 219, -1272, 2724, 1004, 1237, - -395, 356, -453, -98, -24, 80, -1621, 474, - -1947, -237, -1059, -2091, 780, 1211, 939, 268, - -412, 1923, -419, 851, 230, 567, 143, 48, - 1506, 2228, -1226, -453, 246, 469, 540, -538, - -96, 977, 508, 105, -3150, -142, -37, 395, - 9, -38, 1, -135, -391, 1702, -179, -1566, - -3181, -1679, 203, -151, 387, 250, 563, 203, - 443, -168, 82, 61, 1604, -1878, 229, -82, - 208, 2965, 1093, 251, 1592, -432, -532, 153, - 407, 157, 191, -216, 52, -58, 935, -2161, - -409, -513, 977, -113, 3247, -1207, -743, -1178, - 136, 206, 184, -885, -64, 16, -23, -24, - 731, 1769, -941, 1543, -2386, -669, -958, 233, - 105, -1124, 948, 97, -1949, 59, -152, -65, - 114, 82, 387, -1908, -492, 129, -624, 93, - 658, -753, 1032, 2480, -1776, 360, -38, 1924, - 168, -12, -10, -128, -1712, -446, 939, 465, - 605, -586, -299, -393, 3878, 111, -379, 146, - 186, -50, -279, -30, -3, 35, -1941, 360, - -79, -111, -4287, -6, 671, -214, -792, 277, - 77, 58, 8, 16, 133, 161, 21, 33, - 1535, -296, -2668, -3198, -28, -386, 1156, 144, - -201, 256, -411, 298, 67, 670, 11, -227, - -4, -104, 12, -1000, 1192, 860, 813, 360, - 25, 93, 792, -350, 81, 4046, -178, 122, - 332, 28, -112, -8, 288, 539, -17, -63, - 8, 231, 55, -514, 105, -344, 252, -153, - 59, -10, -21, 51, 6793, 45, 259, 384, - 209, -2010, 311, -769, -1957, 2791, -463, -293, - -218, 1026, 897, -798, 47, -525, 31, -42, - 2018, -2767, 1658, 685, -1947, 46, -1468, 340, - -272, 318, 21, -421, -396, 244, -51, 290, - 45, 3, -1530, 1359, -3681, 1487, -1689, 209, - 438, -785, -220, 2, -55, -483, -35, 40, - 6, 189, -200, 2, -2026, -1747, 838, -880, - 1128, -3108, 184, -671, -261, 8, 296, -130, - -78, -268, -100, 18, -105, -9, 448, 3184, - -570, 656, -376, -969, 1682, 2635, -277, 577, - 217, 281, 219, -351, 31, 64, 101, 82, - 957, -1885, 774, -3536, -168, -431, -106, -479, - 1041, -103, 774, -142, 894, -724, -94, -766, - -58, 112, 2028, 566, -346, -139, -2671, -1907, - 1039, 189, -33, 1690, 263, -514, -225, -237, - 145, -319, 38, 116, 2891, -77, -2065, 2559, - -327, -763, 86, -172, -283, -147, 137, 245, - -333, 220, 92, 194, -176, 105, 3108, 329, - -372, -1188, 670, 773, -235, 34, -146, 876, - -259, -1580, 876, 105, 582, 259, -63, -99, - -1558, 1122, -1541, -438, 227, 1221, -1297, -746, - 2698, -29, 1169, 995, -2, 201, 392, -405, - -22, -36, 757, -4039, 725, 1960, 1478, -107, - 67, -367, -97, -88, 154, -80, 0, -265, - -163, 14, -109, 33, 597, 115, 543, 468, - -757, 826, 509, -176, -305, -4959, -118, -464, - -421, -72, 1, -187, 123, -88, -1086, 26, - 368, 610, 3394, -337, 364, 2594, 491, 759, - -309, 395, 152, 338, 249, 303, -122, 63, - 1019, -864, 1546, 196, 75, -633, -93, -631, - 777, -74, 1235, -745, 377, 3113, -174, -282, - -24, 89, -920, 2124, 620, 566, 1290, 2977, - 1180, 278, 188, 750, 981, -357, 80, 69, - 77, -151, 150, -15, 834, -893, 818, 1655, - -500, 237, 133, 243, 405, 239, 16, -152, - -70, -3692, -110, 145, 58, -57, -2527, 3072, - 2226, 218, -824, 384, -96, 119, -228, -194, - 136, 111, -251, -109, -179, -34, 143, 109, - 1157, -216, -1429, -702, 323, -1199, -60, 632, - -585, -340, 1040, 471, -32, -380, 3432, 455, - -138, -39, -2416, 652, -253, 145, 281, 393, - -671, 2841, -1616, -46, -385, -1417, -273, -168, - 318, -263, -2, -69, -638, -137, -2668, -359, - -86, 79, -777, -404, -560, -3533, 122, -113, - 617, 497, 117, -268, 110, 73, 752, -1105, - -521, 762, 695, -587, -147, -1235, 1866, -2250, - -671, -511, -2178, -820, -619, 162, -37, 102, - -342, -278, 6837, -278, 185, 10, 361, -52, - -171, 246, 184, -175, 19, 166, -48, -41, - 92, -152, -1227, -983, -3985, -703, 1143, 204, - -523, 1053, -623, 1002, 231, 53, -277, -409, - -67, -56, -90, -47, 448, 754, 554, 972, - 505, -331, 4946, -193, 89, 530, -24, -172, - 254, 244, 140, -10, 40, -77, 1655, -438, - -2776, 51, -553, 592, -2902, 280, 804, 776, - 131, 69, -207, 131, 7, 209, 93, -19, - -1148, -733, 2674, -1628, -1243, -506, -2346, -857, - -1028, 666, 365, -353, 105, 120, 210, -85, - 37, -40, 1027, 11, 1234, -5, -1976, 515, - 289, 3815, -142, -188, -248, -273, -265, 593, - 205, 164, -65, 70, -992, 1586, 2130, 779, - 92, -3067, 421, 1, 1172, 496, -917, -760, - 169, -64, 14, -40, -247, -95, 1769, -145, - 712, -794, -571, 240, -1774, -38, -129, -836, - 3372, 887, -451, 73, -107, 182, 100, 14, - -703, 2559, 490, -839, -333, 134, 804, -3549, - 50, -199, -215, -370, 453, -86, 151, -98, - -58, 128, -2624, -1507, -1623, -2186, -89, -55, - -472, -667, 2, -439, -1453, -262, 565, 56, - -118, 288, -56, 87, -398, 729, 40, -6015, - 219, -212, 287, -250, -211, -29, -61, -55, - -120, -92, 30, 129, -122, 111, 2037, 1260, - 943, -252, -13, -794, -2570, -1117, 297, 374, - -1629, -1, -407, -597, -324, -179, 408, 58, - -902, -1672, 611, -198, -61, 103, 366, 915, - 811, -280, -401, -3849, -111, 221, 353, 232, - 4, -18, 673, 1792, -2350, 132, 1979, -2318, - -417, -689, 326, 768, -377, -522, 373, -389, - -105, -103, 33, -48, 1497, 1125, 1893, -2744, - -1219, 921, 472, -165, -438, -129, -682, -783, - -685, 167, -715, 156, 64, 61, 1147, -892, - -72, 579, 1191, -2759, 1831, 1895, 663, 816, - -98, -61, -223, -366, -429, 31, -129, -121, - -255, 1804, 138, 180, -1063, 598, 763, 720, - 385, -526, 143, 80, 168, 976, -714, 236, - -3204, 93, 874, 238, -359, 1595, 191, 568, - -182, 20, -608, -288, 602, -224, 3874, -308, - -70, -826, -109, -42, -882, -1421, -1603, 625, - -1206, 31, 782, -106, -700, -246, -571, -124, - -848, -390, -523, -2903, -9, 39, -109, -199, - 497, -11, 377, 5, 25, -115, -61, 283, - 27, -131, -193, 280, 178, -5439, 44, -52, - -1210, -617, -162, -1097, -3, 748, -45, -1197, - -1058, 909, 1607, 693, 42, -749, -3001, 407, - -62, 45, 214, -312, -1054, 498, 1291, 1189, - -1268, 1083, -757, -319, -2796, -716, 310, 1583, - -608, 319, -84, -119, -1415, -602, 628, 463, - -1213, -794, -474, 2682, 931, 240, 2491, 76, - -234, -161, -690, 359, 28, -19, -774, -1023, - 738, 675, 248, 52, -348, -545, -2715, -599, - -252, 660, -387, -104, 2316, 456, -90, 100, -}; - -static const int16_t cb4440sm0[] = { - -6448, -59, 298, -659, -59, 329, -569, 397, - -224, 128, -216, 153, -100, 319, -53, -90, - 50, 3313, 4, -215, 405, -256, 78, 2890, - -187, -969, 195, -1022, -119, 214, 254, -360, - -222, 39, 2139, 91, -290, 529, -73, -16, - -318, 128, -348, 565, -1190, 202, -185, -234, - 3498, 48, 68, -1917, 1694, 212, -477, 239, - -3301, -489, 424, 418, -82, -61, 599, 1530, - -200, -252, 162, -243, 43, -534, -2695, 255, - 317, 489, 279, 3337, 246, -349, -149, -128, - -146, 256, -455, 137, -75, 836, 209, -349, - 3494, 255, -1948, -732, 367, 1373, -211, 608, - 345, -17, 43, 102, 19, -219, 173, -2361, - 130, -862, 637, -103, -589, 219, -1261, -238, - -2528, 1643, -1587, -690, -166, 7, -57, 1221, - 326, 103, -830, 608, 196, -3705, 1103, 568, - -1602, 543, -153, -416, 74, 185, 156, 34, - 1329, -798, -214, -515, 121, -797, 749, 346, - 629, -609, -877, -60, 184, -157, 250, 193, - 4385, 369, -181, -191, -308, -314, -395, -173, - -88, -388, -43, 46, 9, -167, 189, -192, - 6086, -226, -1795, 126, -941, -423, 397, 380, - 461, 319, 364, -194, 433, 1214, -3715, -274, - 9, -327, 212, -375, 130, -917, -63, 1120, - -651, -211, 149, -1128, 265, -73, -4630, 493, - -83, -20, -314, -91, 910, -109, -3, -417, - -109, 374, 357, -2773, 253, -234, -306, -3060, - -762, 53, 476, -299, -89, -2440, -658, -83, - -854, 3770, 374, 552, 450, 51, 346, 887, - -463, 189, 254, 182, 15, -37, -3263, 2594, - -647, -83, 404, 770, 691, -654, -301, 81, - -13, 742, 371, 54, 31, -83, -59, 4196, - 653, 256, -1075, -539, 1084, -1077, 1238, 259, - 20, -191, 854, 179, -47, -1025, -189, 281, - 2556, 1765, 106, -79, 320, -3066, 228, -500, - 1, -183, -46, 220, -233, -50, -98, -261, - -84, -25, -4378, -428, -1395, -582, -619, 443, - -1456, 375, 144, -32, 356, -454, 28, 136, - 5, 247, -1057, 709, -362, 293, 3084, 545, - -2804, -625, 16, -228, -238, 164, -201, -114, - -149, 58, -74, 203, 271, 462, 1037, 159, - -1652, -591, -846, -166, -3272, 710, 773, 824, - -1138, 630, -14, 209, 348, 1476, 322, -371, - 241, 4133, -877, -476, -391, 602, 1259, -1204, - 352, 90, -473, 43, -152, -439, -131, -217, - -1559, -5029, -186, -239, -44, 750, 33, -167, - -211, -67, -91, -143, 124, 32, -16, 8192, - 68, -102, 163, -31, 458, 38, 249, 21, - 157, -63, 36, 49, -22, 89, 9, 153, - 46, 60, -146, -13, -7506, -104, 101, -141, - 25, 165, -84, 219, 53, -182, -94, 46, - -1314, -371, -298, -527, 6, -1955, 52, -714, - -461, 174, 1450, -298, 107, 2965, 250, -65, - 46, -171, 296, -785, -784, 35, 36, 29, - 915, -891, -391, 168, 509, 3763, -1267, -138, - 132, 424, -53, -669, -1491, -927, 712, -638, - -440, -299, 522, 1593, 445, 3234, 547, 498, - 440, 145, -135, -188, -296, 1080, 468, 77, - 176, -315, 221, 4784, -666, 274, 762, -42, - 218, -86, -273, 116, 814, -21, 402, -266, - -392, -425, 1126, -68, 142, 357, 5143, 363, - -224, -198, 115, -221, -262, -736, -2774, -196, - -208, -613, 163, 696, 789, 132, 114, 121, - -3138, 164, 172, -189, 232, 53, 310, -50, - -407, 1207, -474, 249, -806, 21, 20, 72, - -534, 101, -47, -223, -4568, -128, -29, -910, - -254, 105, 3163, -119, -135, 1745, 1744, 1105, - 291, -333, -278, -441, 660, 141, -291, 314, - 149, 142, -121, -7878, -240, -204, 189, 376, - 3, -129, 59, 46, 170, 82, -150, -34, - 67, -110, 635, 148, 256, -2939, 157, -509, - 1439, -2470, 794, -298, 407, 980, 805, 349, - 208, -35, 1009, 1180, -114, 776, -339, -776, - 250, 1951, -557, 172, -395, 795, -3075, -348, - -106, 122, -47, -9, 55, 40, 3002, 421, - 538, -1, -277, -3062, -15, 168, 461, 521, - -525, 413, -196, 159, -3314, -85, 983, 565, - -3113, 38, 79, -172, 20, -228, -520, 346, - 47, 485, -177, 51, 175, 444, 3475, -3416, - -81, 118, 264, -162, 20, -192, -219, -111, - -57, -225, 159, -218, 117, -28, -150, -1100, - -681, 444, -54, -11, -4669, -216, -1151, 858, - 168, -39, 52, 387, 74, -39, -154, 2767, - 307, -132, 531, 175, 906, 14, -129, 49, - -3389, 476, -127, -329, 479, 118, -85, 209, - 4, 227, 154, -2, -238, 263, -24, 553, - -231, 78, 2, -183, 31, 5933, 117, 86, - 386, 359, 153, 101, -784, -553, -13, 256, - -347, -1311, -936, -64, 1718, -444, 168, -590, - -3252, -194, -243, -269, 2096, -994, -1081, 309, - 1003, 290, -66, 306, -3239, -25, 700, 365, - -770, 144, 4, 259, -185, 1493, -158, 726, - -3180, -1683, -119, 45, -493, -205, -1728, -1226, - -235, -87, -88, -87, 1966, 8, 142, 496, - 239, 828, 30, -517, 3150, 2266, 402, -315, - 74, -312, -414, -16, 458, 381, 376, 1287, - 1093, -410, -967, 80, 382, -106, 4419, 445, - 293, -283, 282, 324, -80, -25, 115, -1667, - -756, 1893, -2772, 395, 3, -349, 138, 1094, - 406, 432, 214, -1328, 632, -132, -100, 135, - 1627, 1062, 1026, -1341, 24, -3352, -173, 1265, - 861, -821, -87, -367, 278, 151, -101, -32, - 161, 387, 5778, -564, 492, 83, 324, 29, - -423, 91, -132, 190, -310, -457, -62, -99, - 171, -214, -159, -2500, -693, -1538, -311, -784, - -2422, -498, 1781, 342, -467, -78, 466, -252, - 241, 197, 186, -1039, -190, 346, -1881, -240, - -65, 1438, 1001, -3009, -52, 221, -490, 1224, - -63, -39, 53, 169, 130, 86, -56, -90, - 116, 4, 7098, -5, 61, -172, -65, 160, - -94, -30, -111, 270, -653, 521, -426, 1084, - -1169, -1158, 584, -2499, 2494, -321, 695, 823, - -429, 35, 529, -280, -45, -286, 2997, 207, - -633, -2207, 1708, -298, -413, 673, -1017, 292, - 493, 76, -136, -365, -65, 266, 852, 512, - 791, -129, 1364, -1065, 1371, 383, -524, 505, - 943, 147, 229, 39, -2969, 70, -295, 66, - 2759, -16, -435, -474, -1058, 762, 54, -257, - 560, -3167, -572, -418, -478, 370, 72, -20, - 296, 54, -2683, 550, -15, -155, 2146, -143, - -1144, 463, -117, -1690, -1917, 42, 249, -278, - -319, -513, 544, -2033, -317, -1955, -2646, 1345, - 759, 268, 207, 1243, 256, -32, -45, -750, - -211, -184, 2397, 473, 2572, -489, 260, 389, - -237, 602, -463, 569, 1673, -176, -227, 964, - 203, 130, -269, -190, 1339, -978, 973, 1986, - 1145, 1258, 272, 1779, -436, -1306, 652, 807, - 574, 1401, 53, -183, 1612, -828, -3094, -82, - 1061, 1042, -200, -891, -126, 181, -1324, 549, - 555, -4, -868, 79, 157, -1533, 18, 230, - -1096, -335, -669, -166, 1853, -310, -340, 249, - -954, -594, -2929, 415, 5, 135, -1315, -237, - 1868, 787, 1912, -1100, 1139, -1103, -217, -382, - -654, 2078, 528, 133, -115, -56, -41, -207, - 69, 461, 465, -396, 1725, 1306, -443, -720, - -1600, 1176, 652, -997, -306, -1040, 2258, -75, -}; - -static const int16_t cb4440sm1[] = { - 8192, 96, 214, -395, -106, 291, -401, 305, - -102, 194, -73, 31, 71, -19, -349, 65, - -183, 26, -21, 8154, 107, -136, -37, -35, - 85, 127, -202, 43, -195, 225, -51, -69, - -57, -107, 141, -120, -284, -227, 28, 680, - 218, 29, -1800, 488, -207, -453, -99, -3680, - -210, 39, 279, 1406, 278, -37, -1596, 232, - 376, 90, 234, -3348, 242, 1765, 555, -883, - 118, 115, 48, -116, 2166, -292, 136, 527, - -236, -18, 411, -20, -190, -480, 665, 3332, - 378, -287, 337, 199, -5, -3904, 311, -297, - -2720, -193, -17, 911, -224, 457, -48, 254, - 271, -24, -77, 165, 23, 182, -1122, 122, - -520, 309, -3604, -1013, -405, -647, -145, -1162, - 1019, -190, -278, 69, 362, -185, -78, -245, - 472, 670, -493, 620, 76, 717, -2296, -111, - -454, 3224, 27, 47, -351, -154, -293, 187, - -93, 96, 87, -453, -132, 9, 125, -209, - -26, 284, -552, 255, 87, 227, -5445, 112, - 172, -15, -448, 475, -5747, 367, 149, -228, - -797, 371, 67, -102, -118, -418, 332, 38, - -100, 90, -183, -3302, 15, -1049, -1560, 1299, - -710, 1257, 698, 316, -283, 955, 240, 182, - 269, 12, -37, 1817, 649, -1273, -2071, -1719, - -765, 977, -1159, 351, -1583, -85, -771, -215, - 123, 314, -158, 32, 560, 208, 265, -451, - -413, 32, 1954, -3598, -1680, -832, -646, 761, - 272, 394, 213, -35, -44, 343, 309, 244, - 3041, -399, -50, -126, -2755, -146, 243, -367, - -600, -166, -832, -537, 269, -48, 2419, -526, - -309, -17, -235, 73, 341, 351, -840, 3241, - -94, -432, 404, -588, 158, -127, -49, 3259, - 3543, 134, -256, -106, 622, -45, -170, -109, - 68, 377, -84, 210, -250, -267, 257, -77, - 6, -1109, -1498, -327, 1063, 992, 632, -245, - -656, -1100, -60, -456, -170, 3208, -6, 13, - -95, 606, -594, -2039, -369, -1743, 275, -93, - 117, 2828, -138, -108, 206, 1819, 98, -45, - 45, -163, 2962, -398, 3536, -183, -259, -581, - 65, -498, -288, -357, -339, -13, -71, -409, - 36, -15, -545, 1433, 135, -220, 99, 752, - 177, -455, -251, 1172, -1274, 1062, -774, -999, - -63, -2756, 99, -86, 4695, -171, -129, -856, - 26, -543, 610, -1350, -2, 271, 455, -150, - 358, 101, 536, 125, 101, 88, -16, -12, - 488, -7479, 110, 264, 140, -302, 110, 232, - 0, 15, 70, -28, -27, -110, -99, 201, - 78, 215, -108, -267, -7548, 34, 312, -86, - 197, 125, 80, -75, -117, -2, 128, -207, - -131, -513, 614, 33, -4844, -302, -323, 160, - 808, 645, 243, -603, 68, -70, 158, -131, - -212, -34, -247, 625, 134, -42, 525, -89, - 31, 116, -1, 508, 5021, 395, 111, -86, - -172, 1433, -114, -126, -148, -337, -260, 233, - -479, 275, -247, -5672, 386, -110, -99, -142, - -171, -154, -358, 30, 1028, -78, 575, 523, - -586, -739, 1586, 1076, -2519, 1572, -1448, -201, - 166, -54, 137, 1268, 1157, -411, -2905, 195, - 489, -740, 154, 522, 2276, -604, 194, -1112, - 192, 400, -271, 250, 413, 273, 158, -299, - -874, -228, -2454, 162, 819, 457, 3401, 689, - -208, -298, -461, -360, -70, -2133, -114, -124, - 81, -228, 625, 3525, 909, 254, -234, 1316, - -773, 531, -30, -16, -164, -84, 2360, -1900, - 351, -2979, 545, 653, 416, 273, -79, -825, - -107, 71, 495, 223, -176, 129, 40, 424, - 1627, 207, 47, -8, -273, -715, 60, -1253, - 1501, -1199, -248, 39, 2859, -432, 89, 299, - 948, -2608, -896, 3468, 84, 511, 55, 151, - 733, 270, -354, 470, -219, -115, -105, 91, - -259, 1941, 775, 12, 2764, 484, 557, 2288, - -118, 294, -32, 719, -62, -64, -295, -82, - -145, -285, -492, 87, -135, -98, 194, -288, - -8, 263, -475, -53, -388, 5621, 41, -28, - 34, -323, 138, 1935, -1806, -185, 340, 1380, - 48, -542, -2965, -339, 88, 554, 41, 4, - -151, 182, -39, -193, -3355, -312, 3106, -203, - 442, -110, 317, -269, 225, 31, -62, -277, - 163, -766, -408, 210, -58, 128, 161, 3308, - 3321, -138, -278, -149, 216, 134, -253, -135, - -154, -123, 254, 200, -2, 133, -307, -6253, - 310, -6, 959, 26, 191, 315, 528, -75, - -230, -203, 153, -265, -94, -61, -2, 2761, - -4623, -353, -19, 102, -139, 54, 438, 267, - -73, 447, 226, 71, -19, 75, -40, -32, - -850, -500, 422, 1237, -688, 357, -3158, -468, - -450, -279, -694, -1109, 734, -1602, -117, 122, - 261, 979, -20, 385, -2929, 342, -3164, -146, - 252, -104, 62, 469, 289, 249, -214, -38, - 73, 83, -7, 18, -394, -5, -140, -267, - 331, -147, 6540, 395, -103, -147, -271, -20, - 191, 73, -155, 197, 71, 503, 19, 138, - -129, 335, 209, 75, -6207, 140, -176, -5, - 35, -40, -61, -146, 1080, 58, 327, -49, - -842, 1431, 595, 3461, 1, 142, 2001, 297, - -16, -425, 1156, -101, -54, 1060, -222, -295, - 938, -1212, -2374, 73, -272, -3318, -8, -718, - 114, -154, 85, -9, 72, 86, -1330, 226, - -1414, -521, 3161, -1856, 133, 240, -499, -371, - -745, 779, -463, -506, 463, -229, -226, 389, - 135, -4137, 360, 735, -318, 777, 593, 977, - -174, 286, 187, -95, -1626, 245, 97, 9, - 277, 299, 1568, 1066, 375, 1342, -390, 884, - 271, 185, -258, -1100, 2113, -107, -447, -1917, - -58, -29, 1081, -455, -524, -196, 1869, -677, - -3564, 1443, 29, -425, -28, -370, -342, -28, - 30, -118, 58, 607, 454, 45, -120, 232, - 20, 21, -175, -112, -236, 492, 411, 42, - -42, 4041, 39, -2579, 235, -146, 122, 24, - 1301, 123, -461, -3264, 316, -88, -209, 140, - 387, -430, 78, 508, 149, -3588, 1107, 820, - -140, 654, 812, -566, -2578, -403, -72, 120, - 355, -136, -121, 209, 240, 116, 231, 1630, - 208, -178, -3160, 2203, -52, 451, 84, -310, - -1199, 596, 69, 285, 242, 15, 49, 341, - -154, -2286, 1206, -109, 1048, -647, 1127, 98, - -1264, -808, 1744, -1597, 13, 26, -216, 263, - 3276, 3192, -105, -390, -31, 676, 73, 265, - 31, 101, 479, -69, 123, -24, -49, 32, - -653, 2253, 49, -346, 1476, 1820, 396, 639, - -219, 792, 1728, 147, -765, -140, 1181, 98, - 153, -98, -755, 2473, 452, 231, 2031, 2468, - -416, 587, 724, 148, 500, -933, -229, 55, - 102, 74, -164, 652, -425, 100, -2684, 1358, - 1626, -350, 544, -301, -1589, -305, -1266, 11, - 243, -125, -330, 294, 1471, -2922, 1581, -546, - 582, 231, -1407, -877, 602, 219, 350, 1130, - -86, 214, -56, 201, -181, -2140, 1108, 493, - 456, -542, -113, -852, 1647, 1897, 840, -1178, - -369, 788, 488, 256, 366, 2298, 1167, -205, - 256, 585, -555, 292, 2615, 748, -247, -1102, - -1682, 226, 415, 20, 27, 100, 9, 436, - -1746, 2621, 1583, -211, -833, 441, 54, -1183, - -826, -916, -707, 564, -232, -14, 147, 453, - 70, 1094, -903, -337, 450, -1546, -662, -1047, - -2345, -811, -1037, 96, 560, 1381, -119, -383, -}; - -static const int16_t cb4448sl0[] = { - -3850, -1289, -449, -36, -1178, -1175, 705, -97, - 37, -650, 426, -477, -145, 124, 6, 207, - -96, -3145, 2917, -260, 349, 668, -72, 6, - 157, -62, -128, 20, -82, -1357, -707, -619, - -313, -229, 3010, -169, -27, 738, 971, -1450, - 246, 154, -163, -15, -93, 5, -35, -42, - 24, 31, -25, 6803, 33, -32, -68, -68, - -44, 317, 43, -106, 608, -999, -699, 582, - 46, 1631, 830, -1570, -2645, 992, 2126, 132, - 2377, 1551, 247, -247, 1508, -34, 162, -275, - -81, -654, -625, 125, -33, -210, 309, 900, - 571, 726, 2691, 2821, -698, 60, 46, -483, - 14, -210, -295, 102, 214, 226, 2622, -82, - -390, 1436, 107, 554, 381, 1307, 2283, -190, - 27, -35, 5557, 283, 103, 180, 104, -89, - -186, -319, -225, -141, 92, 1, -1942, 1025, - 906, 32, -3, -1089, 182, -799, 483, -368, - -1734, -103, 1680, 474, -133, -1067, -545, -219, - -118, -635, -2559, 1002, 2554, -640, -505, 179, - -344, -81, 107, -61, 79, -12, -29, -37, - -7574, -92, 64, 92, -164, -20, -61, -35, - -312, -159, 333, -3401, -2596, -344, 88, 604, - 535, -87, 365, -13, -77, 131, 127, 588, - 302, -94, -506, 2427, 99, 304, 2653, -1104, - 1380, 976, -530, -120, -105, 293, 9, -826, - 388, -66, 421, -202, 605, 675, 4060, 978, - 143, -94, 21, -2444, -30, 554, 695, 2878, - 657, -104, -435, -326, 307, 20, 20, 159, - 106, -3473, 326, -1029, -304, 670, -2109, -431, - 573, 704, 293, -45, -169, -119, -191, 599, - -910, 1976, -165, 581, 1209, -1689, 2365, -370, - -601, -696, 374, 202, -114, -61, 3, -63, - 30, 369, -158, -128, 198, 52, -98, -44, - -323, -5118, -1100, -669, 2256, 32, -66, 206, - 65, 2801, 783, -470, -973, 471, -211, -27, - 1879, 302, -388, -249, 301, 537, 2761, 321, - 571, 20, 337, 1336, 522, 231, 368, -363, - -2065, -57, -2565, -584, -611, 56, 814, -382, - 1671, 408, 492, 12, 1201, 1513, 247, 2165, - -592, -1246, -493, -1012, -1330, 1251, 75, -100, - 182, 52, -47, 710, -1137, 2420, -559, 266, - -801, 2523, 1229, 736, -409, -49, 269, -174, - -179, -24, 348, -661, 251, -1039, 2647, 283, - 728, -1850, -2088, 196, 39, -72, -35, -94, - -540, 266, 340, -450, 763, -5, 113, 2618, - -2737, 1047, -246, -522, -182, 376, 1068, 203, - 1238, -938, 211, -308, -395, -629, 596, -2634, - 1452, -1155, 83, -89, -3121, 419, 40, 2691, - -306, -343, 4, -347, -725, -117, -315, 115, - -215, 26, 429, 1074, -1831, -1850, 2609, 72, - 467, 191, 432, 857, -186, 0, -443, -24, - 500, 541, 30, 2324, -1160, -1153, 1783, 1282, - -1992, 101, -108, -108, 556, -2012, 506, 691, - -65, -610, 402, 610, 1941, -121, 942, 589, - 1879, 58, 312, -2218, -2056, -2284, -350, -453, - 306, 38, -579, -185, -101, -196, -150, 156, - 126, -44, -143, -7923, 126, -120, -138, -233, - 97, -20, -121, -175, -8, -13, -123, -365, - 251, 730, 2883, 667, -418, -208, 2170, -1442, - 196, -389, -516, 252, -98, 525, -1819, -647, - 1575, 768, 1124, -428, -1010, -2027, 411, -473, - 863, 210, 908, 40, 145, 37, 192, 189, - 52, -217, -168, 63, -7, -53, -121, 13, - -145, 0, -37, 61, -7979, -142, 32, 118, - 190, -7, -13, 113, 36, 31, 1461, -2088, - 2391, -939, -66, 822, 280, 246, -157, -183, - -433, -356, 88, -101, 3969, -3388, -84, 84, - 130, 35, 74, 37, 181, -195, 219, -29, - -23, -32, 69, 625, 2328, -192, -2617, 287, - 543, -1604, 823, -547, -277, 764, 276, 156, - 198, 17, 84, 346, -27, -129, 143, 217, - 212, -249, 20, 6449, 7, 51, -889, -88, - 265, 282, -1956, 1327, -1025, 1338, -1709, -1008, - 372, 57, 1404, 234, 2621, -18, 663, 301, - 0, 167, -372, -2534, 1945, -191, 198, 359, - -43, 92, 24, -5498, -63, 189, 36, -369, - 352, 381, -205, -144, -119, -267, -60, -10, - 387, 2388, -155, -450, 465, 1529, -216, 2673, - -146, 118, 50, 290, 147, 11, -2912, 863, - 2184, -689, -44, 59, -663, 663, 675, 295, - 1331, -115, -10, -54, -1, 31, 1699, 127, - 215, 2966, 163, 416, -1053, 1216, 356, 1428, - -166, -172, -2, -355, -169, -331, -94, -78, - -123, 4875, 311, 67, 1145, 397, -288, 212, - -344, -290, 126, 16, 176, 485, 551, -526, - 11, 120, -274, 83, -5399, -154, -1611, 887, - 321, -446, 1166, -333, 652, 310, -895, 62, - -219, 2840, -753, -34, -3203, -3600, 464, -249, - 336, 297, -85, 316, 144, 306, -249, 149, - 112, 73, 192, -89, 18, 197, 116, 51, - 37, 212, -7248, 163, 31, -52, -31, -101, - -1366, -353, -325, -1335, -440, 1193, 670, -2635, - 872, 1400, 733, 395, 122, 130, -4146, 0, - -382, 1486, 308, 1179, -412, 288, 701, 161, - 147, 959, 60, 77, -123, 17, 193, 204, - -226, 388, 272, -588, -157, 2823, 735, -745, - 2368, 359, -1088, -2004, -1293, 2018, 483, 320, - -1014, -806, -479, -68, -51, 168, 873, 27, - -7906, 57, 19, -23, 27, 43, -13, -50, - 93, 16, 29, 31, -26, 32, -22, 453, - 2922, -2560, 138, 923, -1245, -405, 10, 228, - -270, 145, -192, 83, 48, 101, 77, -226, - 36, 7792, 126, -275, -37, -36, 9, 45, - -89, 13, 148, 125, 24, -442, 111, -12, - 540, 1794, 3008, 1620, -185, -1394, -161, -25, - -313, -317, 591, 2507, 134, -369, 77, 527, - -619, -236, 2681, 87, -1060, -34, 1894, -1123, - 373, -628, 1934, -1279, -1689, -609, -472, -598, - 405, 229, 414, 12, -2923, -33, -435, -49, - 2380, -34, -344, -2171, -284, 274, 226, -287, - -84, -57, -1, -169, -50, 479, 707, -2774, - -532, -640, -244, 44, 458, 2519, -590, -472, -}; - -static const int16_t cb4448sl1[] = { - -2878, -714, 3098, -76, -51, 232, 118, -780, - -691, -267, -309, 105, -179, -5, -84, -11, - -120, -379, 458, -3161, 65, 2994, 64, 374, - -440, 62, -183, 28, -561, 73, 59, -2565, - 445, -451, -1026, 437, 10, -173, 1243, -2278, - -481, -395, -154, -2402, 945, -2789, 117, -1184, - 75, -704, 527, 478, -589, 17, 131, -110, - 574, -1055, -628, -277, 2798, 1483, -657, -1996, - -248, 194, -284, 822, 225, -170, -10, -302, - -427, -1700, -90, 2756, 2124, -49, -964, 372, - -637, 443, 13, -69, -71, 196, -1971, 110, - 1147, 698, 1333, 1369, 527, 165, 903, 577, - -2134, 56, -33, 34, 183, 247, -342, 974, - 1079, 2478, -26, 80, -2377, 430, -1422, 428, - -2187, -469, -1280, -326, -40, 188, 911, 405, - 2772, 279, -493, 265, 768, 45, 5778, 44, - 121, -257, -135, 124, 263, 15, 197, -114, - 5, -14, -8, -82, 3989, -511, 197, 2446, - -292, -205, -919, 162, -121, 145, -40, 71, - -105, 72, 2035, 960, -145, -467, -518, 167, - -2988, 421, 860, 320, 40, -446, 319, 160, - 140, 511, -55, 213, -148, -527, -666, 687, - 9, 23, 344, -156, -4646, -125, -220, 9, - 134, -25, 16, -1319, 763, 58, -1586, -438, - 301, -411, -337, -3398, 358, -68, -111, 5483, - -36, -456, -94, -116, 204, 95, 84, -73, - -163, 69, -190, 64, -3716, -326, 1815, -843, - 312, -498, 684, -641, -766, -104, 606, 70, - 2630, 51, -170, -3584, 167, 461, -162, 132, - 496, 91, 171, 255, 48, 2, -120, -1196, - 534, -431, 2669, -403, 8, 287, -391, 2557, - 849, 167, -275, -184, 605, -3570, 113, 22, - -2586, 668, 294, -910, 67, -141, 0, 418, - 271, 75, 90, -124, 446, -142, -635, 631, - -956, 1566, 25, -1982, 790, 2770, 33, -520, - 23, -7488, 67, -73, 60, 64, -46, -36, - 76, 3, 22, 149, 61, 34, 255, -380, - -284, -2531, -1423, 1507, -926, -1074, -929, -1430, - -141, 165, -80, -268, 21, -767, 1542, 3197, - -191, 2014, -304, 595, 536, -906, -126, -354, - -76, -162, -125, -3139, 3197, 934, 366, -923, - -330, 277, -284, -163, -12, 402, 15, -146, - 20, 83, 111, 196, 23, 71, 77, 7287, - -175, -13, -227, -59, -56, -28, 1, 163, - -50, 59, 635, 150, 95, 2750, 775, -2057, - 423, -1078, 1749, -3, -655, -365, -357, 145, - -76, 5, -93, 224, 150, 108, -34, 173, - 148, -371, 34, 48, -8037, 65, 50, 103, - -42, -10, -96, -90, -3, 60, 92, -79, - -76, 386, 114, -1947, 833, -1279, -484, 217, - 3156, 226, 485, 1191, 425, 88, -59, -243, - 2292, 1681, 671, 62, 899, -2453, -100, 1039, - 713, -104, 554, 219, 356, 963, 741, -102, - 455, 2067, -324, 172, 28, 772, 752, -2351, - -1438, -865, -1668, 105, 1034, 1195, 14, -350, - -425, -648, 2086, -532, 634, 1537, -33, -598, - 2888, -85, 184, 158, -164, 3339, 237, -284, - -54, -246, 46, -254, 365, 55, 1928, -346, - -357, 331, 139, 16, 674, -384, -67, -3399, - 165, 76, 215, 137, -3187, -146, -264, -165, - -3039, 235, -541, -630, -32, -33, -211, 160, - -121, -111, -1296, -47, -128, 292, -1523, 1540, - 771, -166, -509, 212, 2758, -327, -418, -305, - -9, 465, 2513, 195, -70, -209, -66, 127, - -147, -3161, -192, -541, -555, 131, -858, -1609, - 973, -156, -1877, 60, 1011, 66, -348, 912, - -1731, -1296, 305, -369, -560, 470, 46, -863, - -124, -37, 40, -395, -4886, -20, 221, 228, - 177, 182, 98, -151, -195, 854, -194, -374, - 301, 586, 58, -908, -19, -4198, -171, 330, - 48, -3312, -164, 1913, 1183, -42, 1287, -353, - 757, 620, -547, 251, -520, 59, 43, -179, - -191, -131, -2951, -944, -2479, 344, -813, 104, - -697, -44, -270, 198, 245, 2866, 208, 178, - -248, 38, 19, 577, 2812, -765, -855, -439, - -60, -30, -352, 1521, -1069, 457, 415, 572, - -749, -144, 100, 515, -794, -1554, 2507, -270, - 10, 62, 2507, -1550, -75, 70, 2530, 562, - 132, -141, 251, 156, 835, 102, 717, 3226, - 3327, 172, 84, -205, -11, 208, -310, 164, - -27, 11, 281, 37, -518, 20, -76, 82, - 5436, -543, -301, 112, 359, -140, -94, 78, - -18, 38, -196, -92, 13, -111, -23, 30, - -15, -94, 101, 142, -6455, 321, 322, 50, - -216, -321, -10, -465, 101, 45, -585, -969, - 1248, -456, -2523, -852, -2129, -889, 33, -1424, - 1462, 583, 749, 527, -1737, 1262, -594, 414, - -215, -1184, 412, 1758, -1836, 1248, 440, -178, - 784, 3591, -227, 43, -493, -766, -270, 150, - 151, -56, -110, -2832, -73, -166, 470, -179, - -681, 71, -114, -2743, -806, -560, 63, -244, - -90, 182, -143, 995, 404, -13, -1343, 1524, - -2472, 1718, -957, 1229, 458, -395, -2817, -579, - -99, 340, 1538, 684, -492, 1156, -45, -65, - -305, -1408, -325, -270, -358, -127, 92, -97, - 415, 85, -4749, 173, -296, -203, 331, 315, - 184, -46, 1315, -146, -55, 427, 37, 255, - -209, 272, 735, 506, 105, 103, 902, -3449, - 116, 2304, 616, -1564, 1508, 478, 320, -2418, - 244, -176, -32, 238, 92, 290, -168, -78, - -3464, 270, -1902, 2, 696, 92, -1610, -206, - -49, 178, 121, 27, 119, 72, -253, -398, - -2720, -81, -162, -550, 2595, 1445, 249, -104, - 218, -310, -95, 18, -473, 1908, 432, -227, - -168, -2725, -240, -1830, 199, 437, -1392, 304, - 1461, -2394, -603, -540, 769, 340, -104, 1569, - -21, 338, -874, 1533, 281, -59, 487, 2120, - 179, -140, -328, -57, 63, -110, -1330, -485, - -2427, 1159, 355, -26, -2055, 154, -563, -132, - 49, -329, -187, -24, -71, -3970, 276, 158, - 92, -202, 7, -422, -578, 186, -407, 4960, - -595, 1027, 417, 691, 69, 133, 123, -147, -}; - -static const int16_t cb4448ss0[] = { - -2680, 2499, -328, 2212, 1288, -57, -727, 76, - -210, -218, 41, -343, -26, -38, 43, 606, - -619, -531, -2082, 87, -1127, 1282, -23, 2272, - -1816, 104, -31, 85, -22, 60, 1293, 138, - 382, 432, 489, -372, -1649, -2809, -2556, -98, - -232, -233, 169, 186, 79, 1157, 2113, -942, - 636, 877, -601, 2277, 1411, 1165, 1029, -613, - -348, -38, -19, 45, 1318, -1980, 12, 2762, - 1519, 184, 1980, -49, -270, 361, -172, -601, - -196, 186, -67, -124, 1503, -1011, 263, 223, - -384, 153, -21, -1063, -239, 1171, -3501, 512, - -162, -180, 139, -680, 609, -1919, 2969, -2321, - -183, 194, -558, 26, 91, 340, -25, -31, - 127, 662, 182, 191, -2201, -2603, 2252, -523, - 277, 50, 355, 295, -65, 355, 207, 82, - -489, -143, -218, 89, 666, -359, 2716, -2310, - -1912, 417, 400, 43, 110, -93, -142, 61, - -3000, 454, -153, 0, -413, 469, 339, 318, - -197, 75, -80, 2894, -129, 82, 1431, 1183, - 429, -1556, -1339, -1573, -92, -911, -230, -12, - -4, -145, -388, -419, -5, -241, 7120, 165, - -125, -122, 126, -150, 109, -146, -61, -49, - 47, 70, -43, 40, 1867, 1473, -1278, 1229, - -2256, -90, 10, -744, 1196, -109, 402, 258, - 690, -74, 26, 1294, -1079, 142, -2384, -324, - -1696, -2741, 321, 66, 83, -127, -131, 156, - 166, 135, 1812, -3445, 10, 535, -547, 481, - -2243, 287, -335, 218, 195, -1, -25, -94, - 195, 1433, -1428, -1444, 520, 219, 3363, -388, - -807, -454, -29, 316, 125, 159, -144, -156, - -317, 752, 256, 216, 340, 488, 147, -5662, - 55, -110, 387, -102, -211, -66, -26, 3688, - -172, -2366, -244, -5, 353, 11, 503, 88, - 227, 69, -240, -187, -58, -389, -1783, -1427, - 20, -618, 544, -1337, 628, -3180, 708, -538, - -423, 115, 49, -161, 184, -682, -223, 689, - 1299, -891, -1073, -1228, -305, 47, -2221, -1559, - 598, -380, 166, 143, -366, 287, 2122, 509, - 629, 235, 1523, 2900, -640, -425, -462, -231, - -53, -27, -263, 2090, -1892, -1147, -42, 866, - -2301, 461, -1082, -625, -85, 148, 229, -25, - 85, 53, 259, -81, -4072, 2577, -12, -7, - 335, -151, -691, -137, 98, 372, -37, -192, - -17, 3318, -558, 2064, 396, 258, -1067, 229, - 1122, 298, -25, 40, 27, -134, -166, -247, - -2010, -440, 1066, -1400, -3454, -289, 428, 629, - -158, 126, 129, 183, -12, -171, -120, 421, - -445, 66, -900, 3680, 1583, 1985, 25, 229, - -535, -1, 45, 207, -54, -30, 1581, -938, - -703, 405, 878, -398, -1069, 1748, -2587, -1419, - -375, -441, -487, 109, 21, -1399, 648, -271, - -701, 635, 115, -138, -458, -600, -1891, 585, - 420, -1916, 1135, 7, 1584, 910, 4267, 1328, - 279, 395, -35, -99, -168, 503, 216, -126, - 211, 212, 193, -2205, 491, 696, 41, 283, - 649, -3425, -999, 200, 625, -261, -378, -47, - -15, -30, -1262, 1700, -2191, 196, -1773, -251, - 84, 498, -261, 150, 451, 41, 336, 27, - -56, 562, -86, -1, -1073, 1461, 2148, -2961, - -326, -257, 440, -42, -48, -320, 122, 94, - -1267, -830, 2810, -94, -201, 990, 2415, -740, - -166, -267, -157, 68, 301, 290, 65, 931, - 1969, -170, 6, 149, -272, -105, 542, -11, - -3888, 105, 305, 333, -14, -39, 1944, -1164, - 88, 3829, -1190, -535, -644, -330, 509, -93, - -314, -228, -294, -342, -26, 1143, -2371, -400, - 74, 101, -68, -583, -1091, 3367, 1146, -638, - -436, 136, 41, -92, 1518, 2818, -2214, -2044, - 636, -2, 79, -508, 676, -439, -358, -198, - -69, 271, 59, 1638, 468, 97, 264, -8, - -5152, -152, 152, 252, 401, -375, -17, -132, - 51, 63, 633, -180, 367, 111, -18, 15, - -52, 128, -54, 11, 96, -122, -26, -7257, - -42, -1221, -688, 197, -107, -217, 141, -289, - 141, 269, 439, -747, -3743, 2098, 226, 137, - 26, -1645, -1735, -80, 43, -216, 245, 544, - 157, 40, 238, 237, -989, 379, 88, 639, - -1335, 1542, 1147, -510, 1008, -134, -626, 696, - -3034, 334, -689, 115, -168, 39, 1750, -649, - -233, -99, -231, 515, 112, -11, -162, -133, - -138, -486, -4137, 204, -102, 867, -1030, 219, - -254, -2787, -128, 961, -2837, -482, -195, 691, - -170, -178, 164, -54, -2008, -116, 74, 398, - -96, -472, 407, 27, 287, 628, 97, -1425, - -3923, 6, 117, -1081, 930, 396, 452, 87, - -441, -155, -738, 1089, 2128, -3133, -21, -622, - -48, -127, 506, 985, -200, 3361, 184, -522, - 41, 503, 209, 14, -96, 791, 1263, 289, - -101, -1728, -1073, -517, 4156, -685, 214, -721, - -608, -102, -295, -114, 126, -340, 109, 88, - -1588, 82, -549, -376, 76, 84, -210, 59, - -130, 321, 678, 4704, 564, -1, 100, 325, - -296, 256, -936, -886, -1088, -191, 476, -3684, - 1359, 12, -397, -70, -17, 58, 569, 353, - 821, -77, 253, 153, 5697, -171, 181, 3, - -90, -413, -265, 142, 62, 959, 151, -103, - 845, -340, -280, -733, -592, -244, 2534, 3089, - 935, -393, -105, 145, -666, -2865, -1532, 717, - 2867, 206, -800, -125, -34, -189, -138, 42, - 189, -141, 107, -3030, -3795, -494, 108, -149, - 382, 760, -142, 337, -844, 228, 124, 232, - -23, -1, 2298, 750, 636, -353, 157, 676, - -191, 812, 3434, 759, 543, -17, -213, -95, - 316, -693, -604, -1059, 32, -496, -3334, -272, - -104, -495, -130, 627, -376, 74, -599, 55, - -2185, -968, 517, -343, 21, -249, -963, 268, - 3339, 239, 771, -134, 42, 231, 75, 1633, - 331, -125, -414, 457, -316, 111, -475, 363, - -687, -4105, 469, 443, 113, 72, 1498, 406, - 915, -229, 564, -377, 89, 137, 39, 2, - -29, -416, -149, 3598, -253, 12, -1015, 3016, - 916, -726, -2286, -99, -1085, -238, 690, -44, - -51, -115, 25, 56, -905, -3050, -1121, -24, - -2160, -1424, 1009, -180, -424, 188, -417, -66, - -86, 74, -28, -225, -937, -90, 251, -1850, - 1939, 1843, 833, -1879, -192, -318, 103, -363, - -22, -57, -2833, -118, -277, -98, -85, -495, - -874, 3027, -141, -1490, -172, -266, -32, 190, - -12, -364, -380, -2107, 249, -217, 662, -584, - 89, -563, 1153, -3091, -656, 463, 144, -26, -}; - -static const int16_t cb4448ss1[] = { - 6475, -60, 162, 42, -71, 50, -85, -278, - -14, -60, -53, 132, 28, -65, -71, -62, - 6, 119, 195, -140, 28, 37, -603, -4956, - -290, 700, -241, 11, -301, 297, -1009, 468, - 885, 192, 40, 495, 846, -28, 201, -255, - 927, -644, 2424, 2882, -82, -1764, 1077, 315, - 946, 843, 399, 176, 567, 546, 377, 283, - 2469, -1815, -65, 12, 422, -368, -639, -493, - -5606, 84, 122, 241, 267, -8, -257, -23, - -220, -118, 139, -1582, -218, -2436, 2539, -270, - 146, -262, -489, 1551, 604, -225, 363, 234, - -110, -166, 1058, 2342, 1950, 43, 2362, -1189, - 492, 172, -296, 159, -430, -311, -135, -182, - 77, -444, -1995, -855, 2080, -457, 389, 872, - 2549, 935, -128, 519, -374, 310, 96, 119, - -263, 1981, -1019, -628, 212, -173, -2292, 1066, - -1985, -426, 115, -746, 147, 3, 94, 195, - -1762, 1713, -337, 1884, -123, -480, 95, 777, - 1073, 2117, -969, 16, 11, 123, 374, -394, - -1419, 829, 1657, 1294, -2770, 286, 813, -290, - -115, 111, 312, 53, 44, 896, 34, -2288, - -3443, -2053, 98, 293, 429, -168, 74, -58, - 221, -383, 100, 63, 1925, -1207, 199, 94, - -94, 3060, 1825, 611, 292, -141, 382, 141, - 105, -151, 0, 1448, -267, 206, 932, -682, - 251, -183, 1080, 161, 4334, -397, 525, -91, - 127, -104, 921, -2282, -274, -1070, 387, -312, - 1380, 2769, -554, 1501, -921, 102, -183, -104, - -66, -1656, 2049, 122, -2271, 84, -276, -204, - 353, 380, -414, -1757, -1035, -318, -130, -10, - 163, -471, 2425, 2864, -1892, 294, 817, 754, - 277, -29, -214, -39, -312, -57, -54, 986, - 2286, -574, 34, -641, 3783, 214, -399, -155, - 38, -148, -42, -89, 97, -17, -2192, 729, - 272, 1168, -3593, 150, 96, -473, 211, -60, - 136, -26, 142, -285, 93, 666, -465, -181, - 2016, -338, -2186, -2608, -449, 107, -18, 45, - 24, 245, -119, 244, 442, 1509, 158, 242, - 169, -16, -221, 104, 115, 16, -217, 23, - -25, 130, 4076, 662, -315, 3068, -35, 36, - 2785, -223, -528, -157, 43, 186, -514, -240, - 15, -245, 520, -110, -781, -641, 294, -20, - 64, -44, 400, -109, 4756, 1334, -421, -195, - 130, -2182, 64, -897, -1423, 3081, -523, 378, - -164, 968, 593, -192, 71, 114, -143, -10, - 1961, -3141, 3173, -39, -110, -57, 144, -68, - -429, 30, -10, 467, 159, 40, 67, 260, - 814, -168, -836, 1073, -3562, 1786, -1205, -148, - -105, 94, 5, 143, 138, 18, -1384, 20, - 635, -126, -71, -87, -320, -407, 559, -151, - 1312, -4395, -755, -263, -77, 1657, 699, 426, - 469, -469, 253, -80, 317, -71, 268, 3592, - -2051, 304, 157, 43, 1872, 3794, -1537, 1226, - -159, -335, 340, -385, -253, -195, 21, 106, - -31, -187, -63, -2771, 446, -708, 202, -186, - 548, 832, 1757, -1274, 1234, -756, -160, 76, - -82, 64, 2169, 13, -849, 244, -2486, -2138, - 844, -178, 270, 297, 150, 202, -41, -188, - 121, -1272, 371, -319, 2848, -469, -2059, 1290, - -457, -380, 690, 148, -51, -340, 113, 57, - -1259, -396, -1404, 336, -511, 576, 4441, 124, - 143, -483, 85, 138, 196, 38, -188, 1177, - -764, -2067, 820, -264, 218, -300, -501, -230, - -2529, 1349, -1606, -199, 92, -55, -1324, -702, - 2078, -1269, 414, -50, 29, 12, 87, -593, - 217, -82, 94, -2392, 308, 2315, 2188, 768, - -1103, -77, 579, 1706, -826, -224, -297, 145, - -640, 570, 146, -199, 1187, -872, 327, -310, - -122, -23, -13, 808, -139, -4425, -670, 412, - -4, -70, -162, -1056, 685, -312, -957, 339, - 893, -252, 4040, -105, 76, 993, 281, -79, - -139, 168, -298, 795, -1107, 395, 386, -524, - 1052, -2341, 2537, 474, 726, -1028, -357, -52, - 115, -9, 1349, -2240, 785, 2751, 77, 922, - 385, -539, -148, 410, 251, -70, 199, 51, - 1728, -206, 1181, 1182, 1388, -791, 121, -3, - 8, -147, -95, 101, 886, -2412, 19, 2401, - -116, 718, -592, -221, 724, -33, 690, -180, - 868, -3330, 377, -336, 128, 267, -2075, 2848, - 2994, -300, 3, -153, 41, -456, 38, -31, - 309, -106, -92, -14, 96, 672, 634, 207, - 1556, 438, -2147, 282, 2443, -1662, 511, 457, - -259, -505, 173, -204, -858, -117, 2751, 852, - 220, -512, -2576, 1542, 357, -77, -4, 165, - -63, 189, 302, -699, -764, -1559, 25, -233, - 405, 173, 698, -73, -300, -1442, -2923, -1326, - -25, 98, -196, -2915, -1169, -3392, 691, 353, - -196, 96, 41, 180, 198, 280, 207, -158, - -19, 1556, 991, -523, -280, -1599, 1368, -3247, - -996, 159, -136, -469, -48, 0, 30, 95, - -765, 33, 6580, -180, 316, -176, 105, -21, - -9, 166, 148, -52, -49, 42, 2, 318, - -55, -91, -1461, -1474, -3086, -756, 1479, -29, - -668, -255, -51, 241, 249, -212, 132, -129, - -410, 113, 17, 301, 185, 96, 10, 188, - 38, -772, 5152, -13, -10, 1527, 806, -23, - -79, 1102, -77, 329, -99, -404, 2276, -873, - -2681, -765, 71, 20, -2448, -803, 1827, 1115, - -160, -15, 288, -46, 573, 100, -726, -694, - -406, 288, 61, -2216, -904, 77, -2983, -962, - -1438, 809, -38, -79, 95, 52, -231, 518, - 115, 41, 908, 780, 805, -207, -2161, 554, - 968, 3111, 133, -158, -13, -34, -182, -60, - 105, 718, -1245, 227, -818, 1184, 903, 603, - -988, -2647, 1847, 141, 817, -337, 131, 393, - 1653, 839, -261, 466, 465, -297, 1440, -431, - 2058, -1857, -1416, 310, -722, -54, 203, -266, - 3770, 172, -593, -73, -508, -61, 1110, 1261, - 275, 1681, 447, -147, -95, 33, 1281, -3119, - 24, -308, 366, -468, 232, 358, 667, -942, - 696, -924, -2059, -62, 151, -2102, 332, 258, - -186, -636, 685, 214, -3174, -1243, 573, -276, - 9, -262, -20, 158, -174, -21, 593, -6198, - -266, -270, -63, -203, 63, -396, -100, 191, - 212, 85, 120, -791, 37, -47, 2108, 652, - 519, 346, 106, -1840, -2566, -563, 14, 266, - 10, 214, 504, -1269, 50, 164, 120, -105, - -546, -212, -79, 41, -171, 675, -252, 4373, - -16, -1697, -1491, -3588, -587, 623, 67, 269, - 484, -25, 1067, 580, -598, 195, 47, -17, -}; - -static const int16_t cb4448sm0[] = { - -5114, 166, -785, 635, -528, -102, 269, 492, - -185, -614, 122, -124, 85, 145, 270, -154, - 39, 2524, 58, -57, 119, 5, 343, 2873, - -278, -787, 137, 62, -169, 2049, 1476, -325, - 130, -702, 2882, -19, 310, -258, -135, 88, - -268, 69, 69, 695, -1935, 815, 678, 44, - 3085, 278, -587, -1326, 360, 145, -17, 66, - -2475, -594, 132, 358, 406, -369, -237, 3363, - 329, -424, 52, 49, 291, -236, -2332, -261, - 49, -27, 170, 3656, -214, -603, 264, 60, - -87, 145, 116, 179, 190, 679, 339, -340, - 3272, 641, -2631, 484, 159, 305, 290, 208, - 226, 68, 102, -145, -356, 153, 647, -2046, - 937, -1666, 1093, -29, -1161, 749, -2360, 171, - -2185, 841, -1406, -1057, -1764, -300, -205, 452, - 2168, -214, -153, 291, -106, 79, 1717, -20, - -1771, 286, -466, 686, 167, 137, 5, 43, - 1075, -2601, 261, -86, -333, -724, 162, 186, - 4, -334, -412, -309, 888, -114, 531, 297, - 4284, 297, -1695, -212, 75, -263, -2313, 102, - -434, 352, -1813, -472, 114, -185, 6, 66, - 8061, 414, -577, 672, -152, 152, 1, 38, - -66, 48, -35, 62, -98, -19, -3762, 98, - 242, 114, 359, -162, 115, -3038, 340, 253, - -526, -144, 14, -147, 28, -352, -5858, 46, - -597, -392, 226, -54, -70, -47, -45, 16, - 53, 137, 172, -3017, -22, -163, -267, -3289, - -31, -174, 110, 794, 425, 67, 58, -72, - -156, 3937, -585, 2116, 99, -1115, -257, 801, - 270, -329, -257, -18, 122, -369, -2196, 1746, - -305, 599, 800, 749, 1466, -299, -1519, -255, - -233, 217, -117, -256, 301, -249, -327, 5530, - 86, 135, -784, -137, 610, -7, 55, 93, - -106, -50, 267, -229, -26, -1070, 13, -75, - 1733, 2929, -130, -713, 15, -2144, 104, -318, - 282, -8, -285, -468, -124, 59, 520, -78, - -332, -654, -5048, 212, -388, 97, -1523, 227, - -2545, 2159, -127, 1020, 79, -664, 403, -31, - -356, -1, -436, -86, 75, 610, 3048, 235, - -3133, -1189, -44, -23, -324, 260, 469, -113, - 22, 53, 525, 427, 469, 1016, 420, 493, - -1229, -238, -2671, 361, -2745, 193, -253, -59, - 15, 53, -57, 36, -144, 127, 25, 11, - -34, 6560, -12, -80, -72, 70, 654, -1135, - 158, 279, 298, 746, -190, -1382, 138, 527, - -1504, -2753, -106, -55, 225, 54, 136, 53, - 506, 174, 268, -533, -43, -416, -196, 6266, - -81, 22, -158, 350, 1177, -728, 594, 34, - -368, -226, -584, 247, 804, -1141, 78, 3923, - -53, 309, 58, -45, -7634, -73, 39, -152, - 55, -77, -45, -62, -25, -247, -161, 28, - -2629, -401, -295, -687, 298, -3240, 0, -251, - 7, -49, 494, -198, 202, 2201, -301, 83, - 45, -964, 256, -1499, -2394, 24, -267, -599, - 46, 161, -370, 81, 636, 3146, -2077, -964, - 322, 400, -635, -688, -630, -92, -235, 104, - -77, -541, 511, 2722, 441, 2757, 952, 739, - -257, -254, -438, -122, -151, 12, 578, -92, - -440, -63, 93, 4971, -499, 419, 1374, -165, - -417, 64, -13, -235, 1080, -77, 536, 68, - -842, -772, 1627, -471, -1350, -144, 2849, 219, - 114, 68, -55, 350, -11, -1334, -3042, 1166, - -147, -891, -483, 1461, 339, 808, 362, -101, - -2807, -24, -377, 518, -438, 194, -110, 194, - -826, 3380, -81, -30, -43, 103, -99, 1539, - -614, -13, -1154, 196, -3122, -521, 1454, -319, - 159, -428, 722, -208, 162, 1871, 2534, 2287, - 946, 261, -483, -645, 26, -170, -31, 17, - 164, 104, -44, -8192, -20, 94, -235, 56, - 68, -58, 380, -25, -170, 17, 16, -154, - 63, 477, 1280, 614, -529, -2347, -360, 159, - 1967, -2085, 485, 335, 378, 178, 1633, -437, - -46, 23, 640, 1465, -91, 1279, -1025, -1007, - -236, 2632, -257, 262, 177, 3029, -3149, -1001, - 231, -262, 87, -243, -68, -597, 109, 62, - -264, 37, -463, -3105, -633, 881, 1026, -86, - 417, 705, -1144, -68, -2084, 46, 124, -36, - -2461, -73, -126, -303, 1079, -358, -2764, -761, - -1454, -245, 203, 0, -179, -117, 2571, -4751, - -20, 194, 298, 258, 390, 270, -36, 182, - 152, -56, -97, -47, 138, -233, -111, -1490, - -490, -329, 662, -320, -4697, 443, 66, 352, - 203, -114, -119, 186, 649, -106, -5, 2280, - 1132, -376, 1168, 919, 1858, 271, -1741, -130, - -3388, 264, 618, -2375, 260, 1279, 110, 732, - 128, -373, 54, -182, 99, -131, 9, 30, - -83, 27, 204, 109, -306, 6903, 130, -7, - -115, 92, -241, 119, -640, -871, -40, 372, - -68, -147, -1503, -58, 920, -466, 311, 144, - -3648, -121, -357, 5, 1968, -737, -1491, 596, - 818, 122, 688, -137, -2415, -368, 236, 71, - -597, -193, -395, 795, 855, 657, -49, 844, - -3320, -1921, 846, 17, -293, -17, -1676, -1826, - -138, 897, -207, -3, 1838, -901, 86, 275, - 964, 230, 510, -10, 2879, 3949, 332, 289, - 109, -229, 18, 238, 244, 287, 44, 103, - 367, 21, -1134, -378, 1338, -828, 3500, 5, - 1027, 475, 208, 654, 589, -92, 236, -85, - -115, 1095, -2504, 827, -885, -806, -155, 2112, - -346, 1120, -350, -911, -234, 231, 55, 87, - 1957, 601, 755, -1248, 753, -2726, -481, 2038, - 96, -363, 309, 150, 299, -561, -698, -1030, - 118, 1224, 3240, -1523, 1476, 342, -688, -76, - 192, -8, -319, 350, 149, -331, 155, -436, - 286, -994, 160, -2696, -423, -2798, -135, -108, - -2846, -254, 3590, 350, 130, -810, 463, -123, - 59, -256, 251, -750, -76, -8, -1633, 150, - -931, 1958, 1523, -2527, 239, -287, 172, 332, - -13, 486, 247, -26, 149, 59, 130, 265, - 19, 209, 7220, -23, -99, -69, -66, -70, - -54, -75, 60, -264, -102, 1079, -535, 1587, - -557, -1499, 241, -2596, 1157, -140, 270, 33, -}; - -static const int16_t cb4448sm1[] = { - 7894, -331, 383, -556, 63, -371, -23, 73, - 46, -145, 105, 43, -199, -52, -85, -85, - 13, -21, -230, 7379, 268, -243, -460, 251, - 73, 12, 115, -18, -247, 433, -90, -518, - 962, 0, -960, 184, -305, -2003, 276, 1696, - 2418, 270, -2140, -215, -534, -389, -403, -3500, - 416, 567, -393, -183, 253, -100, -285, -107, - 100, 281, -527, -2944, -86, 2652, 311, -785, - -811, -283, 425, -77, 393, 136, 170, 1290, - -765, 108, 676, -213, -1226, -470, 427, 3499, - 616, -1211, -226, -37, 88, -2792, 351, 78, - -2975, 99, 192, 1390, -338, 47, -8, 58, - -255, 50, 221, -49, -788, -207, -2122, -167, - -692, 379, -3239, -965, -698, -463, -45, 34, - 1785, 1026, -1107, 113, 124, -258, -277, -714, - 2764, -178, -200, 907, -45, -213, -2575, -530, - -112, 3616, -128, 76, -366, -135, -22, -51, - 125, -100, -79, 142, 54, 107, 87, 493, - -34, -221, -448, -243, 994, 845, -4656, -105, - -487, 41, -112, 349, -4328, -72, 513, -112, - -685, -470, -138, -541, 340, -1505, -24, 37, - 169, -405, -434, -2994, -42, -416, -1927, 1551, - -1488, 420, 179, -66, 14, 92, 147, 141, - 497, 404, -412, 2301, 336, -2877, -1845, -948, - -784, 262, -211, 6, -1678, -434, -1433, -727, - 1254, 542, -1430, -302, 1558, 107, 617, -833, - -369, -178, 1682, -2569, -1232, -1556, -87, -178, - 400, -178, -427, -124, -63, 142, -221, 33, - 2880, -227, -356, -466, -3362, -398, -167, 164, - 126, 59, -1, 5, 212, 25, 2062, -462, - -33, -46, 45, -201, 823, -268, -302, 3623, - 389, 382, 136, -30, -64, 2, -600, 3114, - 2720, 273, -588, -235, -313, -141, 37, -28, - 355, 184, -433, -110, -576, -56, 134, -623, - -271, -2529, -2753, 947, 1319, -2, 620, 36, - -412, -1986, 221, -404, 514, 3223, -106, 1497, - -368, -167, -142, -366, -125, 16, 142, -435, - -160, 2845, -153, 470, 387, 3117, -75, -375, - 658, 259, 755, -3, 3744, -517, -1446, -667, - 1372, -1692, 117, -96, 195, -201, -134, -76, - 179, 97, 71, 1887, 161, 365, 228, 1177, - 235, -834, -48, 1667, -1123, 2217, -209, 100, - -219, -2778, 81, -579, 3421, -326, -492, -233, - 78, 32, 117, -74, -80, 85, -282, 453, - 500, 721, 800, 83, -624, 1000, 165, -20, - -516, -4193, -334, 107, 1221, -1507, -10, 523, - 85, -44, 21, 34, 199, -106, -2233, 525, - 2138, 40, -55, -63, -8179, 326, 333, -152, - -27, 137, 212, 130, -10, 76, -61, -113, - -544, -179, -187, 0, -5308, 322, -326, 513, - 415, 375, -92, -354, 69, 77, 65, 93, - -352, -165, -1837, 1790, 914, -276, 2215, -1418, - 343, 281, 4, 283, 4398, 1695, -248, 153, - -166, 751, 822, -406, -456, -251, 185, -251, - -222, -169, -266, -6323, 249, -40, -45, -203, - 47, -83, -621, -174, 327, 30, 114, -29, - -505, -224, 1804, 1582, -2292, 2102, -746, -421, - 170, 438, -171, 153, 84, -157, -2937, -123, - -81, -227, -98, 263, 3531, 36, 105, -479, - -94, -357, -22, -124, 279, -116, 543, 201, - -393, -226, -2255, -133, 1613, -123, 2687, 70, - 191, 240, -996, -676, 606, -1245, -306, 413, - -272, -539, 485, 3583, -224, 432, 389, 31, - -888, 318, -149, -228, 764, -426, 1608, -2656, - 254, -2193, 252, 484, -90, -117, -257, -2210, - -156, 553, 559, 680, 298, -16, -519, 1172, - 2172, 1288, -113, 186, -199, -1415, -83, -1984, - 667, -1013, 344, -399, 2889, -1175, -908, 186, - 185, -22, -328, 3132, -1166, 209, -213, 386, - 2140, 552, 1023, 719, 529, -169, 421, 196, - 76, 1995, 532, -75, 2060, -526, 396, 2974, - -264, -348, 149, 586, 22, 97, -337, -252, - 357, 103, -2308, -2578, -1836, -277, 346, -314, - -989, 185, -314, 102, 56, 3779, -265, -1029, - -12, -126, -431, 356, -2493, -86, 172, 116, - 61, -146, -2220, 211, -165, 233, -327, 73, - -7, -104, -546, 253, -2406, 361, 2252, 486, - 675, -177, 2643, 603, 300, 1123, -642, 361, - 684, -2151, 569, -1014, 120, -50, 321, 3174, - 3080, -733, -427, 299, 169, -123, -140, -13, - -315, 21, -120, -24, 174, -191, -350, -7842, - -145, -169, -419, -15, 150, -130, -73, 162, - -9, 38, -287, 109, 390, 147, 151, 1907, - -4243, 7, -207, -147, -230, -343, -117, -111, - 107, 132, 1457, -88, -8, -445, -176, -172, - -1799, -813, 486, 1150, -3026, -168, -2620, -584, - 178, -543, -1868, -359, -113, -1783, 214, -663, - 473, 866, -136, 169, -3324, -129, -3404, -249, - 234, 422, 251, 340, -343, 231, 134, -42, - 32, 64, -209, 12, 236, -267, -419, 1, - 260, -109, 6508, 105, 7, -273, -123, -107, - -152, -274, -157, 75, 74, -201, 46, 37, - 338, -21, -180, 208, -6417, 794, 250, -81, - -585, 4, -119, -314, 529, 219, 159, -132, - -277, 76, -613, 4933, 15, 213, 2461, 286, - 542, 177, 2767, 389, 136, 750, 559, -994, - 684, -12, -2081, -546, -89, -3733, 548, -620, - 675, 118, -121, 190, -52, 19, -19, 25, - -1224, 344, 3094, -2067, 7, 273, -1268, -375, - -297, -201, 271, -191, 123, 6, -260, 2284, - -308, -3062, 242, 668, -221, 1146, 1218, 473, - -133, 82, 57, 112, -1677, 78, -229, 354, - -463, 763, 1628, 2243, 1386, 1630, -145, 255, - -60, 228, 195, -864, 2539, -466, 985, -3075, - 2, 118, 221, -395, -450, -256, -158, -32, - -3829, 2012, -50, -465, 146, -1091, -318, 271, - -12, 596, 160, 120, 92, -209, -335, 104, - -28, 689, 305, -548, -849, 1617, 605, 185, - -414, 3899, -273, 51, 182, -192, 121, 616, - 1219, 414, -959, -4219, 1319, 60, 246, -468, - -32, 225, 338, -39, 1235, -2079, 2250, 626, - 121, 296, -137, -339, -1870, -47, -397, 124, -}; - -static const int16_t fcb8l[] = { - -1239, -1310, -1240, -1146, -1337, 1303, -482, 2215, - 2026, 2222, -1144, -1188, -1209, 2535, -1111, -844, - 1485, 625, 1254, 1204, 5932, -1116, -1235, -1208, - -801, -1020, -558, 1387, 1513, -1079, 3220, -896, - -1083, -1166, 2246, -1210, -838, -950, -960, 764, - 13941, -1307, -817, -1253, 1850, -1320, -1361, -1218, - -671, 780, -839, -1068, -776, 2977, -714, -944, - -823, -580, 357, 591, 302, -1078, -895, -1020, - 3116, -1144, 1438, -891, -71, 1528, -238, -1297, - -1020, 4616, -1185, -514, -1154, -1157, 1901, 2372, - -1131, -1289, -1273, -1289, -1311, -1331, -1340, 439, - 455, 2395, -537, -1180, 2409, -1084, -580, 1937, - 846, -51, 615, 1099, 3854, -1177, -912, -1095, - 656, -995, -647, 3298, -976, -436, 12323, -1291, - -1187, -1341, 4779, -1368, -1357, -1317, -985, 1407, - -513, -1387, -1224, -1069, -1218, -1117, -181, -1209, - 5376, 4256, -22, -1232, -1173, -834, -1054, -947, - -611, -822, -206, 5572, -988, 1067, -837, 738, - -332, -38, -59, 143, 248, 386, -447, -1233, - -1258, -1169, 3653, -1045, -657, -926, 2004, 2201, - -1164, 7042, -1302, -1313, -812, 150, -129, 305, - 442, 742, -1185, -1293, -1220, -872, -1304, -1260, - -853, -1293, 2962, 3011, -178, -1187, -1087, -896, - -895, -1053, 3788, 59, -169, 1632, -1201, -1289, - 5263, -896, 331, -852, 218, 825, 1129, 1024, - -39, -1186, -1054, 1862, -1198, 2010, -1075, -1005, - 702, 1550, 4491, -1055, -890, -645, -987, 2465, - 529, 194, -72, 370, 1547, -968, -849, -1153, - 6459, -1164, -1061, -1020, -838, 125, 3698, -1168, - -1066, 1882, -1159, -439, -1017, -759, 744, 1302, - -812, -985, -1002, -1029, -871, 3690, -170, 604, - 623, 1272, 6135, -1012, -1231, -1066, -927, -1082, - 2393, -843, 1537, 1240, -866, -1161, -866, 6639, - -994, -860, -264, -298, 469, 1184, -868, -1262, - 2167, -1177, 2132, -987, -563, 969, 1145, 1508, - -735, -1232, -1090, -1204, 1507, -1101, -393, 755, - 975, 1246, 1944, -1068, -1169, -1040, -987, -1301, - 5488, -1057, 3150, 1890, -1133, 2725, -1123, -963, - 1901, 260, -484, 449, 564, 1144, 679, -1118, - -989, -702, -556, 162, 689, 712, 673, 443, - -695, -1247, -1019, -1065, -406, -1143, 1750, -743, - 2644, 2402, -1171, -1157, -1059, -823, -688, 1314, - 1458, 629, 857, 856, -875, -1316, 3470, -1061, - -846, -761, -712, -955, 978, 1967, -980, 3517, - -994, -953, -903, 56, 228, -30, 359, 560, - 9926, -1178, -1056, -627, -952, -481, -1168, -268, - -701, -555, -887, -1212, 1768, -1156, -396, -755, - -119, 1594, 949, 1201, -844, 1734, 1312, -331, - -500, -280, -125, -219, -139, 496, -1121, -1227, - -1145, -215, -1123, -765, -173, 4055, 1086, 1465, - -714, -904, -901, -713, -1073, 1233, -797, 645, - 58, 897, -518, -624, -441, -554, 1139, 549, - 147, 72, 127, 428, -1104, -979, 2433, 1867, - -237, -745, -280, 110, 794, 631, -1049, 1141, - -974, -920, -849, -392, 634, 414, 614, 797, - -1162, -1344, -1192, -1259, -1079, -912, 2717, 2548, - 1847, 1920, -1004, -1091, -1006, -692, -85, -24, - 1014, 1427, 751, -584, 6057, -1206, -1072, -795, - -921, -1103, -1157, -623, -818, 2641, 3121, -1084, - -1095, -939, -664, -694, 884, 555, 144, 593, - -874, -1074, 417, -1027, -6, -790, 1687, 80, - 1018, 738, -527, -958, -701, -377, -4, 155, - 304, -348, -947, -342, 2269, -1040, 1124, -494, - -76, 76, 2, 114, -194, 348, 904, 466, - -577, -717, 107, -39, -29, 158, 101, 149, - -968, -921, 558, -264, -445, 138, -121, -33, - 105, 243, -478, -1047, -937, -751, -609, -822, - -709, -976, -1006, 2800, -1108, -1292, -1055, -1272, - -1295, -1152, 305, -1144, 635, 2067, -584, -1135, - -663, -1130, -754, -1009, -937, -515, 1473, 841, - -1235, -1338, -1305, -1141, -1109, -1217, -238, 1915, - 3550, 2306, -963, -985, -874, 763, -826, -694, - 19, 391, 379, 776, -582, -1216, -1285, -1164, - -1276, -1305, -1273, 2631, -579, 2487, 1058, -655, - -808, -878, -910, -1006, -1122, -590, -663, 428, - 2185, -1125, -1032, -1076, -873, -1139, -1029, -477, - 1720, 1238, -1111, -1311, -1343, 1074, -1328, -1181, - -970, -386, 2359, 1777, -1045, -1189, -1117, -1053, - -942, -329, 501, 1237, 808, 1022, -866, -1048, - -678, 1597, 1528, -262, -256, 231, 418, 728, -}; - -static const int16_t fcb8s[] = { - -1022, -858, -773, 304, -881, -771, -341, 937, - 270, 420, -684, -1000, -795, -903, -671, -575, - 14, 3327, 528, 893, 965, -541, -947, -1027, - 4008, -1081, -743, -991, -808, 933, -1406, -1173, - 7513, -824, -213, -797, -648, -40, 176, 217, - -1298, 6743, -755, -232, -440, -680, -269, -60, - -80, -85, -893, -1044, -726, -733, -834, -641, - 231, -779, -501, 1832, -1296, 2548, 2754, 19, - -210, -708, -205, -74, 18, 55, -1225, -1123, - -1239, 6991, -689, 272, -290, 56, 356, 675, - 1623, -1134, -607, 1426, -872, 511, -1060, 408, - 253, 423, 1960, -1337, -1152, -985, -924, 2020, - -398, 348, 4188, 1044, -650, -831, 2909, 2083, - -457, -5, -1037, -964, -128, -40, 6019, -858, - -937, -559, -624, -601, -411, 120, -289, 412, - -1271, -1351, 3858, -1214, 2224, -325, -165, 535, - 559, 386, 1868, 649, 269, 245, -708, -778, - -179, -12, 101, -12, -1235, -892, -829, 2570, - -574, -431, 170, 167, 492, 531, -930, -1093, - -1037, -1177, -1151, -912, -466, 303, 1601, 4089, - -1234, 3160, -631, -1090, -741, -274, 103, 13, - 356, 289, 2709, -1115, -1011, -965, -948, -563, - 1939, 870, 1187, 550, -1028, -1217, -726, -954, - -694, -753, 3729, 141, 518, 854, -1102, 1138, - -947, -620, -379, -436, 72, 449, 432, 428, - -1112, 1276, 544, -334, -445, 179, -32, -37, - 9, 28, -1252, 2983, -963, 1256, 419, -10, - 17, 211, 218, 191, 126, -942, -691, -529, - -533, -193, 1216, 150, 389, 152, -1191, -987, - -942, -860, -463, -705, -159, 184, 1893, 1080, - 1753, -694, -609, -699, 61, 269, -126, 93, - 236, 380, -527, -966, -334, 163, -662, 3295, - -477, 591, 259, 638, 397, 181, -598, -129, - 35, -51, -122, 64, -32, -98, -1351, -1140, - 3372, -753, -776, 718, 513, 134, 420, 354, - -1128, -546, -743, 297, 1819, -77, 179, 17, - 181, 206, -1028, -1027, -757, -755, -389, 1035, - 227, 249, 315, 395, -931, -881, 1207, -777, - -165, -531, -375, 73, 346, 332, -1159, -788, - 1196, 959, -432, -337, 243, 176, 321, -7, -}; - -static const int16_t fcb8m[] = { - -1379, -1331, -1277, -1266, -927, 0, 2552, 2575, - 425, 48, 2568, -26, -841, -762, -679, -562, - -420, 186, 68, 69, -743, -193, 266, 92, - 1714, -241, -357, -93, -252, -222, -884, -385, - 2436, -446, -150, -533, -192, -33, 226, 8, - -756, -1180, -1238, -1258, -1250, -1147, -764, 141, - 3075, 4136, -1255, -1288, -1202, -1188, -1222, -1257, - -500, 1989, 4062, 1328, -300, -186, -399, -329, - -330, -533, -313, 2030, 193, -128, -933, -1016, - 66, 1648, -228, -321, 236, 114, 356, 212, - -677, -826, -784, -670, -484, -423, -188, 215, - 2476, 652, 3424, 1991, 940, -576, -942, -1038, - -1097, -1161, -1120, -956, -763, -416, 2824, 1429, - -693, -755, -455, -670, -535, -225, 4814, 116, - -940, -953, -1008, -856, -797, -582, -531, -213, - -412, 2479, -156, -218, -319, -168, -236, -248, - -305, -515, -224, -382, -501, -759, 139, 1789, - -258, -343, -167, 721, -1014, -1092, -975, -1070, - -1126, -778, -178, 36, 522, 5371, -402, -1351, - -1577, -1662, -1642, -1560, -1249, -870, 602, 8968, - -1126, -1102, -1118, -1072, -946, -511, 482, 1635, - 1108, 2471, -935, -748, -302, -445, -810, -359, - 1433, -83, 336, 1834, -712, -773, -752, -609, - -391, 625, 2550, 403, -447, -18, -261, 91, - 5096, -199, -887, -1018, -728, -930, -921, -684, - -22, 2422, 2118, -417, -757, -789, -732, -794, - -785, -664, -627, 885, 471, 798, -429, -684, - -454, -185, 185, -26, -990, -369, 1048, -25, - -98, 720, 41, -60, -3, -92, -790, -147, - 846, 4007, -346, -907, -849, -730, -639, -842, - 9096, 617, -1164, -1275, -1380, -1396, -1391, -1364, - -1342, -1080, 655, 5687, 505, -818, -1134, -1125, - -1136, -1123, -1088, -996, 3, 36, -48, -28, - 121, -55, 172, -43, 21, -74, 1537, -69, - 378, -38, -113, 159, -149, -609, -693, -796, - -715, 588, 376, -744, -659, -316, 145, 448, - 659, 320, 787, -315, -956, -682, -595, -327, - 146, 348, 837, 577, -1011, -1014, -647, -159, - 679, 158, 294, 670, 507, 540, 418, 558, - 12, -674, -901, -897, -827, -682, 323, 2580, -}; - -static const int16_t fcb8sl[] = { - -1269, -1637, -1349, -1672, -1421, 2750, 212, 3563, - -74, 1555, -1495, -1148, -1172, 1351, -484, -473, - 1418, 557, 899, 635, 6124, -1140, -1154, 783, - -1444, -1509, -1041, 1793, 4459, 1325, 2055, -921, - -794, -713, 1625, -50, 78, -159, 361, 855, - 10282, -1533, -1105, -1582, -1704, -1697, -1440, -1001, - 864, 2038, -1347, -847, -1419, 1474, -1369, -1189, - -1125, -655, -134, 950, -1398, -222, -1498, -1262, - 2597, 729, 2521, -544, 457, 2058, 3821, -1568, - -1577, 2013, -1717, -1620, -1292, 2771, 2559, 4942, - -1497, -1576, -1724, -1550, -1775, -1734, -1097, -635, - 1934, 2706, -1399, -994, 1685, -1142, -511, 1595, - -275, 861, 484, 958, -1374, -764, -1105, -1493, - -1678, -1630, -521, 5138, 53, 1331, 4909, -1376, - 2134, -1638, 1562, -1565, -1487, -1625, 3232, 4742, - -1017, -1353, -1212, -1585, -1309, -1139, -71, -820, - 5928, 2987, -641, -1314, -1198, -1182, -1005, -542, - -1287, -1210, -1103, 6865, -1130, 1375, -884, 1241, - -532, -173, -68, 15, 309, 192, -1128, -1107, - -849, -1343, 2233, -1281, -535, -679, 3878, 1865, - -1427, 4508, -1022, -747, -1117, -1104, -33, 669, - 1216, 1482, -1360, -1075, -1483, -1390, -1366, -754, - -1042, -766, 3467, -624, -968, -1101, -393, -890, - -447, -995, 2346, -909, -784, 977, -1141, -1201, - 5256, -1552, -536, -1419, 0, 596, 556, 1654, - -1124, -1225, -830, 1267, -719, 1791, -546, -297, - 978, 378, 2674, -1261, -1159, -951, -1027, 2537, - -470, -360, -268, 1098, -1154, -1513, -729, -1455, - 5671, -1236, -800, -874, 1630, 1273, 1909, -623, - -724, 1417, -559, -326, -257, -189, 265, 220, - -284, -1302, -1272, -1223, -842, 4338, -934, -1001, - -495, 2944, 4295, -924, -1004, -1097, -1024, -328, - 1736, 106, 452, 158, -1024, -541, -1296, 4376, - -1117, -1224, -843, 1097, 1121, 1251, -829, -1374, - 2292, -1505, 1850, -1153, -943, -979, -534, 1444, - -1510, -1494, -1147, -1397, 1535, -794, -21, 1313, - 638, 1015, -1072, -1275, -1166, -1602, -1618, -1379, - 4541, -226, 2169, 888, -1369, 2392, -1087, -948, - 1074, 674, 384, 124, 500, 749, 398, -1091, - -721, -114, -15, 413, 200, 135, 290, 189, - -1185, -1188, -1339, -1549, -871, -574, 2333, -346, - 554, 3773, -1247, -1531, -1408, -1310, -1007, 2861, - 2465, 608, 1080, 1224, -1103, -1477, 1884, -1412, - -904, -1473, -846, -188, 782, 2049, -1473, 1531, - -1530, -1459, -1546, -1260, -856, 1191, 652, 933, - 5072, -1456, -1653, 3759, -1751, -531, -1391, 4297, - -374, -751, -1570, -1242, 1461, -1286, -913, -621, - 1768, 1246, 1291, 779, -1360, 1641, 1122, -629, - -328, -197, 241, 359, 560, 536, -1474, -506, - -1523, 298, -1551, -1254, -985, 3603, 4317, 958, - -885, -241, -1159, -930, -1249, 1490, -825, 274, - 347, 307, -1060, -1027, -809, -1063, 1554, 1708, - -242, -23, 424, 804, -1317, -853, 1571, 1898, - 239, -556, 298, -161, 777, 765, -1464, 1053, - -1198, -1156, -917, 0, 1460, 447, 1178, 629, - -1455, -1591, 296, -1785, -1694, -1631, 3669, 3819, - 3437, 3274, -956, -666, -874, -284, -858, -202, - -687, 1728, -512, -951, 4692, -1360, -1242, -1188, - -1513, -449, -1566, -1515, -1226, 3857, 1246, -1225, - -860, -1068, -748, -27, 380, 1190, 591, 552, - -1391, 194, -763, -463, 331, -265, 702, 181, - 290, -145, -838, -1359, -1381, -1569, -1399, -1088, - -1357, -1295, -486, -612, 1638, -586, 1458, -774, - -223, -620, -104, 189, 344, 269, 1555, 1428, - -867, -621, -294, -206, 32, 235, 261, 161, - -1021, -105, 654, -235, -282, -7, 189, -159, - -218, 113, -1096, -1318, -1256, -1335, -931, -476, - -1041, -1199, -1134, 2781, -1479, -1222, -1397, -867, - -815, -661, 740, -240, 1158, 735, -1435, -1003, - 351, -990, -245, -72, -347, -72, 1408, 634, - -1697, -1727, -1534, -1716, -1436, -102, 402, 1518, - 1903, 1311, -1477, -930, -355, 508, -162, 21, - -46, 454, 387, 173, -1312, -1284, -1486, -1172, - -1356, -965, -1106, 1760, -670, 2163, -70, 417, - -559, -667, -545, -945, -429, -363, 157, 1280, - 2059, -1319, -1291, -975, -1354, -1249, -780, -476, - 1410, 1252, -1193, -927, -1462, 871, -1281, -1327, - -900, 1540, 1531, 1227, -1651, -1334, -1073, -752, - -154, 710, 830, 773, 279, 307, -1294, -796, - -761, 1012, 1583, -420, -177, -323, 154, 582, -}; - -static const int16_t fcb8ss[] = { - -1481, -1069, -1082, -726, -818, -550, -417, 343, - 489, 275, -814, -510, -712, -933, -558, -236, - 32, 3051, 451, 301, -414, -237, -683, -599, - 3627, -445, -232, 56, 58, 112, -1226, -639, - 4096, -644, -226, -23, 90, 162, 313, 104, - -1385, 5607, -428, -860, -447, -265, -145, -132, - 115, -200, -1349, -1280, -1216, -1046, -657, 43, - 1333, 831, 675, 1174, -1394, 2288, 1840, -682, - -497, -256, 22, 22, 261, 70, -1369, -826, - -975, 2286, -329, -267, 142, 36, 437, 313, - 1570, 52, -470, 622, -244, -247, -114, 22, - -117, -541, -1167, -596, -809, -929, -669, -327, - 102, 516, 2790, 597, -1317, -870, 1327, 987, - -25, 391, -48, -82, 209, -242, 4424, -311, - -396, -765, -382, -336, -365, -414, -74, -13, - 1127, -588, 1363, -714, 368, -450, -390, -364, - 84, 139, 1864, 1881, -15, -790, -281, -286, - 38, -186, -31, -238, -1249, 262, -841, 731, - -414, -61, -274, 280, 100, 557, -841, -775, - -1007, -1063, -687, -374, -360, 31, 1048, 3471, - -1385, 2464, -840, -1105, -714, -400, 56, 445, - 588, 427, 1785, -1093, -783, -847, 41, -23, - 465, 392, 382, 428, -518, -249, -58, -791, - -689, -581, 3146, -183, 296, 66, -1243, 1059, - -1076, -874, 416, 544, 253, 66, 168, 211, - -1388, 1253, 138, -727, -509, 905, 319, -297, - 67, -525, -1470, 2237, -87, 547, 556, -239, - 90, -147, -114, -302, -1017, -824, -585, 25, - 0, 62, 1422, -155, -41, -320, -1125, -1069, - -1134, -783, 1129, 45, 183, 47, 716, 672, - 409, -1169, -910, -447, -34, 79, 95, 455, - 504, 381, 342, -877, -506, -812, -805, 3031, - -249, -518, -69, 564, 243, 261, -332, -434, - -173, -37, 61, 45, -5, 6, -1433, -1009, - 1428, -951, -582, 154, 143, 625, 383, 387, - -1392, -1222, -578, 229, 1294, 218, -142, 355, - -149, 201, -1341, -1135, -857, -767, -273, 2059, - 255, 578, 350, 315, -1041, -617, 254, -504, - -255, -96, -537, -396, 363, 1074, -1361, 484, - 538, -789, -704, -447, 200, 521, 213, 90, -}; - -static const int16_t fcb8sm[] = { - -1183, -1170, -867, -948, -746, 492, 1531, 1412, - 524, 82, 590, -994, -916, -859, -680, 12, - 742, 961, 230, 255, 34, 38, -176, -1, - 1880, -240, -769, -531, 269, -32, -772, -494, - 757, -583, -677, -281, 717, 440, 561, 91, - -1121, -1054, -1189, -1100, -745, -417, -61, 302, - 3079, 1817, -1384, -1479, -1477, -1509, -1077, -323, - 902, 2348, 1464, 1038, -487, -179, -447, -311, - -296, -439, -172, 2166, 245, -28, -1050, -390, - -238, 633, 302, -335, 843, -52, 185, 230, - -110, -433, -690, 148, 63, -289, -404, -469, - 1948, 245, 2016, 1337, -341, -554, -617, -457, - -436, -459, -400, -520, -661, -7, 1078, 971, - -326, -332, -23, -749, 83, -104, 2106, -947, - -867, -883, -705, -433, -35, 164, 427, 646, - -924, 2196, -656, -798, -282, 217, -227, 134, - 446, -15, -584, 33, 185, -571, -159, 1852, - -405, -94, -61, -83, -329, -516, -394, -450, - -173, -140, -54, -156, 226, 1850, -752, -1304, - -1378, -1275, -1017, -680, -337, 356, 1131, 4143, - -1120, -1253, -1269, -860, 90, 973, 152, 886, - 609, 1454, -29, 36, -117, -815, -651, -346, - 2085, -414, 24, -93, -235, -1103, -1132, -758, - -98, 1497, 1285, -289, -34, 402, -646, 637, - 2147, -677, -350, -266, -232, -61, -199, -359, - 167, 1546, 816, -453, -35, -251, -468, -491, - -371, -593, -878, 1445, -795, 651, 108, -155, - -201, -14, 250, -271, -732, 793, 154, -288, - -86, 16, 557, 642, -592, -587, -87, -365, - -309, 1753, -40, 95, -529, -87, -214, -234, - 4999, -466, -755, -800, -785, -722, -532, -703, - -526, -465, 591, 3937, -229, -804, -808, -698, - -576, -613, -506, -725, 10, 13, -117, -55, - 101, 52, 125, -76, -25, -28, 1469, -245, - 8, -25, 65, -53, -262, -282, -411, -588, - -667, 1374, 304, -787, -661, -675, 55, 320, - 720, -4, 366, -103, -136, -332, -314, -293, - -38, 127, 151, 380, -1330, -1338, -618, -40, - 1284, 1500, 466, -515, 105, -161, 19, 697, - -417, -559, -317, -712, -756, -567, 754, 1481, -}; - -static const int16_t fcb11l[] = { - -1291, -1237, -1175, -1186, -1139, 524, 1225, 1464, - -1042, -721, -901, 41, -728, 822, -657, 1078, - -483, 1530, -489, 1253, 926, -326, 404, 89, - -1191, -1170, -1237, 1633, 1493, -465, 986, 1184, - -857, -832, -300, -811, -936, -667, -254, 492, - 4044, -1136, -983, -855, -592, -199, 383, 876, - 2076, -1042, -1019, -729, 1435, -25, 64, 845, - -991, -921, -861, 916, -402, -551, 236, 429, - 5253, -1233, -1268, -414, 1793, -463, -569, 1693, - -1197, 6322, -887, -211, -945, -540, 626, 903, - -993, 1500, -490, 1445, -764, -136, 321, 548, - 462, -228, 127, -322, 481, -183, 88, 155, - -809, -844, -959, 4011, -581, -232, 330, 986, - -900, -916, -1069, -866, -979, -439, 4016, 1558, - -1023, 2121, 1717, -612, -588, -446, 223, 430, - 2567, -972, 2118, -1030, -900, -664, 180, 858, - 3232, -991, -1132, 2119, -446, -548, -258, 895, - -962, -184, 2639, 1081, -661, -222, 292, 530, - -952, 1767, -213, -701, 1079, 37, 131, 489, - -875, -749, 3167, -776, 1247, -109, -83, 636, - -1146, -1070, -1001, -1064, -942, 2891, 1137, 1585, - -1314, -632, -1179, -1105, 1101, 51, 2038, 2036, - -926, -727, 180, 1515, -566, 1191, 101, 595, - 2247, -364, -315, -105, -130, -79, 121, 210, - 7994, -1302, -898, -785, -758, -777, 31, 415, - 744, -652, 688, 1226, -649, -605, -268, 314, - 611, 662, -240, -411, -698, -434, 377, 339, - 953, -810, -931, 1054, -484, -298, 721, 522, - 922, -1046, -952, -871, -618, -270, 419, 635, - 1006, 129, -838, -724, 220, 481, 253, 329, - 205, -456, -724, 675, 598, 332, -14, 291, - -1016, -695, 542, 1270, 498, -456, -113, 362, - -547, -1068, -1178, -1261, -1161, -905, 390, 2204, - -1056, -1102, 5611, -1100, -1076, -902, 360, 978, - -538, -286, 1253, -430, -457, -148, -1, -60, - -1116, -955, 2869, -926, -680, 1111, 706, 842, - -1311, -1275, -1150, -236, 675, 897, 758, 912, - 1886, -1115, -999, -84, -588, 2190, -171, 739, - -737, 150, -902, -854, -917, 334, 557, 534, - -851, -39, -25, 214, -136, -73, 263, 234, - -1021, 1332, -543, -655, -712, -651, 80, 479, - 1555, 1933, -707, -485, -206, 139, 312, 405, - 2472, -1172, -945, -939, -713, 568, 1421, 684, - 70, -1263, -1235, 586, -195, -1065, -449, 3182, - -1143, 529, -926, -558, 419, 390, 375, 563, - -1090, 3370, -688, -528, -346, 136, 317, 615, - -803, -977, -1082, -806, 3607, -443, -156, 1130, - -1288, 1585, -1218, -1226, -979, 359, 1555, 1402, - -341, -416, -480, -360, -415, 542, -148, -322, - -1095, -1074, 762, -864, -634, 1770, 340, 466, - -1040, -834, 1508, -707, 143, 74, 1418, 905, - -1094, -710, -549, -860, 373, 1492, 2024, 741, - -938, -910, 2661, -1087, -1105, -901, 383, 906, - 755, -819, 581, -612, -420, 305, 344, 363, - -356, -991, -845, -1051, 2112, 1738, 554, 954, - -1028, -943, -892, -896, -236, -674, 1076, 679, - -611, -1099, -859, -914, -444, 910, 491, 709, - -1063, 775, 496, -669, -304, 672, 261, 496, - -1086, -963, 1037, -639, -134, -577, 33, 607, - -1070, -649, 730, -748, 1884, -18, 346, 627, - -1089, -1118, -955, 751, -690, 606, 1204, 1037, - -1016, -1095, 473, -919, -1036, -685, 1744, 1216, - -834, -916, -920, -634, 1086, -474, 161, 620, - -997, -899, -25, -499, 399, 405, 163, 401, -}; - -static const int16_t fcb11s[] = { - -1148, -1134, -1000, -585, 715, 774, 626, 650, - 2109, -898, -729, -239, -213, 847, 77, 371, - -902, -790, 1853, -871, -816, 163, 295, 377, - 1718, -1070, -840, -791, 1612, -129, 144, 450, - -830, 1909, -539, 803, -411, -188, 122, 148, - 1202, 705, -696, -578, -213, -25, 126, 142, - 3309, -1083, -865, -771, -470, -237, 980, 521, - 428, -995, -1003, 3088, -1000, -455, 320, 503, - -615, 1746, -751, -734, 1092, 31, 97, 225, - -1175, 2287, 1278, -421, -315, 91, 130, 120, - -1203, 4211, -970, -878, -228, 71, 327, 288, - -1012, -850, 1471, -732, 1228, 201, 146, 271, - -868, -528, 1196, 744, -186, 85, 38, 153, - -1081, -895, -742, 1014, 1110, 66, 237, 335, - -1012, -1137, 4357, -1062, -569, 377, 268, 445, - 1203, -717, 1070, -541, -72, -29, 91, 104, - 6448, -1148, -1069, -810, -659, 118, -284, 300, - -1085, -940, -214, -621, -781, -622, 1789, 711, - -1165, 1643, -890, -809, -533, 148, 384, 373, - -910, -986, -855, -1032, 3647, -478, -132, 713, - -3, -674, -1036, -956, -899, 2698, 629, 665, - -764, -1066, -1173, -1058, -692, -144, 1114, 3195, - -1012, -643, -670, 1547, -576, 351, 251, 273, - -950, 563, -742, 248, -149, 514, 100, 185, - -193, -616, -655, 255, -364, -323, 172, 256, - 308, 228, 16, -187, -243, 219, 88, 53, - -1024, 664, 450, -416, -189, -239, 43, 102, - -64, -499, -159, -400, 905, -64, -68, 46, - -1055, -77, -813, -661, 59, -77, 226, 321, - 1224, -553, -436, 793, -155, -83, -5, 72, - -652, -897, -157, -579, -539, 846, 181, 318, - 782, -967, -802, -569, -6, 364, 540, 513, -}; - -static const int16_t fcb11m[] = { - -453, -1087, -1133, -1125, -852, -158, 1152, 3313, - 1015, -444, 1085, -465, -317, -298, -471, -238, - -647, 1426, -241, 149, -300, -169, -19, -228, - 3282, -269, -1025, -1069, -1097, -1071, -539, 1303, - 1111, -933, -741, -801, -553, 98, 393, 1031, - -786, -729, -835, -810, -78, 1569, 631, 944, - 1031, 651, -409, -397, -346, -221, -99, -216, - -88, -211, -419, 193, 1298, 196, -221, -879, - -1036, -1303, -1282, -1052, -575, 283, 3110, 1337, - 489, -463, -640, 112, 341, -322, 261, 266, - 1646, -817, -1256, -1273, -1217, -1031, -142, 3691, - 3012, 1564, -289, -830, -970, -1032, -1075, -989, - 556, 52, -588, -589, -613, -748, -352, 2054, - -69, -785, -718, -499, -141, 192, 1396, 446, - -3, -514, -612, 3, 171, 1067, -114, -109, - -812, -893, -776, -342, 1428, 421, 438, 552, - -933, -1143, -207, 1312, 791, 166, -198, -79, - -632, 1122, -537, -620, 450, 97, -85, 174, - 1760, 123, -168, 485, -77, -567, -776, -952, - -758, -1176, -1322, -1355, -1207, -928, -177, 6229, - -413, 261, -327, -848, -725, -395, 849, 1533, - -201, -124, 2976, -335, -703, -674, -727, -949, - -521, 209, 1004, 838, 56, -477, -751, -603, - -922, -615, 1832, -448, -329, -148, 73, 467, - 4991, -86, -809, -928, -951, -956, -819, -751, - 1841, -790, -712, -116, -113, -91, 0, -388, - -729, -196, 758, -377, 68, 85, 428, -35, - -5, 2, -9, 18, -31, 53, -23, 26, - -896, -445, -188, 818, -347, -44, 502, 578, - 101, 2968, 269, -724, -702, -747, -719, -673, - 7587, 68, -1171, -1377, -1441, -1455, -1473, -1178, - 699, 585, 15, 2257, -503, -940, -1085, -1288, -}; - -static const int16_t fcb11sl[] = { - -1502, -1463, -1336, -1177, -367, 89, 475, 867, - 550, 820, -805, -580, -803, -89, -817, 1691, - -304, 120, 36, 564, 409, -525, -820, 362, - -969, -870, -605, 1983, 993, 722, 1505, 1101, - -842, -848, -918, -379, -71, 257, 499, 607, - 1619, -956, -1024, -869, -744, -74, 795, 684, - 532, 634, -1360, -818, 49, -981, 111, -473, - -718, -477, 377, 710, -1399, -1105, -1152, -1024, - 2426, -356, -191, 1079, 911, 1164, -809, -791, - -919, 2731, -851, -400, -113, 242, 508, 847, - -1229, 1199, -910, 1127, -686, -383, 26, 352, - 536, 646, -790, -1243, -1103, -1170, -1132, -1065, - -788, -521, 161, 3842, -1098, -883, -1052, 8, - -1103, -747, -552, -480, -241, 820, 3392, -770, - -770, -724, -588, -426, -153, 426, 639, 724, - 1626, -713, 1157, -736, -492, -512, -160, 461, - 569, 583, -1351, 1332, -1222, -1358, 240, 1541, - -724, 612, 1583, 1194, -1061, -990, -671, -969, - -952, 2368, -442, -413, 1933, 1023, -144, -283, - -992, -940, 983, -232, 818, 341, 502, 549, - -1420, -1268, -1279, -1213, -621, 2019, 685, 1948, - 1264, 1200, -1293, -664, 392, -848, 866, 1191, - -220, 95, 450, 640, -1334, 1098, -751, -701, - 1296, -347, -92, 233, 532, 599, -952, -694, - 3085, -908, -256, -494, -177, 123, 809, 941, - 18, -1089, -801, 303, -761, 11, 632, 288, - 476, 518, -241, -1138, -1068, -869, 292, 121, - -26, -96, 457, 548, -106, -784, 930, -700, - 1842, -812, -617, -307, 430, 655, -698, 1157, - 947, -803, -662, -743, -49, 1120, 348, 578, - 855, -1049, -753, -67, 710, -347, -28, 694, - 411, 468, -61, 239, 23, -1072, -757, 477, - -658, -362, 239, 576, -1479, -1279, -1286, -677, - -939, -722, 3217, 338, 1562, 1566, 925, 917, - -697, -708, 645, -447, -280, 714, 503, 552, - -1050, -1021, 889, -956, -934, 705, 457, 616, - 556, 667, -1331, -51, -256, -48, -234, 240, - 757, -74, 148, 356, -1278, 1538, 234, -372, - -472, -221, -424, -494, 170, 551, 216, 294, - -885, 231, -263, 334, -64, -54, 291, 350, - -1140, -1074, -1199, -1374, -1278, -845, -547, 667, - 4544, 1922, -899, -930, -954, -1120, -1092, 1156, - 1889, -404, 259, 1114, -956, -836, 881, -316, - -977, -860, 202, -249, 121, 816, -1188, 3644, - -829, -876, -670, -473, -161, 420, 851, 886, - -1014, 1191, -938, -958, -864, 741, 241, 957, - 288, 629, -1155, -898, 1104, -789, 28, -867, - -580, 2588, 836, 1234, -953, -749, 934, 1137, - -310, -177, -113, 244, 532, 424, -341, -602, - -880, -1105, -303, -381, -527, 1943, 126, 759, - -1277, -1037, 59, -783, 485, -589, 1341, 737, - 488, 709, -1473, -1208, -1082, 589, 791, 735, - 447, 322, 835, 731, -1116, -681, -592, 704, - 520, -545, -104, -24, 263, 458, 632, -721, - -1086, -1223, -1150, -866, 1537, 2815, 123, 1097, - -1238, -861, -1217, -1238, -1261, -914, 1165, 422, - 711, 883, -1196, -972, -428, -230, 171, 8, - -448, 1195, 445, 440, -413, -139, -375, -568, - -781, -520, 611, -586, 881, 589, -724, 972, - -907, -794, -819, -641, 1650, 66, 254, 703, - -1380, -1168, -967, 676, -765, -537, 578, 1542, - 687, 833, 1151, -811, -948, -995, -246, 1301, - -377, 262, 632, 652, 1530, -679, -682, 993, - -666, -457, -72, -20, 317, 516, 861, -528, - 24, -579, -386, 53, 526, -76, 66, 345, - -59, -612, 165, -181, -98, -34, -66, 286, - 95, 108, -1118, -147, 643, -1055, -768, -502, - -587, 27, 2113, 811, -1219, -947, -811, -1188, - 1143, -609, -753, 88, 2844, 1424, -1428, -1082, - -1273, 1086, -1206, -1171, 279, -510, 2325, 1757, - -1437, 654, -1278, -1267, -1117, -950, 779, 2205, - 1150, 1101, -1484, -1009, -1199, -1416, -1215, 657, - -737, 634, 1266, 1742, -1445, -1193, -1358, -1158, - -1015, -995, -655, 4035, 1966, 1903, -1069, 954, - -1099, -1171, -1029, -818, -576, -104, 1390, 1069, - 559, -914, -1034, -1152, -987, -582, -222, 394, - 1204, 775, -1464, -51, -959, -1005, -452, 347, - -94, 1, 525, 595, -1324, -1226, -1102, -825, - -927, -776, -582, 175, 1675, 632, -859, 28, - -914, -209, -468, -625, -230, 646, 579, 446, -}; - -static const int16_t fcb11ss[] = { - -1351, -1229, -1174, -767, 1403, 182, 532, 445, - 415, 610, -1095, -771, -1142, 3221, -803, -680, - -302, 318, 441, 438, -1188, 1145, 1552, -528, - 887, -547, -429, 124, 99, 128, -768, 1049, - -562, 1121, -593, -96, -105, 105, 251, 154, - 1684, 1598, -635, -685, -177, -211, -268, 234, - -118, -49, -719, -873, -1092, -985, -678, -406, - -234, 407, 653, 3195, 991, -584, -874, -14, - -683, 2964, -769, -450, 287, 350, 853, -803, - -574, 1761, -410, -60, -230, -78, -21, 19, - -1271, 4435, -673, -790, 110, -243, -81, 147, - 191, 145, 5571, -611, -634, -699, -195, -281, - -249, -302, -272, -67, -893, -656, -745, -697, - -550, -639, -409, 3085, 383, 798, -311, -340, - -564, -787, 3628, -332, -510, -219, 465, 351, - -747, -1084, -972, -727, -404, -630, -176, 437, - 3352, 978, -886, -751, -767, -580, -693, -942, - -803, -158, -36, -3, -966, -674, 3075, -926, - -172, -9, -40, 111, 169, 212, 181, -811, - -715, -986, -521, -686, 3915, 18, -58, 499, - 210, -1187, -903, -915, -522, 1038, 477, 788, - 290, 412, -1010, -791, -700, -710, 34, 1774, - -256, 96, 131, 241, -1251, 2086, -5, -765, - -446, 141, 93, 160, 88, 129, -1153, 1171, - -1192, -1073, -391, -187, 206, 416, 444, 648, - 707, -542, -504, -750, -623, -648, 776, 692, - 165, 330, 1112, -1199, -876, -428, 949, 65, - 250, 104, 108, 173, 2147, -905, -846, -540, - -376, -131, -113, 124, 314, 485, 1253, -515, - 1435, -527, 21, -100, -368, -84, -119, -144, - -1375, -1189, -1189, -999, -723, -190, 796, 639, - 699, 816, -1188, -919, 683, 842, 177, -62, - -25, 71, 15, 16, 157, 80, -331, -343, - 12, 193, -133, -94, -94, -64, -1306, 531, - -917, -142, 1274, 102, -15, 184, 159, 148, - -43, -1103, -581, -419, 447, -132, -204, 187, - 631, 461, -1302, -1162, -927, 896, 203, 164, - -55, 287, 544, 485, -1258, -791, 677, -945, - -244, -101, 423, 362, 298, 389, -825, -640, - -646, 274, -73, -274, 1473, -13, 132, 169, -}; - -static const int16_t fcb11sm[] = { - -767, -1179, -1188, -1069, -690, -172, 787, 1389, - 1623, 844, -169, -894, -919, 51, 15, 426, - -326, 1579, 182, 77, 202, -417, -357, -17, - 2154, -77, -607, -589, -375, -261, -376, 175, - -829, -801, -579, -290, -244, 533, 1307, 873, - -877, -1175, -1157, -726, 461, 1729, 433, 219, - 246, 606, -791, -827, 649, 891, 820, 720, - 407, -641, -727, -708, 2498, 961, -99, -542, - -530, -507, -536, -608, -642, -622, 316, 195, - -721, -549, -253, 1520, 171, -81, -372, -333, - 1166, -1072, -1230, -1123, -1031, -868, -370, 209, - 1561, 1751, 113, -367, 399, -663, -10, -271, - 950, 118, -335, -272, -863, 60, -875, 1850, - -242, -276, -38, -106, 471, 30, 823, -344, - -752, -714, -309, -419, 86, 1604, -250, -185, - -839, -703, -561, -281, 1813, -57, 255, 266, - -32, 99, 400, 2520, 315, -372, -306, -511, - -549, -659, -760, -729, -559, -137, -610, 174, - 924, -310, -705, -307, 885, 512, -611, -1097, - -1172, -1072, -758, -527, -192, 278, 740, 3398, - -1136, 409, -230, -353, -137, 322, 326, 365, - 133, 173, 2291, -644, -725, -596, -535, -340, - -88, -65, -53, 273, -760, -390, -649, 119, - -243, -222, 1726, -113, 44, 326, -618, 311, - 2345, -241, -398, -399, -382, -322, -444, -457, - 1873, -454, -505, 42, 481, 187, -49, -505, - -634, -754, 1052, -597, 1315, 297, -412, -110, - -205, -552, -682, -524, -1055, -431, 971, -363, - -539, -366, 39, 995, 181, 476, 662, 229, - -445, 1682, -205, -181, -273, -497, -685, -628, - 6135, -21, -834, -934, -1002, -1066, -931, -974, - -902, -643, -820, 1891, -706, -288, -252, -231, - -79, 126, 35, 37, 10, -10, -36, -6, - -9, -47, -7, 1, 11, -2, 644, 315, - 145, -353, -396, -428, -357, -60, 275, 109, - -1179, -952, -698, 138, 286, 171, 394, 263, - 814, 495, -490, 110, 369, 599, 9, 599, - -431, -233, -328, -69, 410, -1002, -462, 77, - 97, 196, 133, -91, 512, 49, 621, -436, - -352, -390, -211, -188, -454, -318, 44, 1424, -}; - -static const int16_t fcb16l[] = { - -13, -798, -772, 235, 515, -181, -120, -509, - -392, -1159, -844, -1041, -881, -1193, 1103, -1080, - 214, 1615, 1819, 1510, -914, -1190, -273, -1099, - -522, -996, -206, 3946, 996, 1678, -1220, -1201, - 2850, -1022, 1101, -814, -188, 879, 1549, 1279, - -1129, 1928, 1550, 38, -356, -574, -157, 286, - 481, 475, -1079, -1176, -861, -548, -657, -381, - 538, 948, -838, 779, -1149, -962, 1788, -779, - -742, -311, 205, 299, 472, 715, 702, -843, - -931, -790, -624, -332, 324, 778, 785, 670, - -1137, -1205, -103, -1182, -1071, -950, 101, 527, - 1596, 1004, 682, -564, -1053, -844, -1184, 1732, - -862, 1994, -988, 1131, -1069, -1276, -1053, 6414, - -1259, -186, -930, 118, 375, 1092, 6215, -900, - -920, -935, -981, -970, -766, -902, -334, 1629, - -1094, -1142, -1155, -779, -1092, 1011, -490, 1063, - 1569, 1340, 2242, -1313, 6027, -1319, -1337, -789, - -1296, -457, 819, 2276, -1071, -1065, -715, 802, - -996, 397, 2396, -27, 1225, 935, 1400, -862, - -802, 1846, -513, -249, -704, 515, 872, 662, - -1141, 5876, -691, -404, -603, -148, -57, 187, - 649, 788, -1116, -915, -551, 3843, -737, -133, - 498, 155, 227, 718, 1798, 1397, -868, -716, - -586, -580, -71, -67, 311, 536, 2465, -524, - 1837, -231, -210, 263, 231, -10, -164, -324, - -951, -1130, 5206, -525, -603, -401, 223, 438, - 1011, 1077, -726, -1102, -1013, -386, -786, 4281, - -329, 262, 550, 1292, -629, -943, -976, 773, - -867, 908, -680, -154, 362, 1056, -1051, -703, - -1333, -1424, -1026, -793, -859, -882, -148, 9958, - -1193, -1156, -1077, 1241, -1013, -726, -139, 551, - 1150, 1019, -733, -997, -651, -625, -54, 722, - 73, -14, 361, 435, 4013, -1260, -1195, 1452, - -1105, 1273, -670, 1546, 1038, 1680, -812, -1060, - -853, -1058, 2094, -801, -457, -320, 683, 960, - -1019, -1158, -1118, -1034, -617, 404, 1376, 847, - 1014, 951, -12, -1004, -1221, -1131, 649, -1052, - 442, -167, -859, 3868, -1216, -1298, -1311, 2866, - -1310, -639, -1079, 1576, 1760, 1837, 118, -1080, - -862, -845, -1065, -1069, 2199, -766, 495, 1309, - -996, -1040, -741, 1357, 1726, 382, 264, 92, - 659, 665, -781, -1356, 2055, -1198, 15, 2143, - 631, 569, 918, 1120, -948, -1253, -1234, 2442, - -1062, 2206, 48, 660, 1822, 1480, -639, 627, - -432, -477, 845, 216, 228, 152, 157, 295, - 2444, -908, -465, -768, 109, 251, 72, -59, - 169, 405, 4395, -837, -931, -839, -215, -564, - 655, 359, 503, 296, 3514, -1082, -1185, -827, - 2879, -1224, -811, -970, 804, 911, 3028, -1284, - -688, -1226, -1251, -551, -1247, -275, 3441, 2322, - -630, -1213, -108, -1191, 1129, -854, 2848, 1609, - 1048, 1535, 2784, -1245, 772, -1230, -1298, -686, - -1293, -639, 278, 2455, 9975, -1077, -1233, -1055, - -139, -853, -48, 24, -720, 533, -1191, 2809, - -1015, -899, -28, -765, -147, 146, 592, 814, - 12493, -1274, -1072, -1297, 877, -1068, -1179, -1032, - 1023, -1178, -840, 930, -660, 1216, -366, -406, - -97, 77, 179, 340, -973, -993, 2280, 1775, - -631, -17, -186, 507, 459, 645, 2095, -1019, - -1067, -949, -857, -1202, -904, -48, 1156, 1273, - -1230, -1245, -1203, -1036, -1150, -955, 1193, 1943, - 1437, 1329, -618, -1055, -730, -1014, 4953, -1125, - 1089, 1085, 1047, 1045, 813, -1036, 1270, -715, - -684, -96, -131, 289, 782, 628, -979, 1060, - -975, -964, -811, -14, 223, 422, 563, 696, - -901, -633, 496, -136, 22, -83, -52, 264, - 24, 147, -446, -1197, -1258, -687, -1239, -795, - -1066, -1196, 147, 2653, -1231, -1275, -1240, -1041, - -1260, -1159, 1961, -34, 2937, 2128, -1318, -1355, - -1326, -1300, -1345, -1326, -870, -298, 2014, 3890, - -933, -1014, -859, -1074, -506, -1163, -954, -819, - 440, 732, -582, -1268, -1206, -1037, -1081, -1255, - -1150, -835, 2360, 1469, -1232, -1384, -1388, 542, - -1359, -606, -1335, 1852, 2142, 3722, -1218, -1321, - -1268, -1207, -1203, -1316, -954, -696, 4730, 2920, - -1225, -1306, -1131, -1273, -1276, -1238, -1040, 2079, - 2652, 1931, -1167, -1302, 659, -532, -650, -560, - -1028, 186, 1224, 2811, -896, -449, -999, -823, - -81, -876, 502, -293, 680, 733, -836, -1111, - -1132, -865, -1141, -938, -980, 1287, 581, 1438, -}; - -static const int16_t fcb16s[] = { - 1260, -1427, -1400, -996, -958, -1195, 6261, 31, - 967, 752, 3776, -975, -840, -707, -696, -555, - 45, 1159, 4, 358, 4718, -1471, -1464, -1291, - -1364, -934, -878, 5198, -273, 1555, -1438, -1729, - -1579, -1470, -1820, -1436, -1255, -631, 4287, 4025, - 1233, -684, -748, -742, -547, -229, 321, 126, - 794, 670, 6689, -1041, -1160, -861, -1002, -976, - 147, -668, 521, 940, -1186, 2097, -570, 1759, - -251, -442, -92, 46, 99, 12, -1336, -1061, - 4427, -945, -861, -460, -306, 494, 481, 536, - -1101, -1105, 2695, 316, -801, -159, 1042, -577, - -78, 340, 2347, 1448, 135, -381, -688, -493, - -254, -234, -74, -80, -1047, -1246, -729, -985, - 5399, -1018, 643, 822, 889, 432, -328, -1386, - -1420, -702, -1450, 6927, -1107, 465, 1625, 1116, - -1258, 2847, -893, -895, -521, -263, 112, 157, - 556, 500, 182, -652, -226, 258, -638, -566, - -419, -669, -224, -221, -1197, -227, -582, 92, - 1914, -184, -11, -18, 270, 166, -1294, -62, - 1536, 2470, -413, -619, -399, 24, 106, 54, - -1223, 2672, 2400, -54, -577, -692, -301, -3, - 206, 89, -1424, -1491, 8425, -1072, -242, -420, - -194, -1, 489, 331, -938, -1319, 2493, -1355, - 551, 2297, 197, -9, 717, 434, -1237, -773, - -1021, 3945, -566, 116, 246, 150, 510, 370, - 11804, -457, -1006, -1231, -1175, -1086, -1221, 589, - -679, -757, -1183, 6502, -584, -454, -629, -570, - -413, -352, -279, -32, -1236, -946, -760, 1535, - -865, -712, -224, 343, 647, 613, -1348, -938, - -961, 8273, -1130, -591, -225, 210, 420, 140, - -1247, -1166, -966, -986, -1120, -907, -181, 470, - 1888, 1161, -1076, -1298, 3479, -1151, 2410, -396, - 1, -44, 357, 594, -896, 745, -33, -422, - -332, -259, 0, 48, 143, 190, -1009, -837, - -876, -371, -370, 1520, -150, 251, 240, 448, - -1024, -1008, -568, -450, -611, -536, 1763, -34, - 355, 454, -769, -599, -639, -737, -912, -725, - -504, -230, 532, 3294, -1077, -289, -875, -542, - -574, -604, -339, 2511, 479, 742, -1218, -946, - 1321, -522, -544, -950, -765, 632, 639, 497, -}; - -static const int16_t fcb16m[] = { - -940, -1197, -1190, -1200, -1192, -960, -718, 610, - 3300, 3253, -1515, -1689, -1798, -1798, -1793, -1764, - -1616, 33, 2377, 7778, -668, 1745, 1501, 785, - -336, -823, -708, -446, -455, -812, 8862, 159, - -1141, -1261, -1323, -1299, -1261, -1227, -1214, -1090, - 3584, 2092, 688, -531, -848, -1000, -1047, -1192, - -1104, -887, 5163, -347, -1129, -1285, -1336, -1291, - -1249, -1109, -498, 2511, -611, -703, -516, -240, - -68, 399, 1570, 252, -5, 43, -1163, -1168, - -1008, -921, -995, -569, 925, 1511, 1001, 2023, - 12926, 135, -1598, -1778, -1847, -1850, -1836, -1734, - -1695, -1690, 621, 4647, 588, -752, -973, -996, - -953, -1081, -1060, -672, -868, 259, 4940, -117, - -718, -907, -828, -776, -606, -981, -1002, -526, - -385, 527, 1501, -239, 38, 25, 112, -77, - 1122, -250, -352, -1113, -1101, -942, -681, 5156, - -800, -636, 5814, -160, -777, -825, -844, -747, - -697, -645, -668, -492, -936, 491, -280, 2573, - -269, -736, -375, -265, -98, -243, -920, -236, - 446, 1095, -666, -600, -246, 783, 282, 0, - -1064, -116, 2271, -118, -482, -240, -187, -271, - 36, 91, -695, -254, -383, -948, 745, 2722, - -129, -799, 238, -379, 2872, -516, -868, -623, - -551, -275, 22, 379, -185, -230, 1524, -672, - -1062, -1164, -1177, -1137, -1058, -790, 6, 4928, - -551, -389, -460, -394, -674, -586, -327, -178, - 615, 2868, -1467, -1203, -1316, -1120, -996, 747, - -219, 2023, 1875, 254, -871, -992, -1062, -1110, - -1149, -992, -492, 40, 528, 5374, 83, -559, - -862, -760, -541, 28, 207, 629, 502, 1260, - -473, -1110, -1336, -1390, -1412, -1379, -1329, -1081, - -238, 9844, -1332, -1306, -1275, -881, -1267, -1249, - -237, 2882, 3535, 584, -13, 52, -50, -4, - 7, 5, 20, -55, 5, 45, 1587, 350, - 191, 617, 153, -236, -336, -649, -798, -1063, - 1451, 707, 253, -733, -923, -859, -621, -738, - -555, 1623, 1727, -411, -724, -772, -746, -675, - -688, -209, 915, 622, -1038, -474, -343, -91, - -173, -104, 255, 96, 1547, 773, -625, 2272, - -90, -509, -527, -247, -147, -234, -45, 166, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, -}; - -static const int16_t fcb16sl[] = { - -1337, -1122, -1559, -1452, -1353, -973, 3858, 1145, - 1225, 2103, -607, -181, 557, -429, 15, -496, - -444, -523, -1866, -1134, -1270, 3029, -1110, -798, - -824, -659, 44, 614, 1059, 1173, 714, -932, - -1095, -1061, -921, -1034, -873, 7, -872, 660, - -1335, -1496, -1623, -1405, -1070, -680, 943, 134, - -190, 2837, -1034, -221, -337, -540, -571, -173, - -411, 2314, -111, 970, -1220, -1036, -1096, -147, - 1087, 604, -367, 83, 461, 679, -1333, 194, - -1292, -1139, -1097, -570, -508, -109, 54, 962, - 2592, -1112, -944, -636, -521, 12, 230, 442, - 562, 624, -1107, -1190, 1554, -981, 1507, -1013, - -394, 595, 823, 1094, -1453, -1298, 242, -1185, - -686, -541, 858, 331, 695, 1197, -1259, 968, - -1180, -1254, -752, 1473, 222, 342, 973, 1029, - -1631, -1500, -1619, -1517, -1299, 1683, 2203, 1163, - 1225, 1497, -1189, -937, -931, 3193, -977, -708, - -262, 549, 917, 1465, 704, -565, -708, 846, - -130, -322, -257, 221, 367, 309, -1416, -1123, - -1323, -1260, -405, 3303, -210, 785, 1007, 1616, - -1043, -717, 44, 824, 419, -492, -579, -604, - -15, 676, -1067, -1079, 3897, -1211, -474, -1020, - -589, 114, 593, 1504, -1481, -1249, -1036, -1012, - -719, 846, -189, -297, -31, 1209, -1761, -1566, - -1449, -1645, -1464, 1422, 24, 2153, 1377, 1948, - -1480, 652, -929, -415, -689, -386, 1628, 489, - 487, 756, -1424, -805, 1241, 228, -697, -316, - 423, 660, 557, 587, 1248, -777, 1088, -848, - -498, -399, -60, 169, 497, 689, 5679, -778, - -1109, -1118, -895, -1042, -504, 390, 1670, 469, - 977, -929, -1173, -1058, -999, -696, 1912, 52, - 1297, 1081, -1469, -1243, -1055, 385, -529, 910, - 79, 508, 1225, 753, 656, -1307, -1239, -1470, - -1110, -1255, -362, 2351, 889, 1687, -1566, -1331, - -1410, -1385, 779, -499, -217, 936, 2064, 1493, - -1499, -1345, -1162, 790, -1115, -673, 2083, 1010, - 588, 1265, -1439, -1168, -1294, 752, -1421, -1234, - -169, -529, 1606, 2131, -1556, -1442, -1444, 487, - -1260, -1139, 360, 2528, 1994, 1686, -1548, -1473, - -563, -1125, 967, 1490, 1503, 487, 991, 1024, - -1430, -1151, -1215, -729, -746, -762, -472, 778, - 889, 774, -1329, -1129, 1383, -1230, -723, 1478, - 379, 161, 1266, 1238, -1467, -843, -1277, -1323, - -715, 58, -182, 5140, 762, 1723, -1285, 1134, - -1175, -1057, 1294, -4, -417, 557, 939, 1182, - 39, 565, -809, -703, -783, -883, -112, 412, - 1056, 691, -273, -1334, -898, -1345, -1069, -1247, - -105, 638, 6811, 1157, 982, -856, -805, -1093, - 1267, -747, -650, 311, 281, 1076, 1371, 1614, - -891, -886, -396, -246, -65, 77, 472, 605, - -943, 178, -509, 112, -142, 512, -66, 109, - 144, 76, 2934, -1203, -1428, -1525, -1269, -1618, - -1129, -184, -225, 3157, -249, -1276, -1055, -439, - -161, -268, 284, 614, 778, 670, -1243, 1682, - 919, -468, -479, -341, 31, 468, 325, 606, - -1081, -723, 83, -399, -275, -658, 240, 149, - 2746, 679, -1573, -1287, -494, 775, 975, -751, - -47, 1758, 652, 1155, -1465, -1073, -1087, -1026, - 289, 340, 448, 1348, 351, 682, 2065, -1183, - -1313, -1562, -466, -1546, -1077, -477, 3012, 2512, - -1560, -1532, -1441, -1229, 861, -421, 1515, 2195, - 1163, 1418, -1268, -1103, -804, -1094, 3254, -711, - -558, 713, 1414, 1684, 542, -781, -827, -814, - -245, 1129, -160, 210, 386, 618, -1633, 488, - -1584, -1571, -1349, -662, 711, 1516, 1661, 1673, - -1510, -1530, 1013, -1172, 425, -1415, -856, 2963, - 2258, 1919, -744, -1208, -863, -634, -729, -1068, - -857, -289, 701, 6703, -1502, -1353, -1531, -1372, - -1388, -1067, 1392, 100, 2570, 1703, -1551, -1500, - -1587, -1693, -1753, -1431, -1048, 1162, 1308, 3073, - -998, -1575, -517, -1346, -1293, -1493, -1375, -1109, - -803, 2972, -1446, -1316, -1114, -1405, -1240, -1057, - -1109, -589, 2623, 1626, -1555, -1026, -1346, -1467, - -902, 1291, 176, 630, 4293, 1949, -1233, -1362, - -930, -1175, -1118, -1375, -1172, -967, 4896, 4195, - -1744, -1562, -1797, -1815, -1577, -1194, 371, 3326, - 3183, 3071, -1425, -1773, -1562, -1358, -547, -246, - 24, -526, -1502, 29376, -860, -614, -857, -795, - 793, -616, 1691, -125, 156, 559, -1643, -1462, - -1523, -1413, -1251, -592, 1014, 1888, 243, 1041, -}; - -static const int16_t fcb16ss[] = { - 308, -532, -811, -974, -641, -431, 3409, 258, - 567, 641, 1315, -723, -738, -502, 142, 678, - -67, -170, 73, -65, 2717, -804, -958, -878, - -532, -562, 238, 497, 548, 718, -868, -669, - -932, -1004, -518, -502, -286, 405, 2987, 1420, - 174, -779, -748, -575, -153, -40, 340, 413, - 275, 387, 965, 82, -550, -744, -592, -591, - -604, -163, 428, 843, -1280, 1756, -368, 777, - -29, -453, -61, 43, 50, 137, 950, -229, - 1504, -491, -353, -167, -285, -158, -94, -185, - -1431, 303, 673, -758, -610, -308, 1247, 348, - 95, 31, 1631, 1963, -624, -770, -466, -150, - -122, -123, 34, -141, -883, -374, -948, -629, - 3420, -772, -392, -31, 603, 646, -760, -871, - -936, -948, -727, 3563, -376, 858, 699, 561, - -1370, 2366, -775, -1241, -1105, -247, 177, 432, - 414, 379, -1360, -1057, -945, -848, -568, -779, - -632, -328, -295, 425, -349, 630, -275, -527, - 438, 47, -194, -96, -239, -545, -1381, -689, - 1644, 1165, -437, -153, -193, 307, 183, 66, - -1335, 2590, 2169, -447, -435, -317, -82, 204, - 45, -145, -1324, -205, 4019, -973, -578, 28, - 175, 506, 235, -98, -908, -294, 1443, -850, - -556, 1707, -277, 58, 241, -188, -853, -572, - -577, 1258, 1007, -190, 1, -3, 103, -49, - 5385, 137, -707, -834, -510, -517, -392, -390, - -231, -275, -1249, 5229, -812, -893, -353, -663, - -29, 187, 45, 10, -1388, -1171, -1051, 412, - -379, -411, 240, 574, 632, 284, -838, -912, - -924, 3062, -695, -409, -224, 422, 293, 267, - -1436, -1237, -1303, -1305, -914, -243, 821, 839, - 1043, 1284, -1178, -496, 1594, -736, 1752, -601, - -396, 330, 231, 48, -1253, 808, -896, -967, - -653, -84, 4, 442, 363, 589, -1005, -672, - -687, -93, -274, 1376, -232, -52, 399, 255, - -1085, -1214, -1088, -748, 1036, 414, 220, 509, - 436, 499, -648, -765, -931, -983, -758, -543, - -379, -115, 780, 3327, -1086, -893, -773, -881, - -683, -11, -322, 3418, 739, 961, -1363, -929, - 899, -1005, -792, -338, -185, 702, 627, 638, -}; - -static const int16_t fcb16sm[] = { - -1125, -1385, -1439, -1387, -1120, -681, -135, 616, - 3086, 2537, -1440, -1209, -1027, -1209, -626, 173, - 662, 899, 861, 2180, 387, 1032, 936, 140, - -353, -302, -290, -330, -551, -1019, 3555, -68, - -441, -539, -500, -27, -423, -506, -522, -415, - 2347, 1890, -312, -742, -679, -679, -653, -609, - -433, -472, 2709, -755, -1153, -1066, -1028, -862, - -826, -315, 78, 1699, -363, -429, -690, -190, - -358, -667, 1909, 39, -1, 138, -1592, -1559, - -1357, -1554, -750, 813, 1676, 1537, 977, -269, - 8320, -602, -1140, -1153, -1136, -1174, -1004, -1091, - -1388, -1187, -507, 3103, -200, -665, -590, -381, - -365, -40, -295, -591, -963, 271, 2231, -547, - -65, -270, -64, 243, -183, -548, -796, -277, - -7, -168, 1575, -361, 35, -19, 192, -154, - -384, 144, -426, -528, -598, -778, -297, 1847, - 564, 218, 864, -654, -485, -435, 45, 709, - 630, -11, -691, -111, -775, -356, -522, 2247, - -79, -433, -620, 594, 79, 60, -828, -475, - 768, -79, -655, 550, -201, 77, 858, -11, - -803, 1173, 1027, -971, -656, -648, -40, 17, - 720, 176, -1055, -936, -258, 550, 1086, 1065, - 0, -473, -364, 30, 53, -6, -54, -24, - 21, -81, -88, -45, -14, 81, 674, -1189, - -1049, -846, -489, -24, -47, 165, 658, 1909, - -241, -390, -387, -454, -319, -549, -307, -112, - 778, 1486, -314, 34, -93, -799, -538, 2219, - -445, 39, -38, -258, -427, -943, -760, -602, - -575, -450, 376, 668, 879, 1215, -1216, -784, - -646, -291, 275, 1019, -77, 124, 256, 1166, - -410, -993, -1145, -1118, -940, -825, -560, -131, - 1006, 4878, -1401, -1286, -1316, -1394, 177, -919, - 162, 2292, 1792, 1242, -762, 937, -168, -900, - -829, 203, 1225, 626, -122, -515, 992, -198, - -782, -25, 74, 1019, -606, -364, -350, -5, - 451, 324, 265, -1143, -820, 382, -362, 85, - -797, 693, 1594, -335, -229, -396, -211, -356, - -97, -115, 92, 49, -476, -1124, -1084, -594, - -228, 728, 16, 589, 1213, 841, -829, 1874, - -907, -1000, 1411, -621, -707, 356, 437, 37, -}; - -static const int16_t fcb22l[] = { - 2735, -1224, -1198, -1073, -1115, -1054, -713, 1693, - -1106, -1259, 722, -1256, -1223, 1686, 1589, 2003, - -906, 2529, 2141, -396, -338, -36, 52, 476, - 319, -420, 561, -492, -526, -359, -221, -254, - -752, -1136, -690, -896, 4307, -363, -42, 1363, - -717, -1036, -874, 2315, -952, -872, 262, 1418, - 737, 1374, -506, -470, -275, -126, 242, 428, - -678, -681, -581, 1016, -553, -509, -485, -408, - 9595, -1015, -1168, -932, -812, -690, -167, 753, - -935, -439, 2105, -526, -710, -570, 9, 548, - 530, -1308, -1060, -351, -974, -1038, 93, 5579, - -737, -1282, 1386, -1284, -1243, -1105, 790, 2169, - -701, -660, -555, 1317, 2805, 792, 2209, -490, - -758, -1262, -1083, -1073, 930, -810, -170, 2326, - -1213, -1286, 3435, -1135, -1051, 220, 3040, 1999, - -933, -663, -714, -855, -372, -599, -437, 373, - 5873, -987, -1081, -1003, -747, -271, 582, 1069, - -917, -754, 5676, -565, -616, -396, 177, 908, - 3106, 1459, -678, -543, -340, 47, 336, 493, - -1060, 1427, -560, -763, -710, -661, 193, 595, - -996, 2488, -588, -752, 1306, 114, 292, 689, - -1202, 2334, -1173, -1167, -755, 353, 1711, 1572, - -932, -751, 2099, 2025, -417, 62, 458, 611, - -981, 4387, -639, -560, -520, -152, 262, 748, - -828, -818, -682, 5250, -640, -270, 385, 1049, - -1072, -774, 1870, -668, 1514, -158, 283, 793, - -1087, -1150, -899, -875, -188, -184, 6656, 2311, - -906, 1654, -446, 1677, -654, -101, 364, 721, - -1272, 7928, -812, -576, -708, -347, 397, 1128, - 3830, -1034, -1055, 2244, -759, -706, 79, 893, - -922, -1067, 2740, -868, -858, 1129, 34, 1096, - 2455, -694, 1970, -650, -674, -131, 370, 697, - -1069, -1137, -948, -1045, -1087, -964, 367, 1091, - 4096, -960, -921, -870, 1397, -511, -190, 545, - -657, -1194, -536, -951, -1094, 117, -720, 2532, - -1098, -1147, -1177, 1764, -757, -121, 2372, 2010, - 3662, -952, -995, -894, -625, 464, 731, 863, - -607, -505, 401, -423, -540, 2144, 755, -430, - -1499, -1242, -1202, -1190, -626, 1249, 3388, 2379, - -983, -1090, -907, -1021, -1012, -870, 2723, 1589, - -913, 332, -102, 99, 226, 6, 176, 354, - 156, -36, -829, -774, -685, -15, 498, 503, - 2030, -409, -599, -572, -341, -2, 111, 302, - 788, -1002, -978, -929, -1001, -886, 578, 995, - 1237, -747, -696, -653, 1143, 62, 506, 571, - 994, -993, -902, -871, -662, 1527, 370, 979, - 980, -466, -484, 787, -261, 61, 250, 377, - -112, -676, -535, -344, 274, 363, 185, 334, - -48, -1144, -1095, -1011, -552, 445, 1355, 1207, - -1108, -1128, -1085, -826, -83, 2001, 1265, 1429, - -1024, 1199, -671, -701, -444, 1192, 187, 673, - -1039, -1056, -953, -732, 359, 714, 787, 935, - -1187, -1133, -1112, -971, 2158, 1720, 801, 2016, - -1056, -1068, -889, 1808, 503, 892, 358, 1041, - -1180, -1184, -1068, -788, 1423, -573, 2141, 1949, - -1042, -924, -849, 512, -629, -272, 779, 815, - 1939, -1069, -1092, -1027, -770, 48, 1554, 1285, - -1109, -1148, -1157, -1033, -934, 779, 1358, 1560, - -1053, 222, -1095, -1001, -681, -26, 1112, 1035, - -1168, -1285, -1169, -1180, -1085, -1097, 1313, 3112, - -928, -655, -811, -618, 1555, -480, 71, 467, - -1220, -1123, -1008, -577, -845, 3854, 491, 1878, - -1051, -761, 617, -650, -453, 51, 784, 757, - -993, -883, -905, -708, -869, 969, -64, 655, -}; - -static const int16_t fcb22s[] = { - 9854, -479, -1163, -1147, -1316, -1137, -991, -942, - 522, 739, -1042, -1306, -1040, -126, 1147, 3526, - 1880, -477, -483, -328, -899, 1063, 1243, -610, - -721, -527, -372, 171, 90, 196, 6615, -1167, - -1189, -1079, -954, -817, -833, 2246, 439, 1038, - -1053, -1136, -938, -805, -1022, -1041, -717, 2021, - 341, 935, -1164, -1230, -573, 1768, 11111, -1113, - -874, -631, -367, 7, -1077, -925, 1558, -850, - -918, -755, -512, 452, 260, 400, -787, -966, - -690, -584, -843, -802, 2092, 120, 103, 580, - -746, -512, -241, -621, 2771, -486, -268, 258, - 171, 232, -1265, -1253, 15128, -1123, -1037, -885, - -1109, -664, -659, -240, 1558, -909, -1160, -1247, - -1223, -1031, -989, -415, 3504, 1569, -651, -1241, - -1145, -1014, -1322, -1000, -354, 59, 709, 4206, - -1124, -986, -633, -976, -907, -636, -371, 255, - 1195, 876, -145, -1146, -1018, -992, -480, -762, - 6904, -703, -431, 1043, -1048, -638, -142, 394, - -852, -730, -533, -361, 234, 221, -1070, -930, - -764, 3210, -780, -256, 1777, 258, 307, 382, - -1224, 987, 4894, 3525, -412, -558, -819, -863, - -572, -497, -1175, -1197, 7637, -1109, -748, -116, - -306, 27, 386, 630, -1334, -1378, -1302, 12592, - -1327, -971, 89, -731, 259, 201, -1135, -951, - -585, -64, 3489, 2765, 43, 75, -527, -162, - 2865, -1344, -1394, -1391, -1231, -748, -962, 5403, - 719, 1418, -724, -1101, -955, -743, -937, -1064, - -1095, -601, -60, 411, -1113, -873, -603, 2913, - 2512, -339, -36, 26, -39, 78, -757, -998, - -522, -838, 5507, -973, 796, 536, 250, 312, - -1363, -944, 6021, -58, 5313, -690, -549, -485, - -66, -133, -1257, 6004, 6374, 1487, -976, -987, - -969, -803, -1027, -624, -967, 1744, 3504, 6, - -659, -691, -326, -129, -49, 148, -1032, -683, - 1819, 1804, -491, -452, -295, 33, -20, 42, - -1226, -1086, -792, 6412, -657, -278, -103, -25, - -82, 207, 2450, -6, 2417, 251, -622, -593, - -409, -193, -339, -304, -862, -667, 2457, -500, - -438, -504, 1408, 143, 203, 265, -1128, -1148, - 2791, -373, -951, 2129, -842, -278, 81, 307, - -787, -822, 2655, -604, 2028, -787, 4, 335, - 170, 219, 649, -457, 972, -607, -359, -470, - -238, 68, -57, 107, 2285, -526, -490, -604, - 179, -41, 230, 64, 20, 50, -802, 1168, - -235, -264, -316, 1469, -499, 108, 183, 150, - -1068, -806, -399, 1244, -355, 487, -57, 450, - 195, 248, -1122, -1096, 3327, -956, 1084, 1306, - 247, 442, 169, 283, 3416, -609, -891, -879, - -853, -573, -285, -147, 380, 608, 1271, -874, - -931, 40, -989, 1432, 1981, -34, 285, 190, - -902, -974, 4117, -868, -784, -584, -358, 200, - 261, 521, -945, -981, -773, 3517, -961, 2420, - 9, 318, 187, 322, -1006, -779, -526, 2972, - -712, -578, -576, 167, 156, 270, 460, -74, - -237, 939, -440, -515, 126, 63, 82, 67, - -1069, -1104, -923, -634, -190, 1151, 526, 2920, - 125, 566, -1144, 4199, 1314, -458, -568, -336, - -515, -332, -352, -143, -770, 283, -770, -785, - -807, -348, 93, 427, 181, 334, -798, -830, - -300, -509, 1257, -554, 1341, 6, 242, 272, - -1030, 62, 1293, 340, 752, -493, -6, -34, - 33, 85, -893, -1202, 244, -131, -306, 7590, - -832, 420, 80, 423, -799, -870, -930, -720, - -640, 2390, -409, -177, 91, 370, -864, -949, - 838, -574, -234, 555, 46, -9, -83, 146, - -825, -478, -664, -57, 867, -296, -380, -73, - 70, 171, -1124, 10522, -228, -609, -958, -1025, - -548, -384, -257, 55, 5414, 436, -651, -748, - -671, -525, -25, -273, -264, 57, -1129, 1974, - -145, 1650, -317, -514, -305, -78, -154, 59, - 1269, 1008, -510, -711, -534, -358, 194, 117, - 102, 57, -837, 1260, -126, -494, 47, -162, - 924, -72, 130, 97, 742, -803, -711, -755, - -402, -188, 24, 309, 187, 379, -1092, 5862, - -647, -807, -715, -696, -408, -29, 104, 353, - 3298, 2193, -263, -772, -908, -754, -449, -164, - -157, -44, -986, 2313, -596, 56, 2057, -478, - 74, -51, 51, 121, -899, 1793, -595, -669, - -743, -689, -546, 71, 201, 382, -1061, 3375, - -776, -876, -648, -407, -44, 260, 258, 393, -}; - -static const int16_t fcb22m[] = { - 11522, 868, -1444, -1572, -1674, -1745, -1844, -1616, - -1723, -1508, 27, -321, -693, -597, -374, -380, - 327, 209, 611, 1182, -548, 176, -544, -485, - -341, -376, -383, 1024, 1316, -4, 192, -649, - -979, -945, -802, -183, 3749, 812, -416, -527, - -734, 1059, -521, 924, -462, -631, -76, 182, - 126, 100, -653, -643, -1189, -1264, -1312, -1311, - -1212, -1016, -218, 8415, -1005, 734, 1303, -272, - -397, -521, -245, 389, 242, -234, 458, -912, - -1215, -1228, -1288, -1131, -845, -404, 912, 5497, - 413, 3161, -432, -148, 1704, -663, -996, -1009, - -1419, -929, -36, -471, -640, -571, -197, -573, - -462, 2586, -179, -382, -757, -895, -1096, -1140, - -1216, -1051, -688, -44, 3311, 3518, -474, 2530, - 1475, -676, -702, -777, -380, -316, -538, -468, - -708, 542, -213, -713, -911, -482, -696, -135, - 1282, 2006, 5707, 476, -707, -771, -650, -788, - -778, -853, -962, -926, 10, -11, 3, 1, - -12, -14, 21, 7, -13, -10, -1410, -1712, - 1379, 5757, 218, -1232, -563, -929, -684, -827, - -261, 1040, -154, -309, -99, 62, 856, 199, - -614, -926, -626, 1568, -258, 374, 1071, -140, - -250, -332, -832, -706, -863, -714, -749, 3081, - 498, -695, -395, -600, -279, 588, 245, 3122, - -329, -677, -262, 67, 19, -530, -882, -862, - -1033, -160, 1542, 1916, -416, -600, -553, -219, - -130, -497, -699, 1719, 160, 3293, -212, -923, - -1045, -761, -1238, -1038, 1543, 738, -548, -541, - -403, -281, -115, -95, -313, -19, -292, 1136, - 3592, 696, -654, -856, -726, -693, -1057, -1267, - -722, -381, -683, 1364, -30, 589, 454, 262, - -57, -1018, -312, 846, -139, -587, -127, 2482, - -178, -233, -977, -796, -6, 250, 220, 1577, - 1141, -251, -649, -809, -1051, -873, -762, -990, - -1010, -890, -897, -639, -671, 1964, 788, 2310, - 6001, 20, -1008, -1159, -1208, -1208, -1318, -1227, - -829, 1680, -1023, -998, -1224, -945, -769, -41, - 2033, 196, 917, 1615, 2026, -654, -1014, -918, - -750, -675, -839, 1541, 282, 430, -1059, -708, - -507, -522, -169, 438, 196, 835, 778, 897, - 420, 526, 1239, 198, -736, -953, -835, -229, - -348, 726, -767, 1311, 248, -353, -550, 1017, - -250, -732, 256, -175, -638, 763, -761, -957, - -554, 539, 252, 299, 431, 613, 4398, -378, - -1022, -1020, -990, -757, -621, -83, -34, 122, - -476, 77, -799, -116, 4546, -787, -735, -462, - -875, -907, -1373, -1354, -1355, -1220, -1024, -88, - 1298, 2844, 940, 1135, 2261, 2142, 181, -735, - -924, -941, -799, -715, -662, 86, -719, -521, - 115, -576, -699, 1052, 1295, -57, 42, 230, - 2876, 501, -294, -158, 104, -157, -515, -662, - -987, -1069, -703, -985, -1061, -946, -878, -267, - 397, 132, 534, 3642, 1298, -560, -701, -526, - -294, 197, 310, 75, -3, 267, -342, 2058, - -328, -427, -709, -688, 14, -43, 237, 506, - 2822, -337, -900, -818, -638, -192, 883, -14, - -271, -559, 2822, -165, -988, -933, -917, -603, - -583, -397, 467, 1092, -1044, -479, 2478, -386, - -535, -253, 63, -49, 79, 27, -182, -100, - 362, -628, -661, -707, 1557, 136, 335, 89, - -197, 5697, 220, -473, -472, -1053, -1023, -1087, - -1203, -756, -377, -917, -925, -568, -237, 1422, - 197, -98, 614, 867, -831, -829, -969, -720, - 414, 1080, 1707, 828, -121, -757, -1044, -289, - 816, 284, 809, -84, -22, -552, -9, 193, - -359, 66, -582, -674, 1992, -31, 58, 427, - -515, -299, 932, -608, -1103, -1068, -1016, -770, - 200, 1031, 1112, 1026, -598, -818, -891, -635, - -828, -866, -650, 4795, -407, 215, -853, 373, - -696, 159, 995, 465, -509, 109, 60, 10, - 8455, 198, -999, -1131, -1111, -1195, -1246, -1192, - -1181, -934, -365, -764, -689, -589, -734, 2479, - -960, 1279, 104, -209, -1012, -824, -1059, -921, - -812, -204, 199, 601, 3136, 637, 3021, 3851, - -490, -18, -930, -1081, -1133, -1182, -1268, -980, - -864, -945, -278, 961, -514, -123, 562, 874, - -130, 336, 3314, -331, -1112, -1162, -1227, -1230, - -1172, -988, -319, 3582, 890, 50, -681, -788, - -906, -876, -829, -827, -41, 3416, -740, -913, - -893, 404, 2059, -651, -474, 302, 516, 578, -}; - -static const int16_t fcb22sl[] = { - 1098, -1107, -1125, -983, -770, -233, 201, 823, - -1433, -1294, -17, -1156, -301, 1185, 1307, 1108, - -1247, 1829, 1353, -537, -457, 116, 574, 712, - 159, -489, 511, -340, 54, 119, 213, 351, - -1489, -1256, -1324, -1132, 3710, 262, 1087, 1465, - -1434, -1027, -1116, 825, -662, -428, -109, 1045, - 229, 753, -604, -422, 122, -220, 279, 375, - -349, -684, -197, 490, -160, -116, -120, 146, - 5195, -895, -974, -758, -524, 21, 761, 1016, - -1216, 151, 864, -602, -715, -591, -347, 592, - -1265, -1328, -1375, -878, -660, -549, 143, 4302, - -1433, -1277, 360, -1032, -835, -385, 337, 1111, - -1345, -1250, -1156, 914, 1594, 22, 912, 1012, - -1576, -1411, -1364, -1153, 842, -184, 240, 1302, - -1486, -1162, 1246, -880, -830, 14, 2487, 1607, - -1384, -158, -572, -977, 43, -30, -184, 572, - 2759, -892, -768, -522, -289, -44, 351, 575, - -1292, -546, 3736, -609, -538, -25, 514, 924, - 1772, 1639, -903, -595, -263, 340, 579, 670, - -1425, 770, -1179, -920, -1158, -675, 496, 1208, - -1337, 1240, -1030, -1044, 1840, 312, 809, 908, - -1457, 1410, -1240, -1083, -541, 568, 2768, 1432, - -1249, -890, 1078, 1278, -558, 63, 573, 778, - -1285, 1932, -1004, -902, -339, 59, 17, 659, - -1352, -935, -877, 3421, -455, 160, 820, 1230, - -1326, -978, 986, -790, 1541, 41, 542, 743, - -1491, -1162, -1389, -1265, -928, -139, 5045, 2259, - -1182, 1358, -953, 1338, -502, 122, 749, 839, - -1284, 4389, -1001, -813, -421, 44, 855, 1072, - 1658, -881, -821, 1409, -299, 4, 453, 700, - -1144, -1112, 1230, -790, -421, 1250, -12, 655, - 1545, -872, 1199, -632, -365, 56, 415, 663, - -1401, -1189, -1403, -1189, -1145, -687, -116, 1120, - 1768, -1068, -1024, -629, 1440, 88, 578, 711, - -1651, -1561, -1564, -1430, -1037, 1264, -21, 1944, - -1552, -1336, -1277, 916, -412, 27, 2454, 1661, - 1996, -1087, -1223, -924, -393, 1673, 794, 1017, - -1362, -132, 151, 537, -992, 1830, 777, 991, - -1591, -1355, -1494, -1420, -666, 2407, 3210, 2092, - -1114, -624, -1087, -903, -808, -438, 1881, 654, - -1140, 254, -105, 212, 386, 49, 256, 314, - 83, 98, -1128, -901, -578, 362, 702, 691, - 1191, -204, -335, -226, -102, -44, -5, 120, - 57, -1110, -403, -651, -806, -202, 567, 690, - 349, -908, -1075, -941, 1487, 464, 763, 782, - 387, -1070, -990, -765, -295, 1669, 341, 881, - 232, -1013, -1043, 723, -311, 294, 646, 574, - 72, -1191, -546, -183, 493, 161, 201, 465, - -185, -1434, -1368, -1051, 64, 385, 748, 986, - -740, -530, -1199, -562, 142, 1388, 1487, 715, - -1359, 873, -1187, -923, -455, 1914, 403, 1016, - -1245, -1223, -624, -495, 724, 652, 433, 585, - -1499, -1277, -1381, -1148, 1679, 2138, 995, 1424, - -1345, -1319, -1296, 906, -228, 1534, 506, 1024, - -1628, -1410, -1422, -1197, 1393, -22, 2728, 1784, - -1245, -1056, -942, 2, -165, -115, 840, 569, - 1016, -1191, -1091, -862, -457, 95, 2087, 1029, - -1460, -1486, -1459, -1104, -571, 925, 1234, 935, - -1568, -49, -1325, -1255, -64, 315, 838, 962, - -1651, -1562, -1606, -1571, -1308, -380, 1988, 2117, - -848, -412, -987, -370, 1224, -304, 10, 498, - -1523, -1348, -1373, -959, -772, 3767, 621, 1773, - -931, -628, 169, -513, 61, -306, 994, 476, - -1116, -879, -875, -484, -795, 958, -162, 444, -}; - -static const int16_t fcb22ss[] = { - 6765, -638, -1108, -977, -679, -446, -325, -432, - -127, 96, -569, -621, -1050, -841, -800, 1474, - 1170, 60, 330, 223, -1317, 855, 307, -931, - -648, -549, -148, 535, 642, 445, 3666, -1146, - -1167, -944, -584, 942, -284, 25, 573, 472, - -1041, -1096, -1209, -1082, -770, -737, -139, 2073, - 753, 832, 507, -828, -1112, -1130, 4284, -722, - -261, -57, 499, 300, -1380, -1130, 135, -898, - -816, -395, 195, 453, 650, 537, -953, -1109, - -1221, -981, -747, -647, 2360, 467, 845, 684, - -1177, -792, -1254, -1148, 1344, -745, -323, 180, - 729, 739, -1020, 183, 5226, -638, -358, -86, - -268, -143, 84, -115, 480, -543, -1229, -1097, - -594, -983, -792, -391, 2637, 1405, -761, -866, - -1186, -973, -792, -640, -220, -102, 1165, 3159, - -1241, -1057, -1322, -1007, -731, 44, 264, 668, - 2645, 1592, 2885, -1155, -1347, -1209, -309, -1161, - 4216, -64, 830, 616, -688, -638, -596, 202, - -665, -623, -499, -248, 512, 749, -1395, -708, - -1086, 1209, -745, -367, 1397, 279, 374, 259, - -1357, -254, 2310, 1839, -147, 36, -402, 300, - -49, 47, -1328, -992, 3453, -889, -621, 135, - 437, 70, 663, 346, -1339, -1136, -1275, 6675, - -1309, 2285, -869, 1154, 640, 617, -505, -1042, - -984, -702, 1283, 1573, -168, 135, 249, 253, - -783, -1119, -1342, -975, -1127, 1391, -705, 4439, - 1160, 845, -1283, -1224, -1286, -1142, -1019, -901, - -658, -157, 231, 611, -994, -463, -1017, 1082, - 1831, -459, -164, 114, 0, 108, -1386, -1079, - -1318, -1091, 2540, -717, 762, 1414, 849, 576, - -1405, -566, 2704, -996, 2133, -678, 404, 281, - 4, -32, -1474, 3530, 2301, -711, -919, -305, - -125, 184, 450, 73, -1132, 1567, 1620, -551, - -198, -645, 19, 8, 190, 191, -741, -728, - 410, 1067, -322, -239, 86, 11, -137, -220, - -489, -607, -963, 3630, -624, -478, -12, 124, - 219, 63, 2040, 75, 1338, -293, -333, -336, - -330, -246, -360, -344, -953, -393, 1550, -701, - -616, -254, 1908, 211, 328, -43, -1089, -299, - 1070, -723, -923, 2170, -400, -13, -28, 108, - -812, -400, 876, -650, 1308, -772, -256, -200, - 117, 329, 649, -639, 437, -704, -567, -20, - -211, 197, 330, 342, 1670, -468, -920, -588, - 972, -310, 9, -46, 70, -29, -1313, 1684, - -794, -979, -752, 1864, -173, 108, 248, 292, - -1247, -1226, -1059, 288, -112, 189, 20, 540, - 454, 380, -1035, -803, 1267, -767, 746, 1331, - 107, 317, 158, -116, 2093, -723, -1064, -906, - -713, -789, -518, 48, 494, 1018, 1835, -1353, - -1303, -1098, -559, 800, 520, 662, 615, 574, - -1282, -526, 1829, -1086, -885, -356, -539, -50, - 493, 402, -777, -374, -754, 1721, -701, 2086, - -348, 218, 138, 109, -1367, -1226, -1041, 1949, - -433, -291, -363, 567, 613, 560, 1166, -481, - -737, 1193, -479, -163, -69, 2, 133, 239, - -1444, -1448, -1350, -987, -296, 606, 755, 543, - 741, 806, -851, 2437, 23, -681, -670, -271, - -439, -227, -243, -198, -1307, 424, -1212, -987, - -745, -369, 162, 641, 915, 611, -24, -728, - -1061, -659, 808, -532, 1241, -233, 266, 353, - 175, 210, -262, -328, 101, -238, 66, -339, - -472, -415, 952, -1490, -1302, -955, -1270, 5776, - -792, 777, 1097, 807, -1334, -1172, -1211, -924, - -877, 2458, -355, 593, 936, 699, -336, -700, - -762, -569, -337, 642, 97, 441, -188, -533, - -1062, 188, -873, -801, 418, -167, -57, -29, - 79, 241, -1110, 6430, -816, -807, -462, -601, - -56, -45, 188, 74, 2869, 43, -1122, -799, - -772, -847, 1394, -36, 294, 13, -1304, 2155, - -534, 1545, -315, -325, 183, 31, 372, 187, - 873, 1376, -1037, -810, -516, -235, 485, 99, - 287, 327, -1074, 1203, -1089, -882, -515, -544, - 2041, -40, 208, 191, 597, -1141, -1274, -885, - -386, 106, 593, 394, 671, 678, -1292, 3861, - -1085, -1150, -748, -218, 500, 55, 335, 469, - 3217, 2888, -882, -643, -590, -506, 43, -459, - -210, -222, -965, 2453, -830, -779, 1808, -588, - 130, 4, 130, -23, -1269, 1374, -1238, -1148, - -523, -659, -170, -302, 1055, 1389, -1467, 2505, - -930, -1181, -842, -516, 399, 886, 849, 738, -}; - -static const int16_t fcb22sm[] = { - 5761, -398, -743, -948, -944, -845, -883, -896, - -811, -604, -1142, -1388, -1190, -685, -118, 1498, - 1590, 293, 564, 352, 124, 851, -131, -652, - -573, -279, -756, -478, 833, 670, 2609, -1138, - -1107, -1024, -739, -646, -387, 33, 635, 1037, - -717, -990, -1161, -948, -660, -230, 69, 2510, - 1274, 841, -49, -872, -764, -211, 3046, -30, - -143, -311, -324, -413, -760, 67, 619, -699, - -725, 305, -484, 1292, 472, -156, -568, -1243, - -1256, -994, -803, -386, 1692, 596, 1325, 1290, - -492, -1007, -732, -788, 1136, -610, 45, 1307, - 420, 649, -534, -1075, -949, -367, 219, 444, - -120, 251, 476, 1806, 902, -927, -1151, -879, - -659, -741, -5, 298, 1861, 995, -244, -1031, - -1142, -1085, -952, -773, -468, -9, 1637, 3592, - -971, -1150, -1199, -985, -689, -317, 150, 540, - 2727, 1678, -223, -403, 102, -902, -773, -223, - 3182, -457, 75, -188, -291, -428, -101, -365, - -442, -336, -128, -33, 781, 1242, 501, -753, - -846, 757, -444, -311, 1182, 4, -8, -122, - 1866, -528, -142, 1598, -15, -219, -557, -804, - -916, -965, 114, 130, 3672, -19, -873, -280, - -777, -919, -824, -654, 1078, 39, -50, 119, - -411, -311, -359, -57, -137, 7, -780, -892, - -767, -167, 1302, 1693, -205, -51, -174, -71, - 838, -220, -1133, -993, -710, -340, 650, 1341, - 191, -5, 743, -543, -125, -567, 70, -42, - -501, -448, 47, 1151, 400, -774, -781, 1324, - 1089, 32, -256, -415, -352, -214, 912, -1141, - -988, -638, 1349, 251, 124, -4, 89, -16, - -678, -569, 1502, 146, 114, 816, -98, -269, - -622, -808, -634, 3319, 1218, -323, -750, -548, - -525, -575, -591, -730, 35, 764, 1423, 574, - -352, -672, -802, -314, -308, -29, -1040, -717, - 469, 421, -527, -420, 589, 195, 556, 472, - -626, -864, -133, 3531, -667, -460, -523, 103, - 23, -309, 2381, 136, 1197, -399, -399, -501, - -638, -899, -813, -707, -249, 719, 821, -989, - -629, -568, 642, -4, 297, 70, -1105, 454, - 400, -235, -562, 1607, -116, -205, 1, -490, - 7, -523, 764, 329, 992, -240, -249, -275, - -366, -265, 662, -803, 393, -567, -501, -32, - 178, 371, 126, -146, 1748, -516, -634, -395, - 268, 893, 154, -36, -620, -999, 304, 1490, - -512, -821, -479, 1922, -610, -481, -482, -805, - -996, -16, -567, 542, -22, 589, -114, 69, - 322, 358, -848, 1205, 509, -527, 25, 111, - -243, -197, -20, 62, 1500, -977, -974, -391, - -555, 448, -256, 79, 392, 547, 1472, -1276, - -1203, -987, -315, 515, 855, 183, 231, 62, - -1176, -397, 2831, -527, -575, -435, 174, -337, - 723, 107, -502, -765, -455, 1124, -218, 1444, - 53, -201, -135, -267, -510, -1058, -869, 1130, - -128, -394, 16, 873, 597, 455, 16, 0, - -11, 14, -12, 9, 6, -14, -11, -23, - -453, -1056, -988, -713, -267, 794, 954, 1361, - 822, -448, 379, 1163, 336, -724, 55, 109, - 237, -80, -732, -1017, -264, 654, -1043, -1015, - -654, 91, 17, 548, 504, 932, -1057, -1151, - -964, -130, 1171, -146, 740, 134, 790, 539, - -591, -577, -388, 154, 609, 341, 657, 838, - -379, -872, 711, -665, -818, -549, -151, 2501, - -28, -189, -255, -378, -363, -1157, -929, -887, - -338, 1926, -33, -26, 1009, 765, -79, -98, - -37, -967, -566, 1012, 905, -245, 41, 322, - 194, -148, -220, -171, -239, -242, -147, -14, - 221, 575, 1754, 3059, -246, -713, -696, -636, - -640, -843, -841, -755, 2554, -504, -568, -318, - -324, -171, -294, -238, -288, -174, -289, 1273, - -231, 1053, -284, -338, -394, -227, -303, -226, - 966, 742, -873, -503, -586, -286, 119, -59, - 339, -38, -843, 977, -448, -238, 227, -77, - 729, 6, 45, -493, 277, -1385, -1289, -846, - -117, 376, 763, 553, 769, 670, -652, 3280, - -762, -882, -396, -299, 124, -270, -31, -210, - 2413, 644, -790, -912, -581, -507, -110, -408, - -54, -30, 632, 969, -632, -206, 955, -95, - -578, -337, -377, -467, 1264, 67, -854, -863, - -909, -751, -616, -479, 563, 2070, -972, 1478, - -450, -715, -859, -689, 190, 736, 617, 530, -}; - -static const int16_t fcb44sl[] = { - 2433, -925, -1015, -1009, -875, -276, 378, 464, - 694, 795, -1044, -601, -658, 257, -898, -509, - -346, 2160, 694, 952, -1302, -619, 502, -378, - -624, -178, 349, -100, 204, 546, -1450, -1127, - -1302, -1297, -1051, -840, 3426, 1346, 1577, 1723, - -1267, -710, -872, 448, -1023, -728, -521, -134, - 874, 936, -1134, -549, 203, -932, -1051, 755, - -608, -199, 858, 1008, 1819, -842, -773, -739, - 818, -371, 289, 293, 656, 704, 308, -1009, - -959, -1089, 466, -468, 279, 897, 764, 797, - -1433, -1276, -1253, -1326, -1182, -992, -85, 4339, - 2135, 2136, 1131, -917, -966, -859, -889, 1178, - 62, 659, 771, 882, 1844, -607, 1184, -766, - -805, -385, -61, 502, 648, 732, -1245, 1315, - -818, -827, 621, -588, 193, 480, 649, 776, - -1178, -1202, -1152, -1088, -857, -191, -49, 129, - 1950, 1237, -1461, -1290, -1342, -1401, -1338, -1213, - -623, 224, 4086, 2517, -1150, -814, -747, 916, - 807, -288, 319, 436, 560, 718, 392, -973, - -988, 411, -954, -502, 214, 621, 856, 831, - -1268, 4012, -852, -1002, -1014, -577, 32, 552, - 987, 1138, -1205, -1319, -1145, -928, 80, 371, - 277, 779, 859, 902, -1141, -991, -957, 707, - -892, 1098, 126, 381, 668, 870, -1254, -995, - -1163, -926, -1149, 2572, -17, 747, 1456, 1509, - -1004, -867, 1205, -797, 938, -657, 346, 520, - 782, 872, -1328, -1080, -1111, -1067, 2227, -892, - 665, 1604, 1425, 1477, 1869, -668, -712, 1044, - -800, -139, 0, 355, 609, 717, -1192, -632, - 3546, -780, -870, -501, 141, 504, 921, 1027, - -1125, -1087, 1154, -660, -987, 937, 82, 1390, - 1360, 1243, 1259, -550, -769, -787, -743, -362, - -12, 177, 321, 505, -1147, -899, -947, -849, - 1371, -462, -127, 16, 752, 954, -1405, 448, - -1181, -1259, -1204, -868, -468, 110, 1293, 1263, - -1267, -1180, -1238, -930, -940, 916, 1793, 653, - 1070, 1137, -216, -997, -845, -659, -699, -174, - 758, 961, 417, 630, -1123, 1691, 1229, -732, - -937, -491, -78, 265, 744, 864, 4771, -856, - -1005, -1007, -934, -484, -17, 579, 861, 959, - -1264, 70, -961, -864, -860, -302, 314, 788, - 487, 686, -1133, -790, -466, 561, -812, -256, - 2078, -58, 757, 953, -1133, -286, -655, -476, - -23, -629, 7, 182, 426, 504, -1110, 314, - 497, -822, -662, -754, 1179, 1726, 696, 955, - 1793, -1143, -1268, -1279, -1207, -873, -183, 1546, - 1440, 1305, -1278, 1396, -779, 558, -840, -32, - -18, 257, 616, 757, 265, -906, 499, -897, - -846, -435, 362, 434, 752, 732, 453, 150, - -1029, -1182, -1195, -940, -297, 876, 1084, 1051, - -1377, 1354, -1148, -1313, -1211, -937, -366, 1942, - 1323, 1410, 311, -270, -81, -159, 42, 42, - 7, 357, 255, 285, 1973, 1386, -752, -873, - -916, -466, -39, 493, 638, 759, -1338, 1107, - -1081, -1165, -1038, -484, 1722, 534, 1038, 1102, - -1446, -1212, -1337, -1452, -1422, -1291, -690, 1634, - 1348, 1640, -1044, -184, -757, -683, -100, 1044, - 369, 349, 432, 584, -1137, -528, 1425, 1294, - -842, -257, -32, 289, 639, 796, -1418, -1229, - -1282, -1391, -1421, -1234, -852, -765, 737, 2076, - -1104, -928, -936, -1088, 378, -765, 1603, 581, - 753, 925, -1191, -841, -919, 2886, -907, -232, - 180, 543, 956, 1070, -1314, -843, 804, -1094, - -1209, -1031, -626, 698, 1049, 1152, 256, 831, - -841, -814, -841, -54, 134, 347, 535, 658, - 104, -801, -959, -519, -406, 156, 12, 13, - 380, 494, -1144, -1112, -973, -965, -916, -474, - -225, 460, 402, 734, -1448, -1316, -1278, 231, - -1086, -578, 584, 1115, 1275, 1260, -1321, -963, - -1127, -1288, 41, -1102, -31, 1331, 1003, 1145, - 112, -1270, -1343, -1376, -1114, -778, 392, 1918, - 1165, 1246, -1247, -870, -1232, -1147, -1075, 570, - 181, 1983, 971, 1216, -1309, -1199, 260, -1136, - -950, -742, 1067, 703, 1150, 1144, -1405, -1533, - -1564, -1549, -1264, -737, 1085, 1706, 1806, 1785, - 282, -1173, -1128, -1188, -971, -885, -291, 254, - 841, 987, -142, -1068, -1264, -1232, -1058, 138, - 546, 521, 1096, 987, 890, -936, -1020, -1051, - -871, -521, 1686, 625, 930, 936, -1343, -924, - -1231, -1247, -1052, -951, 1110, 125, 826, 1116, -}; - -static const int16_t fcb44ss[] = { - 6575, -881, -1291, -1258, -1090, -517, -268, -56, - 106, 295, -303, -1134, -1113, -650, -508, 1843, - -235, -141, 454, 832, -1212, 856, -404, -620, - -682, -487, -69, 865, 341, 95, 3626, -1037, - -1366, -1349, -1126, -558, 187, 343, 657, 765, - -410, -735, -1046, -1023, -897, -673, -366, 3174, - 1264, 720, -730, -922, -523, -821, 4042, -463, - 45, 329, 213, -93, 301, -1011, 277, -840, - -820, -451, 417, 470, 739, 953, -1219, -1286, - -1545, -1426, -1209, -803, 1156, 1311, 1329, 1329, - -643, -1136, -1200, -912, 1221, -695, 342, 910, - 905, 812, -996, -365, 4868, -738, -591, -621, - 17, -42, 0, 100, 2085, -1214, -1434, -1432, - -1243, -577, -626, 140, 1357, 1821, -1064, -1261, - -1629, -1525, -1488, -1101, -631, 551, 3556, 3974, - -635, -846, -1005, -646, -803, 123, -151, 357, - 2137, 953, -1168, -1055, -1115, -1061, -823, -651, - 3842, 606, 491, 491, -1297, -1063, -990, -1051, - -1202, -983, -468, -47, 163, 336, -1131, -446, - -683, 644, -660, -675, 1251, 373, 195, -123, - -1109, -430, 1820, 1883, -862, -743, -265, 119, - 66, -41, -1281, -768, 1941, -955, -1054, -856, - 528, 363, 488, 545, -936, -682, -814, 5534, - -826, -347, 58, -38, 168, 14, 1224, -719, - -300, -766, -407, 630, 269, 39, -230, -701, - 1601, -958, -945, -955, -734, -487, -20, 1392, - 544, 282, -118, -1133, -1161, -1065, -939, -213, - -129, -271, 451, 2570, -895, -805, -536, 1455, - 1496, -647, -199, 114, 95, -42, 2230, -855, - -715, -819, 1762, -699, -50, -109, 163, 207, - -334, -759, 3297, -645, 2561, 77, -239, -259, - -275, -445, -1304, 3536, 1610, -526, -926, -582, - -12, 44, -180, -69, -804, 1107, 1451, -868, - -851, -589, -354, -85, 88, 336, -537, -444, - 40, 231, -715, -523, -351, -379, -123, 171, - 1223, -328, -567, 2182, -291, -352, 20, -157, - -338, -635, 2194, -476, 1624, -802, -762, -585, - -245, 48, 63, -45, -32, -646, 847, -556, - -727, -259, 1309, 239, -128, -755, -1018, -640, - 876, -642, -906, 1394, -26, 338, 204, 148, - -988, -521, 135, -807, 1065, -525, -80, -248, - 383, 836, 521, 13, -553, -865, -928, -631, - -137, -83, 446, 221, 1924, 48, -621, -845, - -782, -544, -531, -418, -79, 915, -711, 1247, - -938, -766, -995, 1459, 31, 199, 261, 190, - -670, -1207, -1013, 108, -670, 204, 407, 266, - 473, 998, -606, -923, 1845, -1061, 910, -774, - 268, 493, 178, 61, 1938, -1237, -1010, -1097, - -780, -368, 1125, 354, 398, 550, 1032, -1128, - -1196, -908, -767, 529, 2326, 728, 227, -13, - -1113, -367, 382, -939, -1094, -896, -463, 446, - 896, 1128, -591, -823, -894, 3052, -968, 2157, - -153, -71, 111, 118, -1106, -930, -911, 1663, - -905, -691, -226, 503, 665, 702, 2067, -1149, - -828, 990, -850, -426, -159, 148, 379, 512, - -1268, -1390, -1492, -1343, -1419, 2246, -224, 2124, - 1523, 1338, 522, 1613, -344, -694, -487, -325, - 293, 96, -374, -679, -364, 124, -1201, -1274, - -1078, -513, 15, 1045, 529, 680, 131, -1067, - -1030, -888, -806, -122, 1002, 1302, 757, -473, - -530, -538, -821, -373, 72, 797, 864, 265, - -542, -1090, -241, -1095, -1205, -991, -1172, 5025, - -420, 728, 461, 103, 2325, -915, -1012, -854, - -1117, 2018, -377, -35, 266, 443, -949, -1163, - -1064, -1057, -802, 721, 1278, 470, 308, 263, - 474, -773, -1033, -892, 227, -30, 39, 101, - 456, 476, -1263, 7275, -946, -1157, -1304, -922, - 248, 143, -98, 312, 3419, -402, -649, -629, - -554, -48, 487, 72, -171, -687, -1167, 1869, - -524, 1490, -869, -236, 111, 68, 77, -85, - 1481, 906, -1189, -1321, -1124, -554, 429, 321, - 814, 699, -1048, 486, -858, -1096, -1072, -744, - 1676, -73, 593, 632, 779, -1265, -1470, -1379, - -1050, -548, 781, 524, 1022, 1079, -1149, 3719, - -1064, -1180, -1159, -775, -211, 241, 492, 555, - 3025, 2828, -849, -1133, -1063, -567, -70, -142, - -176, -62, -614, 1745, -684, -610, 1478, -619, - -235, -361, -84, -44, -1155, 1494, -1183, -1210, - -1294, -1017, -330, 210, 931, 1368, -1306, 2714, - -1052, -1128, -1220, -908, 2409, 441, 310, 318, -}; - -static const int16_t fcb44sm[] = { - 5619, -163, -1005, -856, -831, -644, -612, -759, - -770, -456, 199, -551, -1348, -80, 131, -481, - 334, 202, 366, 1246, -1245, 499, -1454, -396, - -675, -257, 525, 1001, 878, 1075, -1004, -1010, - -1127, -947, -976, 332, 3533, 1315, 265, -683, - -1114, 1056, -1009, 1154, -728, -212, 620, 169, - 102, -110, -658, -902, -1238, -1213, -1238, -926, - -735, -455, 1130, 5139, -1184, 190, 1590, -604, - -800, -373, -366, 251, 720, 571, -6, 304, - -1228, -369, -659, -506, -25, -234, 313, 2366, - 623, 1473, -315, 780, 1048, -416, -586, -737, - -1029, -1094, 483, -725, -771, -379, -268, -15, - 697, 1774, -1, -999, -987, -867, -1339, -1255, - -1018, -652, -125, 643, 3006, 2417, -543, 1629, - 1557, -684, -568, -474, -132, -291, -338, -321, - -1250, 641, -158, -935, -575, -575, 154, 415, - 798, 1421, 3147, 1903, -335, -767, -729, -627, - -611, -752, -836, -735, 678, 502, -946, 556, - -821, -51, -256, 94, 151, 70, -808, -324, - -359, 3637, 286, -90, -365, -613, -782, -871, - 75, 1051, -780, -487, 47, 273, 1768, -102, - -828, -1267, -1093, 1420, -624, 225, 1307, 85, - 239, -152, -649, -853, -1072, -796, -644, 1383, - 1143, -199, 94, -25, 70, 52, -1064, 2487, - -844, -607, -587, 148, 726, 224, -238, -484, - -957, -729, 1517, 1334, -475, -317, -253, -186, - 1, 17, -832, 1450, 423, 1408, -576, -825, - -630, -579, -312, 314, 788, 382, -1000, -1060, - -763, 968, -135, 56, 143, 477, -736, 30, - 4023, 68, -266, -420, -538, -751, -893, -879, - -935, 59, 465, 887, -351, 1396, 176, -250, - -684, -1019, -515, -815, -957, -439, 188, 3794, - 86, -98, -245, -829, 1894, -386, -865, 1513, - 24, -506, -281, -615, -476, -364, -1283, -963, - -339, -133, -161, -480, 25, 230, 1364, 1815, - 1766, -844, -1423, -1185, -972, -458, -275, 138, - 1317, 1778, -1295, -874, -1211, -792, -601, -500, - 2301, 901, 1336, 842, 1355, -426, -1160, -959, - -801, -433, 1852, 144, 284, 169, -1122, -851, - -957, 272, -393, 817, 862, 262, 333, 802, - 320, -576, 1615, -615, -886, -311, 108, 13, - 1, 320, -1205, 962, -483, -791, -749, 1158, - 677, -57, 166, 279, -860, 1237, -971, -1057, - -598, -285, 884, 1174, 657, -303, 2254, -706, - -1113, -655, 719, 234, -124, -199, -135, -360, - -758, -623, -385, -18, 3243, 470, -139, -286, - -520, -953, -1193, -1140, -1297, -1137, -764, 25, - 235, 2217, 1501, 1369, 2024, 781, -1353, -835, - -824, -601, -259, -140, 387, 671, 3, -974, - -760, -884, -485, 709, 1505, -95, 321, 739, - 1610, -156, 1515, -76, -420, -369, -189, -506, - -705, -907, -1052, -516, -1048, -996, -471, 1195, - 212, 184, 800, 1665, 747, -1029, -1013, 789, - -703, 559, -139, -98, 380, 523, -355, 2047, - -766, -991, -809, -566, -257, -242, 485, 1322, - 1989, -330, -945, -559, -448, 1241, 811, 10, - -767, -1218, 1600, -755, 428, -729, -355, -665, - -416, -120, 381, 548, -717, -14, 1587, -886, - -9, 353, 839, 201, -454, -1112, -1334, -309, - 660, -375, -661, -511, 1437, 540, 492, 0, - 95, 3911, -237, -301, -562, -483, -569, -799, - -883, -580, -670, -980, -1056, -896, -797, 1551, - 267, 1000, 1617, 75, -1132, -403, -988, -830, - -627, 1164, 1315, 1594, 310, -564, -1091, -563, - 1195, -442, 1086, -344, -176, -258, 175, 476, - 923, -37, -629, -919, 1278, -610, 113, -314, - -81, 192, 731, -944, -1297, -1108, -934, -259, - 640, 1164, 1326, 558, -767, -519, -875, -930, - -817, -533, 496, 2605, 1359, -131, -1010, 912, - -1055, -309, 768, -198, -166, -76, 429, 640, - 3283, -895, -1229, -853, -853, -399, 147, 44, - 237, 495, -833, -909, -1004, -811, 1039, 1627, - -194, 295, 738, 290, -771, 237, -912, -479, - -648, -518, -226, 573, 2346, 419, 1013, 1510, - -865, -873, -982, -557, 598, 50, 81, -81, - -1150, -640, -1011, 1991, -561, -140, 42, 175, - 521, 799, 3231, -46, -1004, -994, -1140, -1094, - -957, -860, 8, 2346, 212, -499, -55, -997, - -623, -588, 38, -58, 975, 1529, -986, -891, - -1121, -619, 1967, -463, -7, 632, 768, 953, -}; - -static const int16_t shape8[] = { - 2765, 1262, 6624, 867, 688, 1884, 3245, 1248, - -2160, 593, 182, -1004, -1067, 687, 1021, -920, - 1396, -242, -2817, -1838, -3351, 1000, 5995, 2459, - -283, 1909, 1452, -4569, 556, -2004, -42, -3393, - -50, -385, 597, 983, 420, 6311, -1572, -1665, - 6128, -1688, -5191, -337, -4199, 371, 1032, -84, - 2169, 931, -392, -250, 137, 831, 8194, -489, - -92, 209, 115, 1453, 246, -647, 936, 1097, - -400, 597, 392, 93, -7709, -711, -724, 2051, - 497, 1919, -876, -769, -172, 2972, 952, 555, - 151, -617, 773, 4840, -3671, 841, 244, -661, - -3424, 958, 81, 532, -315, 796, 5491, -516, - -1, -1371, -531, -5538, 313, -1749, 2413, -835, - -3143, -244, -3470, -850, -4241, -859, -74, 2141, - -1005, 4643, -339, 4089, -861, -6612, 483, -2888, - -580, -45, 3662, 918, -317, 3596, -741, 897, - -2578, -654, -1628, -1865, 629, 3219, 214, -1898, - 1173, -4509, 1682, -2161, 697, -147, 9839, 751, - -1094, -341, -669, -1322, 649, -832, -382, -5467, - -44, 3510, 1312, 3104, -202, 1870, -155, 601, - 719, -22, -350, 394, 81, 397, -9185, -174, - 351, -4717, -4450, 3672, 1163, 2351, 1720, 1048, - -1221, -280, -18, -15, 678, -3931, 4707, -99, - 1823, -535, -1836, 138, 1166, -3031, 5515, 1362, - 1235, 455, 595, -3671, 1102, -163, 62, 1104, - 813, 870, -295, -1088, -299, -3976, 805, -7468, - -412, -2109, 236, 46, -5764, 615, -1475, 853, - 790, -6197, 312, 637, -3923, -422, -1086, -5647, - 878, -1410, 2085, -51, -2941, -769, -63, 838, - 823, 741, 2785, 450, -7003, -121, -915, 60, - -41, 0, -39, 8774, 647, -521, 379, -342, - -344, 818, 1316, 1056, 182, 2765, -467, 7886, - 45, 791, -415, 3864, -2428, 2255, -661, -64, - 1693, 144, 1784, -1194, -46, -1856, 1208, 4131, - 914, 8028, -17, 1939, -1415, 533, 291, -466, - 186, -705, 668, -614, -253, -2190, 287, 3929, - 1472, -1561, 5, 889, -2020, 158, -14, -1419, - 1338, -353, 622, -54, 87, -1104, -2911, 513, - -632, 1533, -267, 22, 6567, 295, 325, 6883, - 963, -373, -349, 183, 896, 1845, -1157, 351, - -367, 1171, 4362, 508, 5632, 704, -1420, -1886, - 686, 5230, -9, 2422, 230, 264, 3738, -270, - -344, -528, -936, 2286, -540, 4274, 337, -665, - 737, 1639, -1307, 5827, 592, -1372, -412, 1419, - 4579, 335, 223, -1067, -112, -446, 149, 1375, - -155, -392, -1980, 561, -67, 341, 6957, 475, - 11449, 39, 81, 766, -1880, 558, -134, -7940, - -489, 249, -886, -358, 6850, 2794, -2217, 1111, - -1222, -1130, -818, 1076, -1823, 865, -2220, 1179, - 4492, 224, -2073, -338, -5351, -390, 133, 496, - -42, -16, 46, 437, 322, -275, -72, 48, - -325, 313, 1108, -1044, -851, -5030, 1035, 4316, - -1281, -913, -1419, -941, 1914, 960, 1242, 202, - 5109, 475, 1254, 1725, -1504, -4, -269, -421, - -150, -4409, -610, -1548, -1684, -817, -210, 72, - -679, -106, -3809, -1137, 4, 7220, -95, 810, - 2432, -331, 492, -81, 138, -62, -613, -636, - 106, 10908, 912, 144, 192, 1251, -3970, -954, - 1145, 1175, -1721, 5326, -1721, -569, -3661, -1166, - 6605, -744, -1494, 853, 134, 3259, -504, -1740, - 180, -207, -659, 196, 179, -106, 118, 789, - -834, 10339, -420, -3002, -456, 113, 6435, 949, - 721, -2709, -1599, -684, -8068, 174, -1416, -58, - 974, 308, -726, 1237, -1594, 519, -131, -198, - -1395, 1180, -173, 338, -5584, -279, -236, 6817, - 89, -220, 3967, -107, 65, 2479, -22, 642, - 7179, 1179, -229, -202, 4948, -5465, 1632, -1285, - 2188, -2037, 1763, 636, 4247, 995, 1176, 2, - -2398, 1236, -661, 382, -1075, 130, 103, -187, - 604, -306, -2635, -2185, 157, 775, 6373, -924, - 1758, -3043, 1707, 2852, -2148, 6779, 376, -1018, - -2374, -989, 249, -5393, -32, 538, -416, -5108, - -658, 1839, 419, 1153, -3956, -617, -1925, 5434, - 626, 1488, -3824, 140, 370, -2230, -7031, 1989, - -581, 639, -4249, -216, 1225, -776, -973, -542, - -2922, -1783, -2430, -3251, 958, 3313, 636, -6277, - 119, -866, -406, -156, -4839, 966, -469, 5559, - 193, 376, -4810, -870, 163, 4130, 2596, 2203, - -114, 2423, -622, -424, 2935, 749, 2500, 4230, - -162, -1489, 2169, -5156, 751, 2748, 2240, -1549, - 4821, 175, 2274, 854, 2993, 838, 322, -2663, - -794, -283, -98, 1393, -709, 362, 285, -1085, - 1075, 374, 1062, 6512, -3375, -3138, 3939, 3628, - 3926, -2442, 1989, -583, -1282, -1882, -3920, -4593, - 540, 2667, -155, 156, -2428, 1229, -436, 1754, - 2815, -1634, -2299, 1155, 990, 3689, -1242, 3145, - 3951, 45, 186, -1110, 257, -335, 8929, 533, - -173, 813, 21, 1584, 541, -44, 1349, 108, - -5163, -684, 5522, -868, -5795, 769, 583, 2827, - -818, -5551, 1485, 37, -631, -262, -4352, -532, - 61, 434, 1775, 8974, -112, -852, -1227, -1645, - 260, 298, -430, 863, -3860, -97, 6467, -328, - -2418, -61, -1253, 1575, 30, -5683, 2113, 973, - -371, -51, 5355, 471, -584, -492, -2187, 2799, - -506, 4435, 1950, -3415, -363, -404, 941, 2628, - -146, 434, 2853, 889, 634, 5749, -54, 126, - 189, -1384, -379, -3205, -540, 1720, 942, -6300, - -286, -58, -1083, 3782, 251, -334, 4172, 631, - 17, 83, 707, 1322, 3273, -573, 1024, -6112, - -540, 4916, 155, -1209, 308, -738, -2150, 786, - -168, 68, -201, -64, -752, -1595, -9188, 320, - -426, 111, -2183, 886, -737, 193, -837, 3219, - 5936, 4022, 764, -82, 3344, -855, 3705, -2652, - 1533, -206, -3673, 1235, 1163, -1217, 3183, 1313, - -745, 6554, 7019, 1302, 2129, 268, -70, 110, - 412, -155, -1703, -4945, 105, -1705, 412, -6588, - 2905, 1279, 73, -2446, -5635, 1168, 2974, 404, - -650, 265, -1773, -1857, -108, -651, 657, -824, - 3352, 177, 155, 1275, 2012, 31, -7, -1065, - 2062, 411, -2325, -208, -6306, 683, 1037, -1060, - 191, -187, -585, 6103, -459, 571, 1640, -693, - 922, -2291, 537, 1934, 263, 3847, -202, 7060, - 136, 4368, 2963, -1032, 18, 1836, -144, -3853, - 474, 2005, 1298, 2396, 825, -2274, 12, 3759, - -394, 907, 490, 2997, 2180, -1570, -1000, 5982, - -129, -820, -3001, 2684, -1132, -2908, 1101, 5044, - 393, -1637, 393, 1343, -1231, 404, 1817, 1463, - -443, 1053, -584, -7756, 45, 499, -4109, 214, - 535, -3348, 54, -1594, 6913, 0, -94, 8772, - 500, 13, 734, 5, 798, -1521, 853, -82, - -263, -619, 1558, 456, 5911, -1376, 1054, -971, - -1275, -147, -111, 4964, 321, 67, 7024, -525, - 620, 883, -1058, -1132, -3313, 630, 226, -6201, - -1011, 1111, -820, -295, 580, 636, 2452, -638, - 6840, -285, 655, 1502, -1049, -567, 329, -33, - -249, 570, 186, 167, 780, 1104, 42, 197, - 10034, -1295, -208, 32, -1473, 716, 159, -6672, - -45, 519, -4300, -246, 3692, 5062, 4305, -748, - -548, 181, -382, -881, -1968, 580, 964, -420, - -327, -3397, -1584, 2770, -3501, 1659, -1252, 2352, - 6, 30, 0, -273, 27, -204, -485, -432, - -6, 176, -428, 1562, 104, -6511, -1084, 2205, - -11, -5254, -132, -508, -69, 373, -1503, 208, - -58, 5311, 92, -966, -6563, -480, -24, 1424, - -1498, -165, 4594, -903, -1787, -353, -7284, 142, - 1008, 875, -6109, -16, 162, 4895, 30, -188, - 2099, 1581, 300, -259, -921, -386, -488, 140, - -482, 7135, -77, 494, -196, 3207, -250, -102, - 318, 978, 161, 7292, 55, -1347, -2605, 898, - 1833, 602, -1988, 630, -145, -102, -414, -133, - 417, -603, 156, -1151, -395, 625, -1676, 86, - 680, 13321, 322, -5816, -292, -223, 4205, -361, - 903, -224, 1745, 95, -6598, 79, 2323, -24, - 263, 778, 146, -939, 1814, 1945, 720, 367, - -2987, 899, -4409, 136, -3185, -342, -3304, 1016, - 284, -345, 2313, -403, 389, -1403, 1835, 151, - -132, -1702, -339, -5679, 2026, -2990, 47, -564, - 399, -2167, 1392, 1384, 5094, -2954, 4467, -22, - -23, 408, 1620, 1381, 2380, 805, 380, -36, - -803, 765, -778, 905, -200, -669, 3942, 289, - 176, -4767, 2015, -3554, 1206, 6071, 180, 2057, - -48, 365, -48, -2423, 585, -109, -1298, 2519, - -525, -589, 374, 976, 3667, 2091, -2890, 1371, - -726, -216, -1027, -116, 2122, -619, -3826, 4649, - 1167, 0, 1237, 1538, 2505, -548, -3093, 1344, - -558, -1927, 199, 2462, 1327, 4597, 833, -3660, - -341, -1010, 428, 148, -1682, 130, 1569, 8785, - -752, -1032, -2407, 353, -379, 3311, 892, 893, - -2596, -217, -835, -2291, 1137, -4339, -58, 2759, - 991, 3527, -281, -6050, -1251, 1802, 8, -3916, -}; - -static const int16_t shape8s[] = { - 2639, 550, 6487, 2812, 1014, 1926, 2959, 757, - -1452, -111, -45, -409, 401, 545, 1545, -1677, - 75, -607, -3658, -368, -4486, 272, 6017, -468, - 1108, 1056, 606, -3288, 1003, -830, -336, -2940, - 247, 227, 1700, 338, -161, 5694, 317, -584, - 6278, -2902, -3862, 293, -3400, 540, 177, -840, - -471, 963, -243, -289, 77, 39, 7626, 333, - 577, 327, -359, 999, -392, 107, 1410, 509, - -983, 36, -193, -68, -7612, -775, -178, 1415, - 1069, 1534, -1276, 1204, 615, 2065, 499, 124, - 265, -454, 1974, 6428, -4028, 1102, -1418, -85, - -816, -64, -46, 926, -960, 78, 4823, -41, - -74, -682, -761, -6598, 3084, -1597, 2945, -861, - -3203, -669, -3717, -310, -2865, -1447, 72, 1987, - 364, 4919, -247, 3678, -196, -6807, -127, -965, - 233, -133, 4000, -76, -182, 3825, 67, 700, - -1934, 545, -2467, -1441, 629, 3409, 512, -3333, - 539, -4896, 3413, -2083, 554, 574, 9430, 296, - -88, -533, -321, -1082, 2363, 42, -50, -5402, - -123, 4458, 1130, 2737, 378, 1509, -3267, 970, - 179, -2114, 602, 479, -438, 277, -9389, 1144, - 2453, -3705, -3842, 3965, 482, 1230, 2211, -281, - -1833, -1741, 1653, -868, 485, -3740, 5371, 989, - 1182, 10, -1812, 233, 1028, -3300, 4698, 1572, - 1580, 928, -314, -3452, 830, -1511, -1079, 554, - 641, 1383, 105, -1101, 1549, -3944, 902, -6557, - 493, -3117, 782, -699, -4806, 910, -259, -28, - 1713, -7012, 570, -1270, -4698, -8, 220, -4295, - 1135, -3905, 945, -467, -2164, -651, 181, 212, - 159, 587, 1587, 1101, -7153, -309, -1470, -1135, - -265, -326, 172, 8840, 726, -780, 170, -1038, - 466, 216, 764, 231, -547, 2456, -420, 8132, - 486, 866, -359, 3351, -1829, 2018, -352, -1353, - 711, 645, 1149, 74, -466, -669, 1009, 3086, - 240, 7468, -182, 1947, -221, 496, -448, 189, - -113, -752, 133, -214, -1310, -144, -1034, 5235, - -1939, -2664, 192, 1526, -2320, 762, -778, 357, - 1251, 424, -225, -1008, -229, -352, -3559, -271, - -1069, 1274, -175, 368, 6453, -505, 31, 7678, - 165, -418, -112, -649, 1421, 667, -334, 1041, - -353, 585, 4109, 1095, 5283, 685, -687, -1459, - 1054, 5048, -194, 2220, 81, 244, 3789, 12, - -923, -1459, 319, 2378, -53, 4097, -662, -1156, - 223, 2589, -547, 4951, -346, -1812, -111, 344, - 5247, 387, -459, -810, 1022, 234, 726, 1840, - -545, -888, 728, 106, 1027, -497, 349, -248, - 11173, -311, 126, 479, -2036, 265, -1286, -7196, - -511, 128, -1833, 496, 7620, 2539, -1809, 962, - -614, -876, 857, 2178, 642, -1180, -2294, 911, - 3932, 711, -1073, -1381, -5317, 237, -414, 579, - -78, -27, -78, -14, 100, -191, 142, -1, - 430, -182, 207, -61, -72, -4866, 583, 5099, - -704, -1496, 1065, -206, 2371, 1496, 1777, -308, - 4802, -1415, 1178, 2650, 312, -338, -250, -64, - -27, -3163, -561, -1283, 952, -902, 354, 1597, - -74, -685, -3266, -873, -744, 7079, 732, 697, - 550, -1362, 251, 34, -742, 0, 105, -608, - -1, 10459, 854, -103, -419, 2286, -3041, -3278, - -51, -491, -187, 4204, 857, -1085, -2501, -1647, - 6740, 605, -2079, 1748, 519, 3462, 106, -699, - 220, -615, -406, 420, 786, 572, 679, 218, - -888, 10283, 129, -2286, -705, -78, 5072, 634, - 702, -6315, -551, -307, -7946, 177, -1897, -579, - 1620, 125, 116, -89, -308, -1018, 142, -506, - -624, 917, -779, 632, -5103, 314, -155, 5687, - 77, -144, 2957, -176, 30, 1347, -426, -51, - 7829, 1201, -592, 1, 4617, -5476, 2216, 414, - 1281, -81, -423, -322, 3623, 447, 863, -375, - -489, 526, -485, 159, 1090, 463, 401, -131, - 223, 1630, -2462, -2261, 623, 1019, 6385, -595, - -654, -2787, 2381, 328, -2069, 5410, -402, -554, - -1594, -860, 83, -5011, -938, 1061, 163, -3523, - -1064, 1215, 761, 1604, -4224, 904, -2706, 4907, - -1838, 3287, -3118, -464, -217, -1187, -6792, 1748, - -569, 613, -3177, -253, 164, -845, 539, -440, - -1871, -2010, -2322, -3026, 478, 2297, -560, -5813, - 768, -1709, -620, 66, -4667, 805, -215, 5366, - -442, -233, -6732, 345, 106, 4483, 1720, 2725, - -109, 2746, -188, 204, 1905, 1225, 253, 3270, - 1912, -1852, -256, -4131, 768, 3984, 473, -1434, - 4380, 208, 2547, 1051, 3347, -171, 629, -2389, - -722, -759, 166, 2192, 325, -193, -289, -945, - -436, 931, 1352, 6918, -2707, -987, 2940, 3574, - 4135, -3205, 351, 927, 128, -1873, -4894, -4816, - -461, 696, -1618, 129, -28, 2195, 2450, 585, - 2557, -1308, -2204, -590, 2345, 3699, -312, 4436, - 3422, -611, -106, -2647, -1752, -73, 8914, -673, - 1625, 850, 720, -1182, -245, -113, 882, -223, - -4873, -1009, 5643, -97, -4779, -155, 444, 2894, - -876, -5534, 1268, -132, -881, -389, -4250, -153, - -44, 986, 1820, 8671, 662, -344, -198, -1909, - 1083, 114, -318, 1070, -3293, -375, 6621, 232, - -2973, -100, -483, -529, -120, -5312, 1702, 651, - -631, 485, 5675, 50, 1132, -465, -1053, 2675, - -1592, 5565, 1036, -2808, 325, 999, 524, 2813, - -265, 337, 4226, 514, 576, 6047, 175, 204, - -514, -617, -94, -2862, -294, 1774, 978, -7040, - -169, 835, -829, 2258, -37, -319, 2750, 138, - -289, -1092, 78, 1032, 4316, -1201, 808, -6243, - -940, 4136, 89, -1076, -647, -255, -207, 227, - -70, -62, -202, 66, 24, -988, -9542, -225, - -739, 161, -2698, 117, -608, 173, -629, 1770, - 5037, 5145, 2530, -1028, 3077, -496, 4671, -1859, - 2148, 447, -4231, 170, 713, 323, 746, 1447, - -1880, 5069, 7765, -492, -775, -659, -770, -59, - -258, -92, -1683, -4639, -1727, -2128, 545, -5060, - 2536, 1549, 492, -1280, -6034, 965, 3244, 475, - -1208, 680, -283, 295, -357, -257, 1753, -362, - 3159, 106, -181, 1805, 947, -1002, -136, 756, - 1189, 237, -2427, -263, -5746, 13, 2171, -1197, - -319, -372, -1300, 5458, 955, 1224, 618, -1087, - 2661, -2026, -20, 2137, 342, 4076, 482, 5441, - -6, 2126, -143, -1596, 274, 1009, 94, -3446, - 398, 1079, 289, 2042, 883, -2005, -320, 3848, - 395, 472, 615, 3245, 753, -1881, -216, 5670, - -64, -565, -2560, 1574, 772, -3824, 932, 4830, - 1182, -1054, 390, -40, 1833, -350, 151, 149, - -966, -62, -713, -8794, -593, 87, -3523, -243, - 560, -3296, 244, -775, 7174, 749, -271, 8566, - 99, 1258, 1239, -489, -107, -1699, -611, 1046, - 65, -509, 524, -354, 6400, -248, 148, -682, - -93, -1584, -61, 4509, 479, 110, 7116, -295, - 480, 1545, 3, 127, -2292, 894, 1261, -6288, - -45, -410, -402, -356, 2649, 649, 1652, -643, - 6587, 117, 876, -33, 956, -302, 1619, -1023, - -99, 386, -86, -498, 684, 1189, 146, 381, - 9832, -97, 264, 91, -1197, 461, 374, -6788, - 427, 294, -4776, 0, 2868, 5199, 4573, -827, - -1867, 623, -1214, -573, -1099, -1476, 306, -701, - -224, -4261, -1135, 2500, -4758, 1469, -101, 1812, - -129, 15, 760, -149, -892, -1417, 761, 1213, - -417, 1569, -98, 1675, -139, -7382, -633, 2584, - -519, -5483, 29, 320, -383, -596, -295, -357, - -416, 4054, -457, -355, -5213, -840, -319, 1321, - -424, -129, 5225, 181, -2696, -174, -7363, -327, - 519, 860, -5132, 275, -141, 4943, 204, -200, - 2989, 939, 390, -461, -333, -394, -174, 312, - -129, 7257, -402, 860, -1, 2677, 901, 609, - 248, 935, -493, 8147, 2081, -1171, -2145, 1560, - 1634, 55, -1746, 561, -747, 931, -712, -544, - 798, -98, 580, -829, -546, 238, -2052, -197, - 802, 13067, 373, -6438, 1159, -845, 4313, 19, - 670, -627, -944, 1277, -6997, -609, 1913, 607, - -454, -89, 859, -43, -71, 494, 169, -713, - -2014, 1570, -4712, 233, -4113, 210, -3689, 1019, - 200, 49, 1800, -611, -472, 1234, 579, 363, - -134, 233, 101, -5539, 1924, -1734, -982, -928, - -707, -1238, 1586, 3676, 4741, -2770, 3105, 942, - -1933, 1363, 288, -2528, 160, 485, -38, 23, - 113, -19, -518, -110, -173, -170, 589, -473, - 296, -3742, 1109, -2977, 1349, 5899, 98, 3130, - 855, 499, 3, -3111, -592, 572, -890, 687, - 697, 194, -344, 1139, 3255, 1270, -2451, 1958, - -395, 267, -951, -2224, 2108, -11, -3357, 2602, - 2403, 1596, -532, 2701, 2251, -1217, -2148, 691, - -757, -2051, 373, 1964, 1493, 4756, 1246, -4345, - -496, -1333, -20, -84, -1558, 305, 1183, 8148, - -628, -702, -1730, 232, -261, 2732, 245, 353, - -3745, 1013, 186, -2042, 810, -3894, 351, 2501, - 852, 4162, -425, -4941, -1536, 2237, 1348, -4274, -}; - -static const int16_t shape11[] = { - 347, -5391, 106, 156, -182, -36, 177, 401, - 700, 524, -1343, -402, -6982, 63, 194, -14, - 82, -36, -677, -393, 187, 7364, -507, -1173, - -759, -3759, -728, 2970, 1334, 32, -1322, -2965, - 156, -839, 382, -6382, -149, 874, 1352, -35, - -499, 99, -425, -3118, -32, -1596, 5608, -822, - -41, 2974, -592, 615, 1777, 2364, 5189, -4171, - -581, 936, -527, 318, -1606, -551, 5350, -448, - -40, 7476, 189, 319, -1390, 10, -921, 10016, - 573, -1065, 829, -1190, -22, -4263, 87, -1742, - -325, 313, -188, 540, -5542, -188, 511, -168, - -518, 17, 152, 1966, -2568, -860, 2735, -1210, - 404, -144, -6873, -129, 434, -2978, 2829, -48, - -9196, -1829, -11261, 1492, -4938, 1802, 93, 384, - 1340, 236, 10066, 731, 861, -195, -7571, -77, - -481, -700, 4694, -734, -6317, 281, 1773, 175, - -5535, 532, 31, 7012, -637, -3586, 1096, 3596, - -197, -7837, -611, 1825, -26, -259, 2307, 12, - 729, -1958, 156, 262, 5494, 26, -5792, -3146, - 450, -1075, 297, 509, 154, 668, 191, -268, - -1585, 369, 1314, -693, 677, 1482, 198, 378, - 11088, -83, 2321, -193, -1082, -3053, 20, -271, - 12975, 272, 1114, 476, -798, -309, -159, 5406, - -109, -675, 621, -2564, 11190, -1342, -88, 428, - -465, -4633, -503, 106, -9448, -454, -28, -402, - 1271, -7972, 754, -207, -2491, 518, -3701, -542, - -1268, -617, -177, 467, -130, 990, 4087, 857, - -524, -5822, 145, 217, -7703, -275, 6647, -81, - 550, 887, -433, -802, 532, 643, 188, 1965, - -920, -284, 3711, 1196, -8896, -357, -626, 908, - -284, -706, -1582, 182, 7705, -138, -2372, -158, - -888, 4247, 4381, -6722, -1619, -1810, 632, -1176, - -62, 4261, -89, 265, 1405, -1449, -389, -7068, - 258, -244, -272, -8149, 37, -457, -8839, 3243, - -4291, -396, -3935, 907, -58, 2388, -908, -1209, - -635, -487, -1717, 6989, -4834, 2136, -822, -699, - 2187, -96, -9775, -3464, 795, 634, -823, -669, - 146, -843, 15, -227, 671, -707, -10004, 198, - 81, -1611, -34, -2127, -2385, -689, 622, 1834, - -63, -4925, -215, -1181, -514, 7701, 607, 2030, - -264, 2479, 913, 178, 3625, -194, 613, 877, - -384, -7732, 1008, 2117, 528, -301, 540, -80, - 559, 28, 7542, -496, 1146, -6573, -1457, 7789, - -227, -1671, -76, -371, -865, -141, 42, 96, - 277, -410, -5606, 328, -8954, -222, -1792, 981, - -120, -650, 2269, -1412, 1038, -186, -8530, -264, - 2284, -727, 1511, -4611, -1653, 1985, -50, -8985, - -245, -3315, 407, -915, -23, -70, 30, -669, - -303, 902, 84, 433, 217, -8303, 7847, -1865, - -680, 254, -38, 364, 16, 50, 90, -534, - -4649, -800, 969, -1081, 454, 147, -62, 8797, - 84, -912, -518, -351, 76, -560, -1438, 629, - 16384, 656, 151, 880, 396, -90, 752, -138, - -861, 9605, 258, -440, -6441, 434, 5765, 282, - 1494, -260, -180, -769, 7867, -86, 536, -262, - -230, -8956, 5857, -591, 1533, 418, -505, -156, - 1165, 415, -168, -1504, -336, -667, 527, 5725, - 42, 429, 1691, 1, 85, -196, 3681, 36, - 469, -364, 559, 910, -1848, 259, 249, -1688, - 261, -36, -592, -156, -69, -5938, -180, -294, - 22, -903, 1389, 4853, 121, 5185, 970, 1210, - 561, 926, 472, -183, 6623, 357, -78, -5877, - 91, -188, -6746, -146, 342, -5648, 3697, 1336, - 728, -69, 398, 2667, -2103, 1901, -807, 258, - 72, -137, 341, 71, -169, -104, -83, 206, - -420, 1187, 744, 120, -5151, -574, 72, -8553, - -312, 140, -69, 6067, 5229, 202, -1722, -164, - 73, 1695, -1064, 234, 24, 4881, -849, -460, - 8641, -328, -1217, 1666, -283, -76, 2772, 401, - 843, -4756, 297, 8593, 367, -732, -225, -198, - -3936, 248, -436, 473, -19, -441, 164, 220, - -266, 3, 106, -244, -5814, 597, -666, -245, - -9298, -867, -480, 280, -40, -139, -6378, -4972, - -886, 3062, 747, -1991, -1668, -423, 534, 866, - -73, -6501, -195, 324, -51, -123, 298, 500, - 193, 278, -8503, -297, 1034, -16, -209, 7451, - 521, -305, -297, -1537, -3025, 689, 248, 319, - 5393, 1497, 2228, -773, -141, 2184, 1024, -4535, - -9160, -600, -932, -2145, -539, 460, -1943, 4265, - -2512, 4416, -304, 1744, 489, -362, 898, 2236, - -2224, 49, -192, 332, 366, -143, 329, -7747, - -4, 1075, 116, 551, 19, -7, 7090, -169, - 837, -71, -371, 451, -31, 474, 867, -421, - -4544, 78, 3208, -549, 1984, 1386, -2208, -1402, - 1616, 189, -37, -6953, -5733, 1589, -1314, 1040, - -1480, -5608, 2627, 3517, 250, 7930, 94, 4687, - 1522, 5543, -130, -462, 7613, -654, 647, -6187, - 139, 342, 5069, -729, 128, 17, -49, 176, - 122, 826, 503, 76, -196, 15583, 12884, 746, - -3942, 814, -1744, 1774, -338, 3089, -1694, 559, - -5355, 2834, -1448, 108, -329, -711, 350, 171, - 297, -123, 672, 625, -5884, 6822, 842, 276, - 242, -2254, -623, -846, 2441, 887, -2066, -1019, - 1329, 107, -83, 826, -67, -352, 549, 137, - -1023, -184, -11, 13790, 48, 883, 3538, -533, - -5553, 861, 738, -436, -5259, -66, -405, 3777, - -574, 738, 253, 363, -76, 288, 324, -337, - 157, -119, -97, 171, 514, -1932, -5171, 579, - 249, 1072, -204, -194, -311, 655, -6728, 186, - -178, 99, 5749, -329, 419, 924, -1131, 598, - -15, -103, -2277, 186, -716, -542, 153, -226, - 5689, 219, 52, 3706, -917, 140, -10576, -151, - 1060, 645, 404, 1310, 331, 216, -1413, -6030, - -5069, -3992, 1366, 932, 1559, -87, 7799, 3854, - 3762, -1043, 474, 1184, 102, -2775, -1199, -1079, - 358, -63, 9784, 141, 3947, 194, -132, -332, - -512, -212, -5839, -227, 7759, 807, -597, -1782, - -148, -352, -1225, -692, 147, -1970, 3508, -947, - 3463, -197, 4737, -698, 578, -172, -775, 8167, - 3102, 883, -914, 16, 827, 114, -1916, -909, - -606, 87, 1036, -435, 102, 96, -370, -204, - -11952, 21, 477, 1285, 6281, 855, -7717, 1155, - -501, -597, 5943, 145, -630, -3406, 13, -4211, - 679, 6570, -231, -6042, -503, -194, 1437, 5640, - -1222, 8181, 386, -986, -503, 1221, 839, 763, - -277, -1787, -1491, 5, -206, 42, 2800, -332, - -2841, -143, -456, 646, -668, -117, 883, 86, - 7111, -270, 624, -1133, -308, -479, -9149, -1424, - 242, -12048, 8, 2307, -6530, -529, 462, -1346, - -153, 4315, -182, -675, -78, -480, -49, 398, - -408, -1440, 8196, 436, -561, -184, 175, 1799, - -154, -439, -721, 2170, 322, 6555, -539, -1672, - -629, -2985, 239, -37, 7544, -1048, -1241, 7241, - -636, 2044, -750, 1206, 1363, -530, -5960, 342, - -7440, 616, 372, 4572, -118, 343, 1086, 570, - -164, 553, -433, 562, 33, 8225, -235, -234, - 1230, 234, 906, 563, -73, 10464, -353, -644, - -1453, 1119, 237, 670, -112, 7083, -451, 3410, - -105, 3244, -1331, 102, 738, -3602, 76, 413, - -318, 10, -5471, 1024, -335, 246, -7820, -164, - 2515, -1411, 673, 6022, 50, -6715, 268, 2152, - -951, -60, 234, -2085, 342, 3002, -169, 2473, - -667, -6846, 870, 5467, 150, -66, -4294, -299, - -612, -3859, 177, 353, -4726, 547, 340, -5646, - -2022, 117, -4949, -303, 280, -266, -361, 673, - -139, -5, -7123, -264, 243, -5245, 351, 656, - 5005, 682, -107, 298, -79, 1407, -449, -797, - -669, -552, -242, -8013, 56, 4092, 1583, -3981, - -49, -7972, 390, 366, -31, 1126, 272, 5120, - -10, 1147, -3682, -155, 252, 163, 455, 358, - -746, -2719, -431, 444, -433, 432, -357, 5370, - 328, -3, 1748, 514, 7198, -527, 172, 401, - -59, -3586, 1443, 534, 1029, 539, 3723, 5392, - -6619, -2559, 2344, 282, -980, 97, -317, -786, - 475, -8646, 307, 447, -3107, 211, -56, 3344, - -1549, -9223, 454, 352, -27, 205, 503, 260, - -372, -631, -1165, -6543, 444, 1535, 404, -1752, - -43, -9381, 754, -94, -7134, 2064, 170, 8222, - -280, -1250, -347, 1688, -1203, 239, -1048, -4570, - -4720, -434, -1008, -4151, -2211, -1414, -506, -5411, - 5379, 984, 4587, -63, 143, 968, -203, 5315, - 591, -756, 1228, -372, 703, 6829, -76, 6935, - 467, 3119, -2, -3825, 175, -4000, -3012, -7745, - -832, -2582, 173, 1992, 3768, 275, 39, 603, - -536, 5851, 474, 254, -72, 1286, -836, 5576, - 1357, 3524, 406, -9214, -554, 3974, -352, 1763, - -482, 658, 1628, 3885, 1938, 6172, 1693, -5183, - 150, -6729, 1238, 1062, -10035, -428, 48, 421, - -185, 659, -426, -633, 131, -741, 462, -463, - -391, -193, -270, -682, -343, -12130, -86, -148, -}; - -static const int16_t shape11s[] = { - 22, -5296, -415, -206, 306, 265, 189, 376, - 721, -1503, -429, -538, -6008, -97, -385, -570, - -313, -1469, -219, -1661, 10, 6256, -1230, -635, - -28, -4208, -344, 394, 138, 1174, -170, -822, - 114, -1087, -101, -7362, 84, 862, 1514, 341, - -115, 320, -120, -1625, 55, -719, 1443, -733, - -577, 7197, 148, 26, 120, 1969, 4940, -3777, - -607, 1675, 64, -634, -84, 334, 6882, -644, - -232, 5008, -316, -164, -138, -16, 15, 9441, - -74, -65, 262, 834, 1143, -101, 434, -329, - 123, -204, -45, 147, -4586, -742, 464, 1412, - 548, -1602, -56, 1356, -771, 263, 709, -481, - -193, 345, -8395, -41, 36, -1900, -178, 816, - -7590, 31, -3011, -371, -2698, 2234, -99, 0, - 714, -845, 9357, 701, -1269, -187, -4227, -450, - -73, -1637, 4679, -138, -4470, 356, 1416, 1462, - -3162, 453, -61, 5243, -241, -2385, 438, 4919, - -252, -3781, 150, 335, 58, -185, 1870, 179, - 192, -2572, -454, 77, 4819, 1891, -4843, -2106, - -472, -3842, 167, 1092, -671, 194, -870, 139, - -115, -455, 452, -519, 299, 1024, 330, -99, - 11189, 82, 57, -849, 167, -4190, 639, 768, - 7477, 626, 94, -1259, -303, 181, -280, 2873, - -589, -461, 1591, -29, 6940, -1264, 120, -282, - -159, -3755, -4, -61, -10172, 152, -12, -200, - 111, -8471, -243, 400, -842, 1661, -3099, 500, - -451, -423, -193, 230, 423, 263, 5011, 1010, - 1044, -4781, 707, 84, -6091, -213, 5193, 434, - 534, 1100, -520, -1590, 75, -322, 2, 2008, - -534, 153, 2641, 1510, -6830, -246, 4, 271, - 75, -1308, -1934, -257, 6748, 589, -301, 627, - 1197, 3708, 4450, -5582, -1312, -2859, 881, 429, - 552, 738, -882, 984, 488, -868, -464, -6969, - 721, -2078, 417, -6121, -184, -128, -7840, 2659, - -2584, -254, 176, -790, -727, 482, 357, 104, - -441, -158, -980, 4563, -4098, 1086, -1217, -562, - 2033, 512, -8331, -3506, -73, 808, -372, -1602, - 748, 911, -599, -1499, 58, 309, -10000, -115, - 70, 1603, 280, -146, -817, 517, 18, 1355, - -121, -4134, 152, -1300, 247, 7258, 415, 130, - -27, 2108, 337, -816, 2480, 396, 533, 66, - -171, -6213, 47, 3081, -648, -930, 1810, -233, - -433, -588, 5526, 58, -18, -3498, -381, 8009, - 7, 1229, 152, -410, -567, 423, -354, 463, - -82, -146, -2868, 271, -5773, 2694, -1006, 150, - -113, -521, 2553, -278, 593, -69, -6517, -785, - 369, -2483, -216, -3144, -889, 1724, -168, -6303, - 171, -1895, -798, -137, -172, -746, -54, 162, - -607, 409, 201, -284, -143, -10681, 7747, -1148, - 303, 58, 4, -96, -485, -146, -286, -577, - -644, -512, 236, 576, 421, 93, 293, 10284, - -2, -117, -590, -546, 350, 445, -301, -300, - 10823, -224, -96, -551, -148, 1042, -125, 224, - -706, 8583, -195, 52, -2732, 200, 4419, 390, - 870, 100, -184, 233, 6179, -317, -472, 1964, - -302, -8722, 2509, -644, 488, -3101, 891, -253, - -38, 133, -15, -1365, -779, -612, 673, 5587, - 834, 377, 835, -2018, 75, -185, 3641, 121, - 693, 63, 503, 646, -7, 348, 141, -1311, - 532, -513, 95, -315, -65, -6478, -16, -848, - -210, -120, 676, 5125, 533, 4147, -622, -4, - -150, -1507, -124, -185, 5365, 267, 1073, -4479, - 173, -204, -4164, -952, -23, -4088, 1391, 205, - 712, -473, -373, 547, -685, 4542, -49, -71, - 33, -271, 132, 246, -188, 6, -309, 118, - 96, 1774, 158, -83, -3573, 1175, -122, -6619, - -1677, -1161, -266, 4776, 3453, 62, -346, -450, - -1380, 103, -457, -1260, -71, 4271, -338, -1394, - 6462, 395, 647, 2430, -735, 444, 1837, 403, - 144, -5573, 211, 4608, -15, 804, 70, 1969, - -3451, -138, -352, 1176, -171, -518, -114, -88, - 335, -308, -64, -428, -4115, 318, -205, -126, - -7854, -609, 105, 144, 270, 266, -4543, -5246, - -311, 587, 305, -115, 372, 727, -294, 414, - 877, -7899, 411, -538, 394, 535, 233, -826, - 329, 491, -4848, -650, 331, 1026, -140, 6474, - 194, -457, 98, -871, -2293, 873, 353, 812, - 4510, 1102, 379, 651, -214, -110, 20, -2749, - -8040, -96, 221, 221, -39, 444, -280, 2814, - -536, 3509, 111, 830, 594, 553, 47, 2812, - -1898, 203, -353, -60, 371, 181, 824, -5448, - 297, 476, 42, -133, 97, 425, 8586, -317, - 121, 453, 1014, -350, 175, 747, -78, -287, - -5832, 625, 4170, -308, 1853, 2846, -3, -876, - 535, 431, -411, -2139, -6021, 374, 298, 1572, - 19, -4069, 1567, 144, 3, 5541, -438, 920, - 87, 1728, 230, 807, 5848, -413, 7, -6241, - 214, 205, 1312, -675, 70, 264, 114, -24, - -482, -72, -296, 327, 249, 11047, 11070, 18, - -937, 350, 22, 362, 555, 815, 130, -125, - -4545, 2662, 203, -318, -305, 323, 633, 416, - -254, 301, 99, 407, -4951, 4766, -790, 1334, - 912, -1046, -350, -135, 3744, 22, -1647, -422, - -151, -113, -130, -345, -2, -263, 18, -24, - -771, -34, -543, 10259, 183, 0, 1743, 1267, - -2554, 320, 611, -1064, -1446, 875, -808, 4865, - -816, 3452, 68, 326, -178, 177, -10, -138, - -33, -93, 65, 264, 185, -157, -5749, 110, - 407, 1240, -698, -61, 176, 1557, -6012, -606, - -555, 458, 3226, -939, 933, 153, -32, 928, - 69, -490, -1543, -87, -20, -196, -327, 423, - 7911, -189, 178, 335, -194, 459, -10572, -196, - 174, -286, 502, -1041, 12, 39, -101, -3983, - -1650, -2902, 386, -151, 1051, -619, 6854, 3408, - 1140, -1854, -755, -40, -1108, -1502, 221, -397, - 375, 1081, 10375, 389, 270, -239, 311, -212, - 384, 1237, -2951, 199, 5281, -56, 34, -704, - 942, 1169, 33, -310, 97, -1216, 3023, -836, - 3256, 404, 3951, -257, 2139, 111, 179, 8255, - 611, -240, -252, -367, -251, -296, -2282, 957, - 61, -265, 720, 232, 34, 146, 204, -290, - -9923, 529, 65, 696, 2958, 352, -3852, 1248, - -743, -395, 5969, 92, -132, -1206, 314, -4013, - 717, 5157, -770, -1878, -1201, -958, 525, 4028, - 116, 6772, -45, -1086, -335, 5815, 51, 57, - -85, -2301, -133, -300, 7, 227, 3429, -1075, - -4353, -832, 30, 1259, -484, 451, 604, -717, - 6765, 294, 118, -410, 299, 592, -3845, 66, - -502, -9088, -74, 259, 450, 475, 202, -1792, - 23, 4719, 709, -398, -1676, -351, -898, -622, - 145, -1392, 7305, 1014, -80, 519, -2065, 1531, - 860, -1448, 134, 1683, 689, 7179, -345, -327, - 1004, -2467, -340, -1302, 5825, 373, 50, 6796, - 314, 13, -270, -426, 702, 279, -4392, -508, - -6521, 60, -278, 2479, 847, -360, -68, -1948, - 91, 969, 421, 459, -341, 6020, -550, -77, - -687, -754, 5, 109, 410, 10860, -183, -317, - -734, -87, 501, -601, 158, 5836, -1057, 1236, - -850, 2965, -330, 547, 1249, -2804, 127, 218, - -455, -805, -4002, 108, -569, 660, -5356, -1091, - 581, -445, -311, 6409, 510, -6789, 519, 1607, - 296, 342, 368, -1440, -846, 1997, -227, 2332, - -2062, -4657, 1030, 5322, 135, 131, -3414, 320, - 1030, -3341, -256, -373, -4565, 1222, 171, -4972, - -1444, 303, -5427, 435, 208, 251, 467, 539, - 136, 199, -8876, -195, -771, -3096, 740, 368, - 1047, -490, 83, 485, 168, 531, -635, -801, - -953, 4, -95, -7603, -59, 2023, 739, -702, - 263, -9230, -313, -997, -510, -772, 156, 3986, - -113, 398, -2602, -1079, 195, -211, 128, 1917, - 221, -965, 11, 71, -101, 180, -36, 7839, - -144, -722, 288, 429, 5704, -984, -510, 775, - 440, -1849, -1348, 1989, 300, 43, 1928, 4341, - -3840, -2427, 2025, -660, -293, 23, -249, -177, - -327, -7858, 33, 245, -1334, 237, -687, 2800, - 30, -8807, -404, 43, 183, 289, 528, 510, - -197, 590, -94, -5423, 381, 1317, 141, -1639, - -432, -7628, -224, 56, -7788, 113, 134, 6981, - -636, 756, -743, 97, 159, 1263, -143, -2941, - -2680, -479, 1395, -1667, -472, -992, -451, -5708, - 4262, 334, 3053, 76, -584, -599, -276, 3518, - 264, -2118, 358, -106, 911, 5053, 480, 4538, - 949, 5203, -103, -14, 177, -3397, 55, -6813, - 680, -1788, 145, 2267, 1104, -789, 54, 261, - 228, 5494, 15, -224, 192, 740, 0, 7632, - 398, 2879, 430, -8212, -657, 815, -228, -488, - -90, -1296, 595, 2979, -15, 4055, -252, -3883, - -935, -7654, 330, 97, -10200, 462, 223, -1017, - -309, -342, -124, -1258, 211, 351, 316, 414, - -91, -18, -202, -74, 410, -11127, 326, 261, -}; - -static const int16_t shape16[] = { - -855, 1549, -4841, 629, 932, -5896, 840, -2041, - -305, -2574, 343, -31, -780, -773, -353, 403, - -1907, -2371, -555, -324, -479, 6961, -286, -4290, - 626, -953, -14, -1681, -443, 1504, -366, 513, - -1206, 870, 9239, 112, -213, 425, 381, 1802, - 750, 594, 61, -152, -2060, -8997, -752, 197, - -493, -176, -389, -591, 2988, 654, 2404, -204, - 304, -279, 202, 66, -185, 415, 159, -1514, - -6775, -37, -2617, -1246, -4012, 1208, -554, 3240, - -655, -394, -1464, -4448, 388, 1058, -364, -1760, - 1081, -558, -116, -108, 99, -925, 763, -1301, - -251, 258, -33, 311, 555, 227, -279, -601, - -135, -675, -10615, -937, 158, 503, -2044, 1075, - -114, 4278, -9040, 67, -1076, -705, -122, -533, - 3299, -1826, -1316, 708, -3840, -740, -370, -1074, - 87, -462, 2177, -1177, 57, -6311, -170, -777, - -256, 435, 291, 10371, -82, -425, -1757, -196, - 3824, -6289, 62, 4506, -519, -783, 1155, 878, - 295, -2044, 305, 186, 263, -1716, -482, -5678, - 415, 2709, 213, 7531, 1376, 813, 1803, 190, - 398, 6483, 1425, 235, 2713, 520, -2892, -1191, - 6074, 654, -6535, 320, -736, -478, 2563, -309, - -3477, -155, 275, 1024, 390, -386, -331, 14043, - 251, -410, 1496, 24, 1272, -816, 549, -238, - -2489, 158, 194, 1, -306, -3088, -264, 200, - -30, -520, -472, -30, -464, -764, 440, -659, - 88, 778, -31, -1794, -3817, -344, 887, -551, - 115, -763, -5338, 2906, 50, 736, 5536, -1101, - 330, -405, 416, 1022, -93, 71, 10034, -200, - -1258, -3405, 480, 141, 399, 500, 311, -503, - 301, 4398, 454, -922, 975, -101, -775, -81, - -1723, 1077, 857, -1682, 813, 847, 342, -276, - 3582, 2991, 5571, 713, 1280, 596, -1325, -1087, - -681, 1411, 391, -1728, 492, 544, 1512, -724, - -7445, -426, 6, -534, -3643, -1598, 2650, -834, - 2096, -333, 67, 1746, -1584, -1003, 1272, 1710, - 1666, 176, -11716, 329, -1829, 385, 802, -382, - 2244, -8, -222, -2351, 369, -1067, -9354, 293, - -51, -1849, -500, -2350, -1824, -826, -450, -2155, - 456, 245, 1796, 320, -73, -306, -122, 290, - 118, -298, -675, -180, -828, 86, -44, 165, - 435, -8249, 769, 630, -1670, -762, 453, 5893, - 259, -92, -1003, -358, -32, -1350, -535, -289, - 409, -558, -344, -752, 6037, -680, 2471, 581, - -351, 1251, -5827, 194, -104, 815, 1257, -619, - 243, 410, 4455, -969, 50, 1286, -1013, -293, - -7740, 73, 615, 523, -149, -824, 2235, 1571, - 970, 944, 4778, -132, -5082, 83, 129, -820, - -803, 694, 1615, 1163, 517, -402, -80, 762, - -107, -419, 142, -294, 11298, 301, 484, -513, - 105, 547, 1130, -4253, -742, 376, -1545, 1076, - 4372, 2338, -2847, 495, -190, -2444, 931, 6487, - 117, -1273, 1488, -75, -322, -487, -2614, -251, - 1233, 4111, -321, -219, -7961, -11, 107, -808, - 450, 111, 4395, 89, 772, -1878, -1894, 1075, - -544, -9467, -459, 637, 842, -956, -738, 4452, - 777, -75, -209, -302, -796, 785, -7413, 321, - 649, -55, 114, 43, -1026, -223, -611, 209, - -5543, 8206, 907, -3358, 1452, -543, -3173, 525, - -95, 35, -475, -525, -705, -569, 350, 206, - -108, -1523, -680, -283, -2583, -4992, -59, -968, - -1719, -2750, 5884, 455, 29, 436, 784, -101, - -216, 110, 612, -511, -12, 98, -67, 177, - -1210, 222, -345, 243, -12670, -472, 282, -2149, - 687, -2631, 4434, 77, -521, -404, -934, 212, - -695, -369, 1138, 1348, -905, 501, 299, -10467, - 1018, 818, 1941, 31, 257, 1219, 944, -157, - 1968, -1649, -126, -440, -599, -1, 6190, 2574, - -332, 753, 195, -131, 5972, -297, 672, -86, - -143, -303, 5, -121, -154, -613, 5541, -1516, - -304, 962, 69, -1857, 4142, -134, 706, 896, - -1226, -135, -310, -9261, 1135, -3437, 620, 802, - -33, -582, 1909, 1407, 242, 2599, -1533, -279, - 836, 8070, -1207, 5745, 200, -77, 162, 781, - -466, -1555, 3297, -957, 225, 1290, 7, 677, - 41, -549, -2778, 1400, 379, -3367, 369, 615, - -6402, 527, 58, 5679, -114, -180, 2842, 88, - -2611, -50, 371, 161, -444, 2062, -38, 272, - -8562, 769, 18, -2593, -226, -503, -959, -1295, - 189, -371, -675, -1528, -98, 514, -1236, 116, - 202, 13662, 1596, -328, 61, 3567, -486, -3316, - -8473, -317, 2868, -419, -17, 535, -965, -503, - -3848, 2222, 620, -1740, 2, 6505, 473, -297, - -70, 3043, -51, -1520, 993, 1046, 1965, 3240, - 1971, -60, -650, -53, -248, -4428, -365, -3723, - 1122, -1681, 1629, 1358, -17, 1136, -256, 2344, - -282, 156, 127, -155, 318, -1281, -1066, 57, - -889, -253, -1396, -579, -920, -1006, -9202, -703, - 195, 5186, 241, 1742, 996, 118, 1431, 4415, - -2452, 6837, -1272, -569, 3485, 328, 441, 832, - 553, 94, 648, 92, -378, 11167, 775, 457, - 1712, -24, 941, 5433, -1645, 2166, 249, -55, - -1816, 383, 735, -876, 443, -568, 293, -1266, - 6963, -178, -174, -1186, 1119, -208, 821, 1499, - -1496, -2171, 1434, 874, 133, -7466, -545, 2193, - -775, -1405, -1205, -575, -1996, -645, -552, -263, - 8861, -517, 76, -992, 278, 2417, -1369, 35, - -1461, -1399, 517, 185, -2895, 347, -3871, 3644, - 284, 3284, -12, -169, -1981, 1196, -67, 2868, - 910, 134, -530, 150, -1328, 1902, -746, 351, - -222, 522, -5702, 797, -1900, 241, 2270, 764, - -335, 1348, -349, 784, -1586, -537, 148, 3211, - -1692, 56, 1678, -321, -290, 7902, 69, 52, - 310, 337, 250, 596, 9998, 336, 1037, 163, - 64, -441, 2894, -1033, 730, -718, -1252, 459, - -131, 7840, -922, -555, 5671, 299, 689, 1115, - -646, -505, -263, 608, -494, 0, 442, -1802, - -598, -701, -4184, 70, -1319, -90, 9155, -339, - 0, 121, 462, 735, -639, 481, 125, 6924, - 3379, 683, 3053, -1219, -499, 1067, -148, -2705, - -11, 795, 1675, 898, 226, 1232, 49, -572, - -9309, 2223, 949, 767, -821, -91, 1075, -352, - -7829, 554, -593, 1284, -245, 1239, 1166, -1157, - -5274, 808, 871, -1446, 7575, -397, -755, 752, - 4193, 179, -205, -37, -750, -2675, -407, -700, - 220, -77, 1604, 63, 461, -9994, -645, -1629, - 103, 576, 132, 10005, -49, -1005, 97, -1608, - 515, -10, -146, -1878, 880, 429, -1271, 996, - -365, 76, -409, 2461, 29, 1159, 217, -6240, - -200, -746, 118, -1884, 457, -816, -608, 3215, - 244, 749, 2268, -236, -1276, -278, 1392, -1767, - 1255, -1474, -8136, 1388, -770, 225, -443, 10, - -392, 659, -1118, -1651, -514, -935, -111, 1112, - 973, -247, -235, -13010, -737, 40, -141, 5167, - -910, 279, -467, -3762, 847, -3935, 1018, 1922, - 830, 190, 253, -1130, -415, 371, 718, 3833, - 1036, -5358, -928, 866, -514, 2724, 2354, 449, - 210, 1462, 680, -1880, -62, 10988, 809, -602, - 145, -536, 114, -147, -568, 3193, -322, 892, - -637, -1381, -65, 761, 1615, 5025, -327, 4941, - -631, -5225, 1204, 3042, 998, -1047, -959, -106, - 1610, -151, 120, -1152, 191, 30, 11963, 101, - 18, -410, -1288, 370, -771, 1337, -544, -613, - 289, -117, 1625, -4506, 2582, -1690, -105, -5324, - -93, 285, -1167, -3564, -729, -4790, 595, 275, - -216, -217, -6000, 682, -171, -875, 224, -164, - 2919, 796, -81, 1434, 186, -375, -4113, -179, - 277, 1363, -453, 2505, 388, -1840, -165, -4800, - -42, -6632, 54, -735, -553, -1679, 917, -2, - -632, 417, -478, -494, -265, 73, -372, -360, - 179, -448, 265, 299, -152, -211, 12730, -77, - 1954, -534, 773, 524, 438, 1901, -4413, -358, - 1552, -248, -1588, -122, -127, 5405, 226, -849, - -7495, -357, -89, 185, 746, 851, 669, 305, - -247, 3457, -193, -161, 638, 600, 610, 855, - -1292, 398, 1528, 2250, 1651, -8414, 763, 1529, - -346, 3769, -111, -6494, 347, -742, 1941, 1967, - 582, -5499, -765, -818, 1850, -1604, -243, -943, - -11, 884, -2996, -2375, 1010, -374, 6605, -287, - -5073, 211, -758, 703, -2607, 747, -130, -429, - -2481, 4894, -457, 3225, 958, 8533, 542, 6177, - -1069, -1210, -963, -5943, -86, 1424, -567, 827, - -510, -6577, -258, -4, -4430, 115, 5401, 1390, - 354, 1755, -998, 852, 993, -481, 218, -987, - 779, -417, 591, 6011, 528, 289, -336, -558, - 60, 9124, -174, 235, -239, -144, -260, -3472, - 746, 4781, 652, -4831, -739, -21, 864, -2310, - 652, 7147, 116, -318, -50, -3485, -325, -345, - -5784, 1144, 2399, -1443, 991, -2318, -785, -281, - -207, -1448, 309, 1001, 952, 1472, -5901, -780, - -2459, 1518, 9878, -1229, 670, -523, 1217, -164, - -55, -95, 243, 7909, 86, -4380, -859, -599, - -183, -2339, 774, -1210, -502, -899, 53, 1039, - 34, -7753, -296, -1951, -4559, 1182, -150, 2878, - -4910, 2761, -1481, 2048, 2600, 1808, -2953, -2257, - 62, 162, 1115, 214, -4510, 926, -6669, 1443, - -124, 193, -314, 302, 699, -18, 745, 341, - 895, -615, -295, -181, 143, -427, 6528, 1074, - -1126, 374, -298, -1274, 22, 887, -511, -1057, - 3228, 722, 607, 624, -95, 11085, 1006, -788, - -285, -92, 1342, -325, -828, 42, -3588, -631, - -576, 4559, -668, -1294, 1739, 1697, -647, 2336, - 376, -120, 1350, 646, -325, 95, 5974, 775, - 199, -8557, 931, -336, -651, -561, -433, -2266, - -129, -657, -1184, 67, 577, 617, 1880, 552, - 90, -617, -273, -1571, -7481, 261, -26, -20, - -459, -1028, 57, -8516, -43, 2774, 1, -4238, - 680, -3310, -56, -152, 548, -1983, 920, 899, - 2180, -307, -2230, -1685, -998, 2091, -112, 21, - -1551, 1182, 6649, -326, 792, 1818, -7596, 563, - 1076, 7422, -908, 1524, -223, 5798, 1318, -3376, - 517, 4162, 756, -4142, 1776, 390, 334, -44, - 218, 5290, 792, 39, 1692, 542, -62, -595, - 590, 27, 8922, 989, 182, 725, 112, 458, - -9170, -1000, 1176, -1290, -1403, -726, 5990, -297, - 1234, -1724, -601, 528, 1072, 184, -146, 61, - 685, 1208, -88, -211, 356, 9569, -363, -135, - -159, -1061, -105, -410, -58, 335, -9986, -300, - -211, 607, 443, -410, -1730, -328, 275, 579, - 805, 899, -464, -18, 296, -446, 2396, -13, - 414, -9662, -385, -808, -1867, 154, -572, 3351, - -1839, -80, 1157, -326, 481, 8815, -1039, 1065, - 2110, 1223, -960, -33, -464, -5660, 490, -314, - 346, 730, -387, -1102, 6656, -719, -1173, -57, - -1186, 2394, -1300, -665, -586, -39, -71, 155, - 1184, 4, -3269, -333, -747, 580, 279, -583, - 7164, -185, 110, 2465, 428, 507, 4462, -4461, - 199, 337, -3597, -249, -70, -680, -5549, 1533, - 917, -303, -9230, -431, -124, -1019, 369, 139, - 1367, 151, -1047, 6820, -151, 222, -2934, -817, - 971, -7325, 556, 1035, -1240, 3115, -1326, 4012, - 2812, 1057, 2580, -261, 3989, 1999, 1624, 2402, - -310, 779, -354, -377, -149, 1035, -2363, 358, - 3666, -246, -1896, 375, 3919, -1392, 683, 624, - -5872, 644, 391, 288, -198, -237, 68, -284, - 88, -1016, 250, 32, 1188, -243, -608, -320, - -219, -11087, 543, 156, 1034, -169, -183, -549, - -66, 716, 996, -928, -309, 5577, 229, 125, - -1328, 9027, -698, -485, -1694, 839, 343, 449, - 1655, 1005, 1053, -408, 9106, 186, 670, 774, - 314, 573, 3888, -882, 26, 2518, -533, -195, - 555, 337, -246, -10779, -231, 31, -314, -941, - 1129, 333, -7503, 168, -551, 237, -159, 4399, - 421, 693, 198, -196, -561, 1035, -548, 1058, - 527, 3617, -361, 1317, -1975, -2638, -1966, -120, - -324, 5678, -2252, -663, 181, -273, -3073, -282, - -622, 363, 71, 184, -776, 284, -1516, -430, - 3, 937, 8587, 258, -1060, -1555, -830, -338, - 318, -9130, -110, 459, -572, 70, 93, 120, - -534, 1296, -168, 29, -914, -332, -997, -818, - 270, -243, 523, 56, -11847, -448, 11, -154, - 164, 2115, -13, -635, 708, -663, 43, -248, - -3244, 254, 19, -1125, 508, 154, 8697, 191, - 595, 4393, -2806, -168, -1916, 393, 3976, 897, - -1716, -35, -180, 605, -1057, -1194, 100, -384, - -37, -107, 2739, -207, 6899, 176, 81, -901, - 1280, -1670, -101, 281, 1147, 48, 21, -151, - -1236, 210, 98, -114, -573, 7940, -153, -302, - -1331, 337, -322, 6598, 477, 147, -999, -3166, - -232, -5104, -799, -1866, -58, -4213, 1376, 181, - 675, 562, 126, 235, 2260, -5152, -243, -699, - -1476, 4135, 569, 567, 737, -4163, 613, -1057, - 1778, 546, -450, -24, 325, 366, 2406, -1319, - 60, -5126, 49, 657, -5937, -194, 882, 3267, - 178, -298, 1873, 12422, 459, 272, 195, -1827, - 212, -802, 730, 471, 1556, 422, 640, 236, - 71, 597, 5783, 5378, -649, 1524, 829, 437, - -351, -122, -1400, 2119, -128, 75, -1677, -633, - -322, -6382, -573, -974, 1672, -378, -242, 3708, - 79, -1325, 397, -150, 1977, 442, 747, -127, -}; - -static const int16_t shape16s[] = { - -392, 96, -7720, 99, 524, -8272, -20, 164, - -434, -85, -428, 1362, 108, 223, 1053, -11, - -193, -5140, -191, -159, 193, 8005, -39, -483, - 1764, -1061, -268, -318, -880, 474, 49, -8, - -223, 130, 11263, 165, 12, -43, -103, -1145, - -588, -81, 299, 73, 444, -7243, -1411, -640, - -946, 16, -881, 496, 2403, -476, 1090, -294, - 29, -148, 109, 145, -52, 247, -545, 1115, - -7451, -491, -1459, 397, -8603, -1022, 1494, 298, - -5156, -358, -1097, -2911, 423, 652, -378, -2357, - -74, 415, -367, 402, 2173, -154, 122, 283, - 1352, 302, -373, -431, -283, -109, -64, -343, - -108, 55, -14644, 241, 37, -723, -71, -208, - -126, 4061, -9887, 494, 2273, -505, -4040, 66, - -806, -1121, -1894, 783, -1445, 426, -820, -1739, - -11, 650, -282, -518, 124, -7266, -21, 160, - -339, 5, -208, 11712, 198, -53, 921, 89, - 5987, -4806, 176, 1884, 64, -517, 2169, 108, - 297, -111, -389, -840, 663, 75, -485, -4862, - -177, 2663, -229, 8120, -219, 462, 3104, 955, - 384, 1310, -73, -504, 258, 170, -1796, -482, - 5691, -437, -8474, 583, -1685, -827, 292, -65, - 1994, -384, 105, 123, 256, -82, -367, 15204, - -128, -260, -10, 169, 249, -1286, 1055, 136, - 678, 61, 1420, -159, -15, -221, -250, 107, - -21, 297, 54, 242, -111, 468, 237, -36, - -159, 37, -102, -488, -4577, 72, 1009, -1, - 1218, 2023, -640, -437, 766, -299, 6144, 184, - -1023, 171, -388, 884, -1294, -320, 8718, 896, - -295, -976, -803, 3092, 1720, -255, -1354, -665, - -63, 4382, 41, -121, -157, 354, 127, 587, - -599, -231, 484, -150, -284, -498, -511, 79, - 5503, 13, 6537, 761, -1619, 1164, -2403, 3057, - -4966, 724, 1076, -1555, 889, -365, 60, -440, - -7144, -132, 283, -305, -126, -1482, 125, -52, - -33, 1284, -961, 1355, 953, -1012, -227, 86, - 731, -14, -15977, -56, -875, -1676, 127, 500, - 3390, -14, -319, -644, 143, 249, -10752, 23, - 54, -1075, -111, 680, -1714, 328, -2092, -852, - 622, 949, 61, 6, -17, 144, 190, 216, - 130, -65, 27, -322, -139, 43, 89, 76, - -84, -10120, -47, 367, -261, 38, 50, 4233, - -210, 14, -1, 25, 762, -299, -132, 177, - 974, -492, -145, -43, 5105, -394, -196, -91, - -25, 473, -8358, -476, 589, -1372, -254, -2387, - -293, -304, 3828, -254, -193, 493, 54, -108, - -8789, -262, -233, -821, -222, 714, 1270, -61, - 892, 13, 3952, -36, -1567, -620, -126, -1056, - 587, 390, -24, 2027, 267, 218, 15, -56, - -130, 40, 551, -29, 14594, -23, 106, -14, - -172, 279, 427, -241, 303, -20, -748, 55, - 5187, 598, -217, 2026, 643, 118, 911, 8023, - 296, 791, 39, -2621, 655, 228, -671, -272, - -176, 6644, -166, -264, -10429, 91, -83, -684, - -169, -344, 2123, -102, -333, -317, -826, 586, - 116, -9311, 445, 141, -1315, -758, 144, 5620, - 363, 66, 142, -161, -684, 454, -6584, -205, - 577, 205, 305, -1536, -4109, -318, 121, -323, - -1036, 8020, 1146, -4004, 175, -1568, -1537, -525, - 2284, 62, 11, 640, 1243, 260, -104, -344, - 102, -624, 122, -300, 266, -6104, -1149, 412, - -1380, 22, 7561, 360, 564, 398, -338, 174, - -76, 131, 44, -426, -12, -175, -113, 78, - 293, -120, -92, 331, -16163, -74, -101, -1198, - -298, -171, 4052, -139, -187, 131, 323, 370, - -144, -160, 131, -284, -190, 83, 878, -14817, - 14, 196, 198, 294, -120, 40, 800, 1841, - 393, -168, 337, -540, -356, 130, 9210, 880, - 304, -2304, -275, 1394, 9903, 673, -62, -4706, - -130, 274, 528, 89, -458, -90, 6318, -133, - 310, -5953, 682, 37, 2937, -371, 197, 77, - -184, 1240, 22, -7695, -171, -4874, -676, -1121, - -842, -642, 1160, -1088, -864, 352, -790, 794, - 801, 10564, -1777, 1095, -441, 1718, 116, 982, - -268, 199, -2408, -2042, 279, -146, 645, -1350, - 5, -150, -932, 113, 25, -672, 153, 158, - -6140, -262, 142, 4815, -1, -424, 810, 63, - 88, -510, -236, 3964, -66, 1229, -16, -758, - -11023, -1149, 48, -1756, 167, 2308, -96, -654, - -639, 369, -221, 47, 202, 329, -352, -26, - -19, 13198, -383, 124, -1211, 3879, -344, -1954, - -8702, 32, 924, 472, 7953, 692, -216, -415, - -3174, -1959, 935, 4048, 155, 7521, 854, -157, - 643, 3760, -107, -2536, 622, -742, 1881, 2262, - 758, -968, -271, -131, 385, -5107, -212, -2548, - 29, -132, -506, -190, -1065, 314, 202, 332, - -2274, 701, 4, -22, -439, 198, -265, -92, - -143, 460, -32, 189, 334, 87, -7639, 45, - -387, 4240, 1231, 92, 1032, -333, -280, 2061, - 296, 365, 2003, -426, -35, 96, -62, 882, - -784, 483, -128, -143, 474, 13740, -166, 184, - -714, 142, 278, 5622, -67, 282, 647, -130, - -31, 300, 727, 728, 409, 178, -601, 84, - 8305, -446, 179, 115, 209, -273, -47, 1932, - -255, -3171, -102, 461, -119, -8102, -809, 108, - -1680, -3171, -775, 324, -246, 132, -27, 84, - 8495, -45, 153, 21, -1384, 290, -869, 38, - -440, 133, -257, -22, -3046, 12, -2797, 4517, - 142, 1605, 423, 579, -558, -301, -257, 701, - -246, -468, -1946, 120, 321, 710, -217, -203, - -50, -44, -5866, 80, 259, 488, 754, 124, - -517, 703, -197, 146, 576, -717, 247, 4121, - 10, -422, -2686, 329, 1183, 14573, 72, 301, - 2043, -125, -1420, -1263, 10340, -678, -1226, 330, - -62, 173, 5885, -56, -178, -1090, -616, 953, - -216, 8277, -124, 411, 7758, -78, -326, 786, - 46, -1365, -555, 479, -774, -576, 8, 304, - 390, -186, -820, 72, -67, -585, 11070, -213, - -12, 344, -399, -748, -150, 2719, 195, 5652, - 4626, 549, 2782, -4, 1928, 482, 1008, -6398, - 843, 457, 1843, 269, 1247, 350, -661, -35, - -6477, 3727, 2313, -424, -907, 415, 1075, 3960, - -1499, 61, 594, -744, 110, 2486, 967, 27, - -5263, -618, -578, 313, 7055, -1081, 739, -492, - -2051, 317, 112, -155, -304, -507, 150, 253, - -42, 221, 92, -275, -355, -8494, -663, 109, - 282, -836, -271, 9316, 165, 63, -171, 10, - -38, -180, -219, -250, -924, -573, -241, 566, - -175, 20, 454, 251, -328, 236, -215, -5673, - 0, -265, 225, 354, 113, -488, 174, -132, - 134, -188, 1255, -94, -55, -193, 404, 504, - 784, -377, -5731, 333, -447, 222, 138, 72, - -256, -58, -230, -169, 728, -481, 95, -394, - -74, -489, -253, -13770, 61, 184, -36, 5025, - -232, 321, 253, -3414, 120, -2512, 799, -586, - 1186, -1135, -955, -54, 7, 83, 0, 5259, - 466, -6358, 254, 388, -211, 207, 2449, 379, - 430, -219, -442, 228, 151, 11819, 67, -101, - 239, -282, 121, -270, 1209, -386, 553, -108, - 789, -518, 237, -48, 497, 8986, 80, 8232, - -89, -359, -803, 473, 995, 1132, 624, 1353, - -305, 711, -71, -26, 18, 254, 13079, -72, - 178, -18, -116, 293, 155, -254, -819, -166, - -808, -190, 150, -4328, -33, -14, 272, -6417, - 78, 78, 67, 310, -177, -435, 225, 610, - -15, 1, -6706, 30, 1, -189, 270, -21, - 276, -182, 77, -231, 30, -116, -7713, 158, - 344, 560, 1466, 3575, -84, -4583, -1260, 372, - 1395, -5223, 284, -1911, 315, -2312, -47, -207, - 414, 129, 36, 85, 317, -125, -63, -212, - -76, 130, -385, 157, 117, 12, 16140, -171, - 375, -721, 161, -342, 950, -667, 1011, 15, - 536, -1203, 1039, -242, -159, 7664, -429, -264, - -8221, -109, 867, -74, -79, -414, 544, 206, - 120, 1859, -44, 73, 554, 121, -160, -127, - -33, 44, -24, 285, 589, -12514, 51, 464, - 17, 264, 58, -6861, 367, -672, 227, 2793, - 782, -6286, -420, -808, -1247, 895, 950, 1533, - -1079, -207, -1927, -4947, -803, -328, 7677, -386, - -4608, -329, -485, 2365, -1492, -1738, -378, -707, - -1850, 9044, 314, 3530, 61, 2921, 79, 9508, - -1102, -3487, 814, -2828, 550, -929, -712, -274, - -566, -2521, 536, -296, -97, 951, 11352, -614, - 106, -342, -1017, -1183, -157, -457, 266, 109, - 545, -313, 1015, 6961, 52, -224, 2247, -248, - -180, 12367, 311, 514, 1218, -561, -2546, -3275, - 218, 8281, 187, -6550, -96, -1001, 1777, 89, - 916, 1042, 399, -267, -97, -3552, 397, 1984, - -6134, 784, 2136, -1346, 619, -1450, -1022, -1226, - 185, 306, -274, -122, 343, 129, -4481, -749, - -759, -496, 8785, -178, 457, -601, 875, 1040, - -268, -1592, -531, 9667, 360, -4978, 525, -436, - 123, -1566, 227, 820, 74, -5, 1477, 154, - -1589, -9411, 248, -485, -3293, -690, 175, 53, - -21, 303, -2376, 106, 515, 2688, -401, -1278, - 425, 540, -353, 662, -7461, -397, -7029, -976, - 445, -1648, 164, -254, -563, 556, 876, -205, - 884, 214, -92, -509, 96, -53, 5734, -295, - -136, 211, 168, 261, -74, 411, 25, -59, - 3596, 400, 320, -69, -21, 14062, -510, 142, - -232, 1597, 34, 240, -476, 131, -3836, -186, - 2579, 2812, -1501, 274, 2685, 2809, -1100, 2696, - -402, 67, 650, -1804, -11, -216, 6751, 112, - 455, -7210, -251, -1075, -833, -966, 1443, -138, - 273, -494, 1557, -15, -339, -82, 402, 206, - 31, -77, -94, 78, -5468, -179, -44, 421, - 163, -386, -133, -6334, 427, 747, -121, -292, - 368, -1087, -338, -1534, 3740, -881, -2012, -1284, - 902, 97, -3407, -567, -118, 1340, -77, -445, - 642, 184, 901, -341, -81, 595, -6531, -248, - -167, 8740, 373, 408, 23, 10709, -299, -876, - -584, -1067, 20, -4556, 295, -1956, 990, -132, - -152, 4068, -92, 142, -1512, 23, -815, 454, - 330, -331, 9042, 120, -100, 34, 96, 152, - -11083, 345, -567, -498, 198, -37, 9276, -479, - 611, -2788, 253, -176, 617, -224, 248, 390, - 39, 25, -110, 127, -13, 6675, -84, 115, - 294, 84, -366, -405, -32, -109, -10469, 99, - 17, -88, -226, 316, -133, -203, -60, 311, - -87, -331, 357, -11, 158, 74, 562, 8, - 354, -10843, -114, -206, 699, -617, -141, 807, - 87, -149, 174, 199, -55, 10880, -332, 182, - 544, 651, -27, 261, -190, -655, 24, -443, - -630, 204, 207, -4174, 3557, 89, -386, 1754, - -485, -127, -97, 40, -1336, -488, -177, -750, - 88, -1040, -2215, -507, 169, 2908, 69, -52, - 8458, 601, 174, 1635, 480, 181, 3004, -3021, - 1868, -364, -2100, -256, -3065, -33, -7467, -890, - -1949, -20, -9472, -230, -847, -634, -377, -40, - 1184, 242, 265, 7056, 42, 16, -5070, -71, - 300, -1186, 187, 337, -1331, 77, -473, 3213, - 5738, 626, 2524, 531, 1001, -803, 1231, -1083, - -564, 539, 191, -498, 184, 603, -1777, -479, - 2298, -604, -2077, 634, 4682, -1387, -875, 498, - -10011, -173, 752, 109, -70, 171, -64, -261, - -79, 37, -233, 128, -66, -70, 356, -310, - 214, -14792, 6, 200, -227, 59, -241, 560, - -230, 479, 403, -22, 148, 7428, 110, -177, - 110, 7518, -2372, -1277, 223, -708, 731, 695, - -702, -2906, 256, -1160, 4941, 121, -1148, -68, - -424, -1590, 4697, 705, 525, 684, -451, -246, - -115, 556, 543, -6658, 384, -589, -1505, 12, - 114, 82, -5084, 164, 154, -295, 106, -271, - -40, -394, -437, 397, -279, -3825, -286, 632, - -1041, 1137, -93, 48, 192, -5914, -92, -235, - 682, 5817, -702, 180, -243, -219, -910, -174, - -146, 142, 12, -69, -207, -269, -53, 567, - -336, 114, 9601, -272, -270, 459, 610, -258, - 97, -10950, 397, 57, -7, 229, 1669, -173, - -173, -92, -347, -133, -357, 92, 132, -609, - 60, -124, 116, -54, -15205, 142, 109, 1127, - 268, -220, 336, -743, -238, -29, -902, 91, - -3597, -288, 1114, -3797, -1615, 32, 11481, 55, - 194, 3567, -1857, -2561, -237, -15, -48, -232, - -58, -21, 37, -535, -450, 857, 2001, 12, - 48, 840, 211, 126, 4833, 275, 176, -111, - 9, -112, -403, 182, 296, 181, -425, -14, - 276, 118, -240, 384, 139, 9183, -230, 143, - 2412, -70, 250, 10191, 809, -15, -257, -1242, - -163, -4253, -352, -436, 264, -4998, -17, -215, - 1412, 1592, 856, -159, 4756, -5032, 307, -251, - 194, 6414, -56, -7, -503, -261, -646, -1050, - -271, -578, -291, 614, 130, -336, -923, -120, - 149, -6012, 273, -295, -4586, 137, 206, 1246, - 498, 614, 991, 13776, 122, 52, -660, -76, - -211, -477, -224, 196, 411, 398, -590, 820, - -441, -35, 4394, 5010, -902, 509, 45, 747, - 1035, -455, -579, 105, 1103, -496, -1249, -248, - 46, -5771, -198, -386, 736, 15, -335, -85, - -624, -124, 580, -327, -102, -18, 866, 381, -}; - -static const int16_t shape22[] = { - 2560, -127, -137, -385, -1875, 90, -240, 140, - 1290, 200, -6762, 374, 1871, 8730, -111, -555, - -1524, -2175, -4689, 521, -179, 166, -1573, 1056, - -346, 247, -92, 5713, 561, 233, -360, 480, - -741, -7552, -1508, 259, -8746, 1604, 1385, 723, - 5678, 2243, 403, 12370, 3526, 574, 4982, 563, - 1713, -1337, 1336, -60, -890, -2184, -563, 9347, - 775, 6318, -883, 1476, -335, 736, -564, 635, - -5557, 617, 54, 257, -325, -66, -5689, 1061, - -897, 90, 8394, 2004, 9456, -222, -2026, -969, - 93, -5, -922, -6491, 1496, -1537, 651, -277, - -1038, 6072, -8534, -2526, 1645, 1459, 547, 2347, - -85, -761, -7210, -153, 414, 6096, 383, 320, - 370, -902, 823, 3071, 499, -731, 38, 473, - 1693, -9456, 946, 1218, -1054, 70, 367, -469, - -7861, -913, 401, 198, -83, 877, -308, 8633, - 253, -2025, 1925, 1412, 1351, -360, -948, -7526, - 1089, -7449, 1652, 141, -43, -2082, 44, 130, - -7525, -15049, -1345, 180, -3009, -4581, -267, 2309, - -1397, -112, -63, 307, -746, -13, 35, -8800, - -1947, -1143, -1096, -2582, -1210, 7683, -743, -1589, - 5699, -80, -1375, -93, -483, 129, 6076, -6099, - 374, -176, -1150, -416, 137, -4309, -1926, 3099, - 82, -836, 392, -655, 108, 428, 3361, 313, - 363, 7534, 1153, 334, 2262, -367, -69, -813, - -9702, 3074, -5461, 0, -1889, 1303, -8306, -113, - -677, 692, -2752, 1292, -171, 430, 4609, -2238, - 196, 1661, -25, -164, -2590, -4919, -615, -7, - -753, 5104, 5197, -66, -310, 827, -126, 615, - 70, -456, 238, 682, -639, -561, 369, 183, - 113, 430, -840, -792, -7282, -7537, 619, -445, - 588, 19, -1061, 652, 46, 861, 9641, -1251, - -41, -699, -605, -1389, 240, -10798, 733, 194, - -1230, -1092, -520, -219, 7, 518, -181, -12062, - 651, -40, 1128, -390, -220, -438, 471, 510, - 632, -321, 1393, 8827, -3241, -6683, 350, 1953, - -246, -582, -5486, -7576, -157, 888, 2965, -23, - 762, 6867, 3697, -43, -7905, -938, 2119, 377, - -25, 691, 136, -725, 7643, -730, 2024, -6932, - 804, 53, 392, 440, 336, 6235, -7037, -5584, - -1579, 1115, 1757, 1001, 32, -294, -592, 300, - -764, -8879, -1612, -845, 1722, 6968, 384, 267, - 862, 10830, -364, -1138, -49, 1041, -908, -14960, - 809, 628, -1150, -1348, -437, 805, 877, -64, - 1041, 5253, -270, 2022, 1253, -992, 11015, 2686, - 17, 80, -1463, 4229, 80, -834, -9286, 1179, - 66, -39, -64, -4057, -423, 116, -1441, -1733, - 752, 1674, 1443, 757, -3149, 9057, -3522, 4007, - -893, 1179, -388, 6368, -478, 4397, 13868, -2996, - 790, 704, -2299, -6003, 449, -5410, 1999, 181, - -1807, -362, -57, 454, -2371, 3658, -485, -212, - 11551, 1535, 478, -1570, -278, 584, 608, -5211, - 6965, 1042, -168, -337, -1071, 72, 451, -204, - -1000, -1044, 689, 186, -166, -375, 9426, 363, - 93, -717, 304, 107, 7853, -1251, 1093, 692, - -742, 33, 576, 447, 678, 452, 408, -4813, - 711, -595, -516, -1108, 1941, 3056, -219, -3413, - 10946, 1513, -2375, 48, -408, 49, -399, -5608, - -58, 161, 4808, 436, 68, -5675, 230, 832, - -1228, 6382, -588, -1312, 772, 4337, -405, -5467, - -222, 1382, 2158, 620, -840, 810, -3830, 48, - -101, 529, -2670, -249, 1035, -7620, -1081, -6646, - 1469, 1043, 743, 1553, -556, -274, 68, 238, - 1078, -110, -5163, 562, 735, -8317, 1202, -1325, - -962, 61, 4280, 570, 7450, 265, -1516, 696, - -1567, -681, 0, -4064, 1548, -2521, 657, 567, - -8343, 1691, -1430, 4827, 807, 905, -2601, -7415, - 921, -1741, 363, 309, 211, -521, 3013, -797, - 648, -3709, 961, 662, 403, -386, -719, -5752, - 1355, 6717, 191, 591, -371, -1225, -5125, 800, - -252, -5769, 1101, 657, -141, 2377, -1365, -218, - -114, 148, 276, 358, -354, 18, -31, -9413, - -5514, -1458, -220, 298, 666, 659, 359, 980, - -1389, 101, 1500, 4661, 472, 264, -7590, -1469, - 41, 38, -259, -346, -486, -9949, 812, 422, - -1354, -2461, -2057, -253, 1806, -107, -41, 16384, - -140, -684, 5421, 1907, -10, -889, -1877, -6815, - -818, -5854, -3196, -895, -1706, -186, 7944, 100, - -11260, -4573, -415, 4685, 395, -6035, 5789, -4566, - 624, -2146, 570, 130, -892, 1385, -262, 6638, - -2324, 348, -288, 607, -1574, 7119, -1037, -40, - -4955, -946, -5215, -1013, -1232, -875, -78, -399, - 231, -173, -5860, 189, -755, -8265, 745, 966, - 202, -1858, -26, -658, 55, 1131, -56, 3030, - 158, 3742, -1261, 317, 6397, 521, -508, -522, - -2040, -747, -6906, -868, -110, -719, 2602, 2570, - -1106, -787, -352, 9212, -545, 7339, -10183, -726, - 1104, -1118, -1655, 383, 1370, 1412, 528, -4689, - -398, -3802, -682, -11004, -2310, 8011, 2301, -5941, - -512, 3813, 210, 1379, -15209, 1143, -2344, 2459, - 2368, -6484, -2078, -246, 383, -204, 1449, -453, - -1539, 416, 508, -7168, -1930, 4279, 453, -215, - -296, -346, 5691, -200, -855, 552, 5921, -109, - 588, -3049, 1312, 6767, -78, -7204, 1187, -754, - -1043, -455, 412, -490, 3124, -273, 1468, -546, - 552, -306, 835, -263, -7234, 324, 318, -1224, - 240, 198, 193, -550, -684, -12416, 85, -1469, - -463, -301, 180, 290, -928, -6399, -931, 176, - 310, -692, 7964, -204, 512, 975, -6415, -394, - -30, -120, 1638, -1474, -381, 5912, 156, -830, - -575, -225, -4079, -787, -957, -801, 181, 575, - 1116, -795, -743, -981, 434, -365, -9780, -1814, - 1447, 1081, 153, 884, 8697, 259, 881, -661, - -1232, -547, 464, 898, -3988, -476, 790, 7589, - -525, -809, -2900, -1271, 170, 223, -5050, -2554, - 1458, -666, 537, -6733, 212, 448, -1556, 1459, - 802, -2716, -8785, 11020, -258, 1229, 1138, 843, - 508, 103, -657, 1273, 8140, 368, -605, 6856, - 110, -423, 5458, -417, 993, 257, 5552, -47, - 1401, -119, -1320, 6193, -1196, 56, -93, -1604, - -1491, -897, 238, 823, 4213, 104, 145, -1049, - -9286, -26, -813, -139, 499, -10351, -466, -515, - -1166, -412, -746, 503, 1872, 17, -11941, -3350, - -108, -7296, -411, 4811, -1870, 162, 5595, -658, - 339, -904, 6911, -715, -240, -71, 377, 4747, - -57, -8920, 521, 753, -375, -1185, 1322, -328, - 5, 525, -610, 127, 1519, 791, 784, -16384, - 116, -1007, -352, 486, -7871, 202, -3684, -387, - 676, -8942, -713, -447, -557, 1159, 974, -380, - -1183, 1049, -9, 838, -932, -139, 371, 1688, - -7617, 1192, 2350, -220, -4558, 2681, 1568, 102, - 1274, -446, -351, 1551, 1101, -8995, -5276, -4416, - 3411, 221, -429, 412, 1625, -4575, 254, -631, - 310, -378, 9743, 859, 934, 142, -1400, -6921, - 6466, -4068, 2664, 418, 70, 284, -903, -23, - -502, 4354, -5993, 125, -34, -1246, -1946, -204, - 1002, -7454, -88, -8628, 2449, 13715, 318, -8759, - 294, -2212, 138, -761, 285, -1686, 291, 606, - 180, 761, -359, -1467, 299, -417, -361, -895, - -5692, 127, -951, 165, 1, 396, -819, -5508, - 280, 760, -411, -1025, -649, -1688, -6290, 272, - -17, -7595, 9, 307, 128, -3995, -119, 481, - -3100, -255, 651, 139, -3492, -6, -4471, 452, - -71, 139, 1255, -6128, 1191, 326, 28, -238, - 1374, -334, -457, -836, -10390, 185, -616, 3366, - -39, 183, -21, 6240, 1141, 341, -348, 738, - 121, -65, -386, -27, -548, 337, -4, -126, - 571, 2263, 4936, -1093, -397, 961, -5886, -734, - 1509, -660, -61, 170, -783, -4197, -1459, 906, - -31, 400, -481, 561, 6, 489, -5397, -1666, - 41, -536, -116, 6713, 1288, -157, -116, 4256, - 1895, 6671, 1837, -544, 1276, 2031, 345, 6471, - -84, 1868, -2006, -1304, -7792, 702, -1189, 105, - -4869, -282, -790, 7083, -628, -1273, 252, -179, -}; - -static const int16_t shape22s[] = { - 493, -2, -310, -109, -1218, -193, -267, -11, - -466, -34, -2492, 287, 241, 3621, -537, 458, - 869, -915, -290, 782, 65, -90, -635, 1836, - 80, 519, 868, 1359, 550, -92, -704, 110, - -210, -4337, -376, -200, -2693, 6, 381, 688, - 556, 883, -88, 1698, 1081, 133, 1130, -78, - 853, -424, -39, -909, -1579, -2774, -372, 3604, - -519, 3777, -66, 1330, -1055, 1135, -995, 220, - -3124, 122, 83, 1045, -701, -120, -6800, -269, - 195, 1197, 5500, -490, 5453, -201, 411, 823, - -146, 46, 252, -2724, 606, -924, -1538, 394, - -420, 6405, -5632, -941, -402, -137, 984, -24, - 594, -40, -140, -20, 204, 1211, 290, -680, - 103, -434, -294, 1646, -159, -2296, -237, 507, - -67, -8999, -97, 403, -1473, -111, 22, -257, - -2203, -600, 577, -117, 48, 2216, -170, 1192, - 700, -477, 1678, 979, 2395, -69, -1746, -2139, - -294, -4210, 181, -372, 320, -180, -503, -550, - -3994, -6315, 502, -804, -432, -112, -457, -1016, - 637, 297, 932, 533, 798, 229, -1001, -2780, - -4009, 1176, 189, -1575, 21, 3512, -348, -1450, - 2488, 463, 611, -46, 85, 94, 3319, -3041, - -362, -261, -1534, -1900, 7, -519, -52, 1166, - -174, -152, -189, -415, 641, 27, 1764, 280, - -301, 2976, 146, -632, 4022, -1994, -84, -61, - -1633, 285, -439, 781, -592, 399, -4794, 203, - -295, 32, -1423, 216, -2773, -9, 3589, -3952, - -195, 161, -223, -2240, -1886, -2643, 978, 113, - -1019, 1645, 1493, -851, 1417, -74, 717, 411, - 887, -1384, 73, 117, -65, -7, 133, 18, - 69, 11, -98, 45, -1751, -2710, 11, -140, - 29, 185, 327, 705, 56, 152, 8202, -117, - 157, -478, 36, -564, 996, -9359, -707, 674, - 1169, 270, 156, -679, 15, 720, -38, -4952, - -196, 183, -356, -1004, 185, -148, -61, 151, - -229, -161, 23, 4350, -650, -4384, -21, 909, - 105, -271, -2538, -4018, -1268, 351, 396, -190, - -135, 970, 3159, -935, -6968, -131, -1031, 53, - -430, 242, -219, 384, 2832, -151, 152, -6891, - 1444, -63, -46, 72, 653, 3955, -4187, -321, - -298, 678, -471, 664, -42, -30, 825, 195, - -1147, -2728, -178, -2305, 680, 1980, -147, 320, - -348, 4307, 806, -263, -60, -102, 8, -10085, - 626, -130, 267, -621, 45, -157, 438, 190, - 78, 1608, -246, -386, 256, -255, 5651, -449, - -13, 198, -3193, 329, -500, -1368, -6647, 609, - -507, -96, 222, -1196, 171, -12, -299, -1423, - 442, 47, -5, -282, -18, 4969, -1764, 231, - -471, 5044, 412, 1496, -146, 35, 5083, -228, - 355, -482, -1063, 1265, 80, -1278, 1225, 826, - -1914, 779, 439, -511, -4177, 425, -38, -55, - 9786, 1005, -538, -664, -641, 638, 125, -2811, - 2308, 28, -1157, -229, -624, 45, 354, -368, - -1661, 90, 778, -328, 272, -223, 9558, 822, - -167, -12, -1020, 2962, 2372, -932, 1961, 1398, - 2660, 3, 235, 421, 114, -283, 371, -1652, - 329, -435, -113, -1296, -501, -686, 297, -384, - 10328, 472, 614, 139, -765, -309, 180, -2009, - -171, -175, 3571, 146, 46, -1356, -134, -15, - -166, 2046, 108, 119, -281, 971, -471, -1134, - 34, -104, 219, 746, -223, 245, -181, 12, - -165, 216, -792, 86, 562, -1807, -116, -1324, - 590, -320, -80, 1863, -420, -1066, -698, -2879, - -6, 182, -2325, 575, 97, -2616, 2938, -673, - -693, -116, 1905, -430, 4739, -12, -3307, 693, - -227, 223, -111, -1498, 5, 1751, -36, 234, - -4584, 838, -370, -296, -818, 337, -46, -8921, - 875, -423, 496, -1196, -24, -1014, 969, 294, - 237, -1733, 27, 2543, 1494, 190, 457, -1391, - 1209, 5651, 548, 504, 686, -2889, -151, 725, - 486, -3716, -285, 830, 31, 5132, 770, -24, - -482, -369, -126, -1552, -347, -272, -387, -9485, - -1547, -1189, 369, 812, 311, 536, 391, 361, - -1708, -288, -94, 2053, 557, -611, -4551, -2368, - 173, 472, 160, -1849, 96, -7569, 183, 484, - -393, -346, -309, -13, -7, 2, -239, 10395, - -587, -115, 1282, -634, 81, 90, -725, -2685, - -1214, -4455, -1897, -2903, -827, 124, 2215, 696, - -1225, -1353, -371, 343, 421, -640, 1480, -1174, - 76, -835, -716, -625, -547, 1250, -2696, 2132, - -548, 439, -607, 408, -221, 5026, 352, -344, - -1339, -602, -1650, -404, -458, -502, 61, -164, - 53, -26, -2652, -209, 64, -4068, 713, 193, - -117, -1290, 95, -86, -515, 1336, -492, 1654, - -2963, 3663, -4231, -1, 3017, 371, 276, -7, - -289, -33, -5942, 237, 30, 586, -264, -493, - 435, -388, -165, 10434, 192, 3897, -5414, 361, - 845, -259, 481, 331, 650, -232, 23, -1789, - 27, -4065, 1020, -4261, -651, 3174, 951, -3363, - 577, -112, 642, -1177, -1707, 492, -250, -1236, - 24, -1394, -1807, -853, 1681, -69, 851, -959, - -5759, -202, 30, -3466, -593, 5414, 65, 141, - -319, 674, 1183, -155, -312, 372, 2829, -75, - -60, -2618, -240, 2944, -631, -4221, -16, 467, - 211, -58, 55, -527, -51, -160, 642, -305, - 388, 413, 210, -81, -3383, -120, 144, -220, - -672, 1352, -630, -2324, -423, -8053, -131, -912, - -260, -380, 470, 154, -1346, -2417, -426, -403, - -137, -160, 2823, 609, -216, -173, -585, -514, - 95, -202, 222, 16, 136, 1751, 237, -1089, - 957, -144, -518, 416, -347, -60, 207, 277, - 512, -1133, 166, 1423, -883, -194, -7016, -1938, - 417, 2302, -992, -179, 738, -74, 411, -462, - -413, 67, 234, -322, -164, -47, -89, 1409, - 390, -1180, -2888, 655, 1958, 0, -1826, -471, - -1247, 307, 104, -8502, -198, -222, 191, 281, - -868, 47, -4553, 2434, 174, 263, 2844, -72, - -597, -1183, -374, -93, 3348, 13, 173, 6285, - -32, -213, 1882, 411, -608, -562, 2998, 293, - 54, -147, -120, 822, -93, 679, 206, -3229, - -767, -1603, -259, -310, 4306, 548, -9, -99, - -5722, -328, -176, 453, 338, -9687, -63, 844, - 322, 615, -1075, -370, 159, -33, -6213, -1375, - 741, -801, -1319, 1513, 1331, -69, 2702, -458, - -203, 103, 4696, -284, 465, -62, -40, 3184, - 238, -6131, 546, 1713, -365, -24, 116, -33, - 304, 807, -231, 291, 903, 749, -254, -12215, - 115, -35, -95, -166, -3776, -170, -4517, -151, - 67, -7725, 666, -573, -744, -719, 37, 31, - 373, 148, -125, 15, -150, -905, -42, 272, - -5223, 650, 5233, 109, -1235, 991, 211, 1522, - -555, -328, -52, 5335, -22, -5476, -3102, -637, - 986, 468, -37, -164, -264, -1290, 754, -940, - -685, -862, 7270, -279, -441, 472, -153, -2515, - 3899, -95, 360, 762, 14, 434, 619, 185, - -230, 1233, -1330, 1360, -756, 361, -1391, -247, - 120, -3573, 293, 375, 806, 5526, 536, 137, - 486, -484, 13, -37, 12, -4, 81, 43, - 10, 43, -38, -371, -64, -1167, -117, -371, - -1958, -166, 543, -97, -83, 391, -59, -1631, - 302, 1077, -128, -641, -64, 21, -2562, -235, - 342, -7121, -646, -49, -961, -141, -210, -555, - -1596, -988, 723, -209, -3585, 10, -35, 1051, - 0, 138, 941, -5002, 805, 3009, 35, -70, - 513, -21, -432, -224, -10628, -167, -1045, 2603, - 336, 360, 515, 683, 981, 3028, 492, -543, - -1844, 23, -30, 52, -40, 447, 11, 363, - -95, 1609, 2613, -13, -400, 719, -4513, -676, - -290, 456, -332, -11, -261, -455, 89, -301, - 285, 287, 202, 281, 87, -202, -1482, -535, - 874, -478, -201, 4715, 824, -204, 145, 2882, - 404, 3376, 363, -18, -127, 764, 106, 1626, - 178, 185, 22, -637, -6216, 1399, -961, -88, - -553, -91, 98, 1831, 9, -583, 1253, -1741, -}; - -static const int16_t shape44s[] = { - -20, -140, 683, -586, -1742, 177, -538, 1900, - 2193, -17, -2096, 261, 645, 339, 77, 1136, - -521, 537, -924, -156, -261, 195, 1049, -39, - 236, -137, 0, 3199, 225, 46, 86, -215, - 557, -5394, 17, 911, -1690, -48, -48, -175, - -11, -631, -153, 4474, -347, -39, 1759, 154, - 170, -180, -273, 603, -590, -5195, -74, 1789, - 240, -212, 431, 2447, 368, -76, -313, 11, - -2926, 19, -71, 208, -51, -728, -6412, -61, - 141, -112, 5280, -76, 4435, -402, -25, 46, - 210, -104, 172, -3830, -366, -23, 239, -112, - 137, 6692, -6288, -720, -132, -136, 552, -1688, - -345, -289, -485, 149, 174, 180, 361, -236, - 92, 407, 6, 2373, 380, -167, 845, 444, - -834, -9358, 413, -1302, 460, 77, 34, 56, - -1516, -143, 207, -43, -31, -106, -52, 403, - -309, 298, -88, 1552, -240, -776, 624, -4181, - -342, -4804, 57, -23, 160, -44, 469, -17, - -3997, -5079, -263, 72, 181, 1085, 538, -611, - -368, 59, -204, -195, -40, -201, -803, -5093, - -3216, 480, 46, -729, 244, 3320, 185, 503, - 2979, -416, 110, 25, 140, -502, 2236, -4420, - -36, -238, -278, 60, -82, -597, 218, 69, - -95, -2102, -2138, -2308, -3796, 20, -211, -229, - 297, 3665, 81, 148, 1315, -4537, -38, 186, - -3106, -526, 90, -35, -193, -302, -5860, 276, - -308, 206, 645, 1, -242, 580, 3025, -2583, - -90, 511, -315, -137, -2033, -4313, 693, 485, - -211, 1486, 1180, 181, -136, 204, 23, 383, - 1479, -213, 42, 32, -64, -136, -91, -146, - 434, 231, 36, -58, -3254, -2647, -18, 345, - 171, -60, 84, 209, 246, -587, 9447, -67, - -187, -108, -226, -458, -519, -11089, -422, -502, - 132, 79, 298, -475, -412, 196, -164, -7347, - 185, -131, 369, 18, -500, 644, -334, 93, - -77, 71, 341, 3566, -281, -4191, -145, 87, - 37, 306, -3482, -5739, 161, -245, 293, 208, - 380, 2888, 31, -23, -2061, -597, -56, 350, - -105, 1167, 64, 342, 3638, -79, -106, 148, - 5422, -719, -232, 8, -395, 3249, -5093, -222, - -707, 241, 318, 735, 376, 78, -166, -1614, - -9, -3373, 330, -1540, 2028, 3400, -9, 317, - 9, 4903, 262, 62, 222, -95, -208, -13376, - -101, 121, 298, 5, 172, 406, -164, 79, - 172, 1993, 235, 229, 1193, -274, 5944, -918, - -15, 1304, 307, 1150, -385, -794, -3467, 660, - 2143, 147, -279, -751, -305, 1052, 205, -108, - 572, -212, 29, -50, 6, 3749, 238, -2016, - -1118, -1329, -971, 2633, 519, 194, 3545, -11, - 77, -92, 1215, -439, 152, -863, 1604, 180, - -514, 252, 308, -131, -938, 133, 378, 11, - 12153, 51, 486, 71, -476, -599, 57, -127, - 2685, -173, -182, 468, -3469, -594, -380, 265, - -879, -352, -278, -309, 575, 124, 10814, -765, - -64, 710, -105, 296, 2562, 98, -358, 556, - 2921, -133, -5, -406, 42, 496, -1053, -1957, - 701, 266, 260, -441, 43, -192, -1, -2174, - 9894, -90, -181, 29, 50, -858, 59, -190, - 49, -282, 1632, 1525, 100, -3659, 13, 173, - -240, 5304, -383, 263, -311, 1747, 169, -2203, - -29, -106, 342, -301, 66, 49, 23, 857, - -607, 698, -1198, -191, -450, -1875, -329, -2156, - 156, 95, 145, 129, -321, 88, 1049, 3980, - -14, 321, -1484, 895, -30, -2174, 289, 933, - -933, 15, 2631, 68, 3054, 221, -87, 175, - 200, 937, -87, -2032, 348, 146, -372, 60, - -2566, 3497, -98, 313, 536, -299, -58, -8949, - 323, -524, -331, 713, -47, 360, 155, 168, - 687, -1391, 1973, 670, 788, -202, -129, -5113, - 54, 1178, 1218, 172, 630, -154, -1047, 840, - 71, -337, 91, 214, -474, 624, -773, 16, - -126, 340, -631, -482, -155, 419, 50, -10976, - -742, -781, 169, 149, 33, -169, 44, 354, - 26, 129, -179, 1401, 776, -155, -3996, -813, - 594, 238, -61, 168, -383, -9261, 294, 470, - -322, -190, -956, -290, 27, -438, -254, 12571, - 344, -393, -568, 56, 81, 171, -115, -4370, - 49, -322, -237, -692, -55, -49, 4317, -6, - -4837, -156, 179, 247, -338, -48, 952, -1061, - -33, -934, 250, -256, -1622, 1039, -738, 2719, - -20, -190, 249, -119, -235, 6080, 123, -502, - -1443, 86, -1684, -177, -128, -58, -237, -641, - -177, 64, -2416, 15, -116, -6465, -412, 161, - 419, 768, 36, 113, -944, -241, -1424, -95, - 635, 1798, -2257, -18, 3046, 173, -33, -207, - -52, -831, -5730, -54, -199, 194, -255, 467, - -211, -853, -512, 11619, 148, 3681, -4603, -282, - 129, -205, -606, 167, 306, 464, 485, -959, - -203, 254, 151, -6880, -262, 5180, 658, -1378, - 1174, -53, -59, -33, -3077, -127, -223, -17, - -31, -2190, 23, 317, -169, 203, -223, -222, - -5295, 116, 80, -2757, -666, 3377, -476, 85, - -630, -147, 1740, -175, -115, 207, 240, -248, - -95, -1016, 3966, 3998, -343, -4751, 187, -113, - -250, 111, -510, -203, 130, 89, 311, 608, - -221, -381, -253, -359, -2254, 45, 224, -141, - 45, -19, 480, -5074, 797, -4580, -163, 110, - -234, 337, 6, 707, 492, -5493, -2750, -94, - -363, 113, 2345, 344, 379, 464, -3222, -56, - -269, -262, -10, -609, 324, 3043, 209, 3092, - -600, 42, -615, -17, -53, 30, 1123, 224, - 593, 632, -90, 428, 1117, -1429, -6741, -95, - -293, -103, -2784, 251, 1688, 621, -349, 1059, - -1093, -148, 447, 149, 88, 92, 687, 1249, - 80, 289, -1841, 221, -10, -92, -1736, 118, - 136, 138, -162, -4162, -111, 62, 95, 166, - -172, -695, -3685, 5694, -527, 2032, -549, 43, - -101, 221, 181, -479, 7697, 2007, -127, 805, - -83, -535, 1354, -383, 253, -622, 2910, 1249, - 782, 13, 42, 994, -545, 75, -485, 330, - -16, 343, 272, -781, 360, -97, -25, -875, - -12689, -623, -307, 195, -256, -11644, 229, 180, - -42, -361, -124, -81, -23, -460, -1993, 212, - -634, -847, 1616, -546, -583, 99, 3800, 10, - 177, 366, 6106, -173, 265, -213, 10, 1108, - -288, -1690, -237, -312, 38, -2272, 431, -26, - -178, -764, 507, 355, 677, -214, -816, -12411, - 47, 12, 294, -295, -3916, -677, -4885, -250, - -453, -7716, 478, 231, 17, -248, 147, 1064, - 637, -80, -41, 265, -383, 142, 116, 2991, - -3060, 809, 2056, -119, -866, -22, -660, 233, - 306, -1873, -1141, 6995, 186, -8678, -109, -39, - -105, 730, 18, -846, 273, -2922, 210, 26, - -174, -142, 990, 131, -436, 1422, -217, -3152, - 3224, 35, 315, -47, 48, -221, 568, 44, - 182, 1696, -1755, -193, 527, 158, -555, -3485, - 171, -4552, -47, -4680, 95, -112, 184, 80, - -36, -915, 87, 24, -259, -1743, 68, -117, - 405, 11, 40, -320, -17, -158, -134, -186, - -1206, -466, 1262, 133, -254, -100, 210, -1735, - -636, 319, -978, 69, 197, -521, -5503, -78, - -544, -1011, 101, -489, -371, -79, -196, -18, - -839, 1091, 682, -1441, -2375, -1127, 54, 829, - -306, -255, 641, -3665, 473, 3504, -1035, -160, - -467, -275, -437, 79, -13513, 326, 132, 82, - 188, 362, -74, 1406, -46, 2864, 351, -558, - -1277, 108, -92, -53, 72, -41, -31, -97, - 353, 73, 1864, -207, 106, -81, -3930, 173, - 41, -539, -497, 135, -526, -823, 69, -10, - 176, 648, -1710, 564, 80, 237, -1956, 234, - 11, 142, -849, 4116, -473, 110, 129, 2137, - -170, 3193, 10, 245, -953, -827, -30, 1235, - 366, -67, 54, -567, -7377, 2461, 582, 74, - -1988, -33, -296, 3090, -54, 145, 564, -295, -}; - -static const uint16_t bark_tab_l8_512[] = { - 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 8, 7, 9, - 9, 11, 11, 14, 15, 17, 20, 24, 28, 34, 41, 51, 64, 83, -}; - -static const uint16_t bark_tab_m8_256[] = { - 3, 4, 3, 4, 3, 4, 4, 5, 5, 6, 6, 8, 9, 11, 13, 17, 23, 29, 41, 58 -}; - -static const uint16_t bark_tab_s8_64[] = { - 2, 1, 2, 2, 3, 4, 5, 7, 13, 25 -}; - -static const uint16_t bark_tab_l8s_512[] = { - 7, 8, 7, 8, 8, 8, 8, 8, - 8, 9, 9, 10, 10, 11, 11, 12, - 12, 14, 15, 16, 18, 19, 21, 24, - 27, 30, 35, 40, 46, 53, -}; - -static const uint16_t bark_tab_s8s_64[] = { - 3, 3, 3, 3, 4, 5, 6, 8, - 12, 17, -}; - -static const uint16_t bark_tab_m8s_256[] = { - 6, 5, 6, 6, 6, 6, 7, 7, - 8, 8, 9, 10, 11, 13, 15, 18, - 20, 25, 31, 39, -}; - -static const uint16_t bark_tab_l11_512[] = { - 4, 4, 5, 4, 5, 4, 5, 6, - 6, 6, 7, 8, 9, 10, 12, 14, - 17, 21, 27, 33, 44, 58, 82, 121, -}; - -static const uint16_t bark_tab_s11_64[] = { - 2, 1, 2, 3, 4, 6, 13, 33, -}; - -static const uint16_t bark_tab_m11_256[] = { - 3, 3, 4, 3, 4, 4, 5, 6, - 7, 9, 11, 15, 21, 30, 48, 83, -}; - -static const uint16_t bark_tab_l11s_512[] = { - 6, 6, 6, 6, 6, 6, 7, 6, - 7, 7, 8, 8, 8, 9, 10, 10, - 11, 13, 13, 15, 17, 18, 21, 25, - 27, 33, 38, 45, 54, 66, -}; - -static const uint16_t bark_tab_s11s_64[] = { - 2, 3, 2, 3, 3, 4, 6, 8, - 12, 21, -}; - -static const uint16_t bark_tab_m11s_256[] = { - 4, 5, 4, 5, 5, 5, 6, 5, - 7, 7, 8, 9, 10, 12, 15, 17, - 22, 28, 35, 47, -}; - -static const uint16_t bark_tab_l16_1024[] = { - 5, 5, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 9, 10, 11, - 12, 14, 17, 19, 22, 27, 33, 40, 51, 64, 84, 114, 164, 257 -}; - -static const uint16_t bark_tab_m16_512[] = { - 3, 3, 3, 3, 4, 3, 4, 4, 4, 5, 5, 6, 7, 8, 10, 12, - 14, 18, 24, 30, 42, 59, 89, 152 -}; - -static const uint16_t bark_tab_s16_128[] = { - 2, 2, 2, 3, 3, 5, 7, 12, 25, 67 -}; - -static const uint16_t bark_tab_l16s_1024[] = { - 9, 9, 8, 9, 10, 9, 10, 10, - 10, 12, 11, 13, 13, 14, 16, 17, - 19, 20, 24, 26, 30, 35, 40, 48, - 56, 68, 83, 102, 128, 165, -}; - -static const uint16_t bark_tab_s16s_128[] = { - 3, 4, 4, 4, 5, 7, 10, 16, - 26, 49, -}; - -static const uint16_t bark_tab_m16s_512[] = { - 7, 6, 7, 7, 7, 8, 9, 9, - 10, 11, 14, 15, 18, 22, 27, 34, - 44, 59, 81, 117, -}; - -static const uint16_t bark_tab_l22_1024[] = { - 3, 4, 3, 4, 3, 4, 4, 4, - 4, 4, 5, 5, 5, 6, 7, 7, - 8, 9, 11, 12, 14, 16, 20, 24, - 29, 36, 45, 60, 80, 113, 173, 302, -}; - -static const uint16_t bark_tab_l22s_1024[] = { - 6, 7, 6, 6, 7, 7, 7, 7, - 7, 8, 9, 8, 10, 10, 11, 12, - 13, 15, 16, 18, 21, 24, 27, 33, - 38, 46, 55, 68, 84, 107, 140, 191, -}; - -static const uint16_t bark_tab_s22s_128[] = { - 3, 2, 3, 4, 4, 6, 9, 14, - 26, 57, -}; - -static const uint16_t bark_tab_m22s_512[] = { - 5, 5, 5, 6, 5, 7, 6, 7, - 9, 9, 11, 13, 15, 20, 24, 33, - 43, 61, 88, 140, -}; - -static const uint16_t bark_tab_l44_2048[] = { - 5, 6, 5, 6, 5, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, - 9, 10, 11, 11, 13, 14, 16, 17, 19, 22, 25, 29, 33, 39, 46, 54, - 64, 79, 98, 123, 161, 220, 320, 512, -}; - -#define bark_tab_m22_512 bark_tab_m44_512 /* Both tables are identical */ -static const uint16_t bark_tab_m44_512[] = { - 3, 2, 3, 3, 3, 4, 3, 5, 4, 6, 7, 8, 10, 14, 18, 25, - 36, 55, 95, 208, -}; - -#define bark_tab_s22_128 bark_tab_s44_128 /* Both tables are identical */ -static const uint16_t bark_tab_s44_128[] = { - 1, 2, 1, 2, 3, 4, 6, 10, 23, 76 -}; - -static const TwinVQModeTab metasound_mode0806 = { - { - { 8, bark_tab_s8_64, 10, fcb8s, 1, 5, cb0806ss0, cb0806ss1, 27 }, - { 2, bark_tab_m8_256, 20, fcb8m, 2, 5, cb0806sm0, cb0806sm1, 22 }, - { 1, bark_tab_l8_512, 30, fcb8l, 3, 6, cb0806sl0, cb0806sl1, 24 } - }, - 512, 12, ff_metasound_lsp8, 1, 5, 3, 3, shape8, 8, 28, 20, 6, 200 -}; - -static const TwinVQModeTab metasound_mode0806s = { - { - { 8, bark_tab_s8s_64, 10, fcb8ss, 1, 5, cb0806ss0, cb0806ss1, 27 }, - { 2, bark_tab_m8s_256, 20, fcb8sm, 2, 5, cb0806sm0, cb0806sm1, 22 }, - { 1, bark_tab_l8s_512, 30, fcb8sl, 3, 6, cb0806sl0, cb0806sl1, 24 } - }, - 512, 12, ff_metasound_lsp8, 1, 5, 3, 3, shape8s, 8, 28, 20, 6, 200 -}; - -static const TwinVQModeTab metasound_mode0808 = { - { - { 8, bark_tab_s8_64, 10, fcb8s, 1, 5, cb0808s0, cb0808s1, 18 }, - { 2, bark_tab_m8_256, 20, fcb8m, 2, 5, cb0808m0, cb0808m1, 16 }, - { 1, bark_tab_l8_512, 30, fcb8l, 3, 6, cb0808l0, cb0808l1, 17 } - }, - 512, 12, ff_metasound_lsp8, 1, 5, 3, 3, shape8, 8, 28, 20, 6, 200 -}; - -static const TwinVQModeTab metasound_mode0808s = { - { - { 8, bark_tab_s8s_64, 10, fcb8ss, 1, 5, cb0808ss0, cb0808ss1, 18 }, - { 2, bark_tab_m8s_256, 20, fcb8sm, 2, 5, cb0808sm0, cb0808sm1, 16 }, - { 1, bark_tab_l8s_512, 30, fcb8sl, 3, 6, cb0808sl0, cb0808sl1, 17 } - }, - 512, 12, ff_metasound_lsp8, 1, 5, 3, 3, shape8s, 8, 28, 20, 6, 200 -}; - -static const TwinVQModeTab metasound_mode1110 = { - { - { 8, bark_tab_s11_64, 8, fcb11s, 1, 5, cb1110s0, cb1110s1, 21 }, - { 2, bark_tab_m11_256, 16, fcb11m, 2, 5, cb1110m0, cb1110m1, 18 }, - { 1, bark_tab_l11_512, 24, fcb11l, 3, 6, cb1110l0, cb1110l1, 19 } - }, - 512, 16, ff_metasound_lsp11, 1, 6, 4, 3, shape11, 9, 28, 20, 7, 200 -}; - -static const TwinVQModeTab metasound_mode1110s = { - { - { 8, bark_tab_s11s_64, 10, fcb11ss, 1, 5, cb1110ss0, cb1110ss1, 21 }, - { 2, bark_tab_m11s_256, 20, fcb11sm, 2, 5, cb1110sm0, cb1110sm1, 18 }, - { 1, bark_tab_l11s_512, 30, fcb11sl, 3, 6, cb1110sl0, cb1110sl1, 20 } - }, - 512, 16, ff_metasound_lsp11, 1, 6, 4, 3, shape11s, 9, 36, 30, 7, 200 -}; - -static const TwinVQModeTab metasound_mode1616 = { - { - { 8, bark_tab_s16_128, 10, fcb16s, 1, 5, cb1616s0, cb1616s1, 16 }, - { 2, bark_tab_m16_512, 24, fcb16m, 2, 5, cb1616m0, cb1616m1, 15 }, - { 1, bark_tab_l16_1024, 30, fcb16l, 3, 6, cb1616l0, cb1616l1, 16 } - }, - 1024, 16, ff_metasound_lsp16, 1, 6, 4, 3, shape16, 9, 28, 30, 7, 200 -}; - -static const TwinVQModeTab metasound_mode1616s = { - { - { 8, bark_tab_s16s_128, 10, fcb16ss, 1, 5, cb1616ss0, cb1616ss1, 16 }, - { 2, bark_tab_m16s_512, 20, fcb16sm, 2, 5, cb1616sm0, cb1616sm1, 15 }, - { 1, bark_tab_l16s_1024, 30, fcb16sl, 3, 6, cb1616sl0, cb1616sl1, 16 } - }, - 1024, 16, ff_metasound_lsp16, 1, 6, 4, 3, shape16s, 9, 56, 60, 7, 200 -}; - -static const TwinVQModeTab metasound_mode2224 = { - { - { 8, bark_tab_s22_128, 10, fcb22s, 1, 6, cb2224s0, cb2224s1, 15 }, - { 2, bark_tab_m22_512, 20, fcb22m, 2, 6, cb2224m0, cb2224m1, 14 }, - { 1, bark_tab_l22_1024, 32, fcb22l, 4, 6, cb2224l0, cb2224l1, 15 } - }, - 1024, 16, ff_metasound_lsp22, 1, 6, 4, 3, shape22, 9, 56, 36, 7, 200 -}; - -static const TwinVQModeTab metasound_mode2224s = { - { - { 8, bark_tab_s22s_128, 10, fcb22ss, 1, 6, cb2224ss0, cb2224ss1, 15 }, - { 2, bark_tab_m22s_512, 20, fcb22sm, 2, 6, cb2224sm0, cb2224sm1, 14 }, - { 1, bark_tab_l22s_1024, 32, fcb22sl, 4, 6, cb2224sl0, cb2224sl1, 15 } - }, - 1024, 16, ff_metasound_lsp22, 1, 6, 4, 3, shape22s, 9, 56, 36, 7, 200 -}; - -static const TwinVQModeTab metasound_mode4432 = { - { - { 16, bark_tab_s44_128, 10, fcb44ss, 1, 6, cb4432s0, cb4432s1, 23 }, - { 4, bark_tab_m44_512, 20, fcb44sm, 2, 6, cb4432m0, cb4432m1, 21 }, - { 1, bark_tab_l44_2048, 40, fcb44sl, 4, 6, cb4432l0, cb4432l1, 22 } - }, - 2048, 20, ff_metasound_lsp44, 1, 6, 4, 4, shape44s, 9, 84, 54, 7, 200, -}; - -static const TwinVQModeTab metasound_mode4440 = { - { - { 16, bark_tab_s44_128, 10, fcb44ss, 1, 6, cb4440ss0, cb4440ss1, 18 }, - { 4, bark_tab_m44_512, 20, fcb44sm, 2, 6, cb4440sm0, cb4440sm1, 17 }, - { 1, bark_tab_l44_2048, 40, fcb44sl, 4, 6, cb4440sl0, cb4440sl1, 17 } - }, - 2048, 20, ff_metasound_lsp44, 1, 6, 4, 4, shape44s, 9, 84, 54, 7, 200 -}; - -static const TwinVQModeTab metasound_mode4448 = { - { - { 16, bark_tab_s44_128, 10, fcb44ss, 1, 6, cb4448ss0, cb4448ss1, 15 }, - { 4, bark_tab_m44_512, 20, fcb44sm, 2, 6, cb4448sm0, cb4448sm1, 14 }, - { 1, bark_tab_l44_2048, 40, fcb44sl, 4, 6, cb4448sl0, cb4448sl1, 14 } - }, - 2048, 20, ff_metasound_lsp44, 1, 6, 4, 4, shape44s, 9, 84, 54, 7, 200 -}; - -#endif /* AVCODEC_METASOUND_DATA_H */ diff --git a/spaces/congsaPfin/Manga-OCR/logs/Boney M. - Rivers of Babylon (Extended Version) - Video Download.md b/spaces/congsaPfin/Manga-OCR/logs/Boney M. - Rivers of Babylon (Extended Version) - Video Download.md deleted file mode 100644 index 046f556cd367489acc6e35044e97aa450ba25dc7..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Boney M. - Rivers of Babylon (Extended Version) - Video Download.md +++ /dev/null @@ -1,159 +0,0 @@ -
-

How to Download Boney M's Rivers of Babylon Video

-

If you are a fan of Boney M, you might want to download their classic hit Rivers of Babylon and watch it offline. This song is one of the most popular and successful songs of the disco era, and it has a catchy melody and meaningful lyrics. In this article, we will show you how to download the video of Rivers of Babylon from YouTube and other sources, using different methods and tools.

-

Introduction

-

What is Rivers of Babylon?

-

Rivers of Babylon is a song by the German disco group Boney M, released in 1978. It is based on a Rastafari song written by Brent Dowe and Trevor McNaughton of the Jamaican reggae group The Melodians in 1970. The lyrics are adapted from the texts of Psalms 19 and 137 in the Hebrew Bible, which express the longing of the Jewish people for their homeland after being exiled by the Babylonians. The song became a worldwide hit, reaching number one in several countries, including the UK, Germany, Australia, and Canada. It is also one of the best-selling singles of all time, with over 10 million copies sold.

-

download video boney m rivers of babylon


Download File ->->->-> https://urlca.com/2uObfQ



-

Why download the video?

-

There are many reasons why you might want to download the video of Rivers of Babylon. For example, you might want to:

-
    -
  • Watch it offline without internet connection or buffering issues
  • -
  • Save it on your device for personal use or backup
  • -
  • Edit it for your own purposes or projects
  • -
  • Share it with your friends or family who love Boney M
  • -
  • Enjoy the high-quality visuals and sound effects
  • -
-

No matter what your reason is, downloading the video is easy and fast, as long as you have the right tools and methods.

-

How to download the video from YouTube

-

One of the most common sources for watching Rivers of Babylon is YouTube, where you can find the official video uploaded by Boney M's channel, as well as other versions and covers by different artists. To download the video from YouTube, you can follow these simple steps:

-

Step 1: Copy the video URL

-

The first step is to copy the URL or link of the video that you want to download. You can do this by opening the video on YouTube, clicking on the share button below the video, and copying the link that appears. Alternatively, you can copy the link from your browser's address bar.

-

Step 2: Paste the URL into a video downloader software

-

The next step is to paste the URL into a video downloader software that can download videos from YouTube. There are many such software available online, both free and paid, for different platforms and devices. Some examples are:

- - - - - -
NameDescriptionLink
4K Video DownloaderA free software that can download videos in various formats and resolutions, including 4K and 8K
WinX YouTube DownloaderA free software that can download videos from over 300 sites, including YouTube, Facebook, Vimeo, etc.
iTubeGo YouTube Downloader A paid software that can download videos, audio, playlists, channels, subtitles, etc. from YouTube and other sites
-

You can choose any software that suits your needs and preferences, and install it on your device. Then, you can open the software and paste the URL that you copied in the previous step.

-

download video boney m rivers of babylon lyrics
-download video boney m rivers of babylon sopot festival 1979
-download video boney m rivers of babylon live
-download video boney m rivers of babylon remix
-download video boney m rivers of babylon mp4
-download video boney m rivers of babylon hd
-download video boney m rivers of babylon karaoke
-download video boney m rivers of babylon internet archive
-download video boney m rivers of babylon youtube
-download video boney m rivers of babylon tiktok
-download video boney m rivers of babylon instagram
-download video boney m rivers of babylon facebook
-download video boney m rivers of babylon song
-download video boney m rivers of babylon music
-download video boney m rivers of babylon album
-download video boney m rivers of babylon cover
-download video boney m rivers of babylon reaction
-download video boney m rivers of babylon dance
-download video boney m rivers of babylon performance
-download video boney m rivers of babylon meaning
-download video boney m rivers of babylon history
-download video boney m rivers of babylon story
-download video boney m rivers of babylon original
-download video boney m rivers of babylon version
-download video boney m rivers of babylon audio
-download video boney m rivers of babylon free
-download video boney m rivers of babylon online
-download video boney m rivers of babylon full
-download video boney m rivers of babylon official
-download video boney m rivers of babylon 1978
-download video boney m rivers of babylon 1981
-download video boney m rivers of babylon 1997
-download video boney m rivers of babylon 2022
-download video boney m rivers of babylon best quality
-download video boney m rivers of babylon high resolution
-download video boney m rivers of babylon low size
-download video boney m rivers of babylon fast speed
-download video boney m rivers of babylon easy way
-download video boney m rivers of babylon safe site
-download video boney m rivers of babylon no ads

-

Step 3: Choose the format and quality

-

The third step is to choose the format and quality of the video that you want to download. Depending on the software that you use, you might have different options and settings to customize your download. For example, you might be able to choose between MP4, MKV, AVI, FLV, etc. for the format, and between 360p, 480p, 720p, 1080p, etc. for the quality. You might also be able to download only the audio or the subtitles of the video. You can select the options that you prefer and click on the download button.

-

Step 4: Download and enjoy

-

The final step is to wait for the download to finish and enjoy watching Rivers of Babylon offline. Depending on the size and quality of the video, the download time might vary. Once the download is complete, you can find the video file in your device's storage or in the software's folder. You can then open the file with any media player and enjoy the song.

-

How to download the video from other sources

-

If you cannot find Rivers of Babylon on YouTube or you want to download it from other sources, there are some alternative methods that you can try. Here are some options:

-

Option 1: Use a browser extension

-

A browser extension is a small software that adds extra features to your web browser. Some browser extensions can help you download videos from various websites, including YouTube, Facebook, Vimeo, Dailymotion, etc. Some examples are:

-
    -
  • Video DownloadHelper: A free extension for Firefox and Chrome that can detect and download videos from many sites
  • -
  • Flash Video Downloader: A free extension for Chrome that can download videos from over 99% of video sites
  • -
  • SaveFrom.net Helper: A free extension for Firefox, Chrome, Opera, and Safari that can download videos from YouTube and other sites
  • -
-

You can install any extension that works with your browser and visit the website where Rivers of Babylon is available. Then, you can click on the extension icon in your browser toolbar and select the video that you want to download.

-

Option 2: Use an online video converter

-

An online video converter is a website that can convert and download videos from various sources without requiring any software installation. Some online video converters can also extract audio or subtitles from videos. Some examples are:

-
    -
  • OnlineVideoConverter: A free website that can convert and download videos from YouTube, Facebook, Instagram, Vimeo, etc.
  • -
  • ClipConverter: A free website that can convert and download videos from YouTube, Vimeo, Dailymotion, etc.
  • -
  • Y2Mate: A free website that can convert and download videos from YouTube and other sites
  • -
-

You can visit any website that offers this service and paste the URL of Rivers of Babylon in the input box. Then, you can choose the format and quality of the output file and click on the start or convert button. After the conversion is done, you can click on the download button to save the file on your device.

-

Option 3: Use a screen recorder

-

A screen recorder is a software that can record anything that happens on your device's screen. Some screen recorders can also record audio or webcam footage along with the screen. Some examples are:

-
    -
  • OBS Studio: A free and open source software that can record and stream video and audio from your screen
  • -
  • Camtasia: A paid software that can record and edit video and audio from your screen
  • -
  • Bandicam: A paid software that can record high-quality video and audio from your screen
  • -
-

You can install any software that meets your requirements and launch it on your device. Then, you can adjust the settings such as resolution, frame rate, audio source, etc. and start recording. You can then play Rivers of Babylon on your device's screen while recording it with the software. After you finish recording, you can stop it and save it as a video file.

-

Conclusion

-

In this article, we have shown you how to download Boney M's Rivers of Babylon video from YouTube and other sources, using different methods and tools. We hope that you have found this article helpful and informative, and that you have enjoyed watching this classic song offline. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!

-

Summary of the main points

-

Here are the main points that we have covered in this article:

-
    -
  • Rivers of Babylon is a song by Boney M, based on a Rastafari song and the texts of Psalms 19 and 137
  • -
  • It is one of the most popular and successful songs of the disco era, and one of the best-selling singles of all time
  • -
  • There are many reasons why you might want to download the video of Rivers of Babylon, such as watching it offline, saving it, editing it, sharing it, or enjoying it
  • -
  • You can download the video from YouTube using a video downloader software, such as 4K Video Downloader, WinX YouTube Downloader, or iTubeGo YouTube Downloader
  • -
  • You can download the video from other sources using a browser extension, such as Video DownloadHelper, Flash Video Downloader, or SaveFrom.net Helper
  • -
  • You can also download the video using an online video converter, such as OnlineVideoConverter, ClipConverter, or Y2Mate
  • -
  • Another option is to use a screen recorder, such as OBS Studio, Camtasia, or Bandicam
  • -
-

Call to action

-

If you liked this article, please share it with your friends and family who love Boney M. You can also subscribe to our newsletter for more tips and tricks on how to download videos from various sources. And if you want to learn more about Boney M and their music, check out their official website or follow them on social media. Thank you for your support!

-

FAQs

-

Here are some frequently asked questions about downloading Boney M's Rivers of Babylon video:

-

Q: Is it legal to download videos from YouTube and other sources?

-

A: The answer to this question depends on the terms and conditions of the source website, the copyright laws of your country, and the purpose of your download. Generally speaking, it is legal to download videos for personal use or fair use, but not for commercial use or distribution. However, we recommend that you always respect the rights and wishes of the original creators and owners of the videos.

-

Q: What is the best format and quality for downloading videos?

-

A: The best format and quality for downloading videos depend on your preferences and needs. Some factors that you might consider are:

-
    -
  • The size and storage space of your device
  • -
  • The compatibility and performance of your media player
  • -
  • The speed and stability of your internet connection
  • -
  • The quality and resolution of your screen
  • -
  • The purpose and audience of your download
  • -
-

Generally speaking, MP4 is a widely supported and versatile format that can play on most devices and platforms. As for the quality, higher resolutions such as 1080p or 4K offer better clarity and detail, but they also require more bandwidth and storage space.

-

Q: How long does it take to download a video?

-

A: The time it takes to download a video depends on several factors, such as:

-
    -
  • The size and quality of the video
  • -
  • The speed and stability of your internet connection
  • -
  • The performance and capacity of your device
  • -
  • The method and tool that you use for downloading
  • -
-

Generally speaking, the larger and higher quality the video is, the longer it will take to download. However, some methods and tools can speed up the download process by using multiple threads or servers.

-

Q: How can I edit the video after downloading it?

-

A: If you want to edit the video after downloading it, you will need a video editing software that can handle the format and quality of the video. There are many video editing software available online, both free and paid, for different platforms and devices. Some examples are:

-
    -
  • VSDC Free Video Editor: A free software that can edit videos in various formats and resolutions
  • -
  • Filmora: A paid software that can edit videos with professional features and effects
  • -
  • Adobe Premiere Pro: A paid software that can edit videos with advanced tools and workflows
  • -
-

You can choose any software that suits your needs and preferences, and install it on your device. Then, you can import the video file that you downloaded and edit it as you wish. You can trim, crop, rotate, merge, split, add transitions, filters, text, music, etc. to your video. After you finish editing, you can export and save the video in your desired format and quality.

-

Q: How can I share the video with others?

-

If you want to share the video with others, you have several options, such as:

-
    -
  • Uploading it to a video sharing platform, such as YouTube, Vimeo, Dailymotion, etc.
  • -
  • Sending it via email, messaging apps, social media, etc.
  • -
  • Transferring it via USB drive, Bluetooth, Wi-Fi Direct, etc.
  • -
  • Burning it to a CD or DVD
  • -
-

However, before you share the video with others, make sure that you have the permission and consent of the original creators and owners of the video. Also, respect the privacy and preferences of the people that you share the video with. Do not spam or harass anyone with unwanted or inappropriate videos.

-

-

This is the end of the article. I hope that you have learned how to download Boney M's Rivers of Babylon video from YouTube and other sources. Thank you for reading and have a nice day!

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Download Genshin Impact APK and Explore a Magical World of Adventure.md b/spaces/congsaPfin/Manga-OCR/logs/Download Genshin Impact APK and Explore a Magical World of Adventure.md deleted file mode 100644 index 0fa3b8848b94387b376e0cace4909b009c3b9bb7..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Download Genshin Impact APK and Explore a Magical World of Adventure.md +++ /dev/null @@ -1,119 +0,0 @@ -
-

Genshin Impact Game Download APK: How to Play This Amazing Open-World RPG on Your Android Device

-

Introduction

-

If you are a fan of open-world action RPGs, you might have heard of Genshin Impact, one of the most popular and acclaimed games of 2020. Genshin Impact is a game that lets you step into a vast magical world of adventure, where you can explore seven nations, meet a diverse cast of characters, and fight powerful enemies. But did you know that you can also play this game on your Android device? In this article, we will show you how to download and install Genshin Impact APK on your Android device, and how to play this amazing game on your mobile screen.

-

genshin impact game download apk


Download File - https://urlca.com/2uO4pw



-

What is Genshin Impact?

-

Genshin Impact is an open-world action RPG developed by miHoYo, a Chinese game studio. The game was released in September 2020 for Windows, PlayStation 4, iOS, and Android platforms, and has since received millions of downloads and positive reviews from players and critics alike. The game is set in a fantasy world called Teyvat, where seven nations are ruled by seven gods of different elements. You play as a traveler who arrives in this world from another dimension, looking for your lost sibling. Along the way, you will encounter various characters who will join you in your quest, as well as enemies who will try to stop you.

-

Why should you play Genshin Impact on your Android device?

-

Genshin Impact is a game that offers a lot of features and content that will keep you entertained for hours. Here are some of the reasons why you should play Genshin Impact on your Android device:

-
    -
  • You can enjoy stunning graphics and animations that bring the world of Teyvat to life.
  • -
  • You can experience immersive gameplay that lets you interact with different elements and environments.
  • -
  • You can choose from over 30 playable characters with unique personalities and abilities.
  • -
  • You can customize your own team and combat style according to your preferences.
  • -
  • You can explore a vast open world that offers various quests, events, secrets, and rewards.
  • -
  • You can join other players in co-op mode and share your adventures with them.
  • -
  • You can play the game for free, with optional in-game purchases that enhance your experience.
  • -
-

How to download and install Genshin Impact APK on your Android device

-

If you want to play Genshin Impact on your Android device, you will need to download and install the APK file of the game. The APK file is a package that contains all the necessary files and data for the game to run on your device. Here are the steps to download and install Genshin Impact APK on your Android device:

-

Step 1: Go to the official website of Genshin Impact

-

The first step is to go to the official website of Genshin Impact at [genshin.mihoyo.com/en/download](^1^). This is where you can find the latest version of the game for different platforms. You can also learn more about the game's features, characters, story, and updates from this website.

-

genshin impact apk download free for android
-how to install genshin impact game on mobile
-genshin impact android game latest version download
-download genshin impact apk + obb file
-genshin impact mobile game download size
-genshin impact apk mod unlimited primogems
-genshin impact game download for pc
-genshin impact android game requirements
-genshin impact apk offline play mode
-genshin impact game download link
-genshin impact apk update 3.7.0 download
-genshin impact android game review
-genshin impact apk no verification needed
-genshin impact game download error fix
-genshin impact android game tips and tricks
-genshin impact apk compatible devices list
-genshin impact game download without vpn
-genshin impact android game controller support
-genshin impact apk safe and secure download
-genshin impact game download speed boost
-genshin impact apk english version download
-genshin impact android game best characters
-genshin impact apk full unlocked download
-genshin impact game download guide for beginners
-genshin impact android game graphics settings
-genshin impact apk chinese version download
-genshin impact android game redeem codes
-genshin impact apk hack free download
-genshin impact game download problem solution
-genshin impact android game wiki and walkthrough
-genshin impact apk direct download link
-genshin impact android game tier list
-genshin impact apk cracked version download
-genshin impact game download tutorial video
-genshin impact android game system requirements
-genshin impact apk original version download
-genshin impact android game new features
-genshin impact apk data download for android
-genshin impact game download steps and instructions
-genshin impact android game best weapons and artifacts
-genshin impact apk mirror download site
-genshin impact android game faq and answers
-genshin impact apk latest update download news
-genshin impact game download issues and fixes
-genshin impact android game gameplay and story
-genshin impact apk pure download source
-genshin impact android game ratings and reviews
-genshin impact apk old version download archive
-genshin impact game download benefits and advantages

-

Step 2: Tap on the "Download Now" button

-

Once you are on the website, you will see a big "Download Now" button on the top right corner of the screen. Tap on this button and you will be redirected to a page where you can choose your platform. Since you are using an Android device, tap on the "Android" icon and you will see a QR code that you can scan with your device's camera. Alternatively, you can also tap on the "Download APK" button below the QR code and you will start downloading the APK file directly to your device.

-

Step 3: Allow the installation of unknown sources

-

Before you can install the APK file, you will need to allow your device to install apps from unknown sources. This is because Genshin Impact is not available on the Google Play Store, so you will need to install it from a third-party source. To do this, go to your device's settings and look for the security or privacy option. Then, find the option that says "Allow installation of apps from unknown sources" or something similar, and enable it. You may also see a pop-up message asking for your permission when you try to install the APK file. In that case, just tap on "Allow" or "OK".

-

Step 4: Install the APK file and launch the game

-

After you have downloaded the APK file and allowed the installation of unknown sources, you can now install the APK file by tapping on it. You will see a screen that shows the app's information and permissions. Tap on "Install" and wait for the installation process to finish. Once it is done, you can tap on "Open" and launch the game. You may also see a shortcut icon of the game on your home screen or app drawer.

-

How to play Genshin Impact on your Android device

-

Now that you have installed Genshin Impact on your Android device, you are ready to play this amazing game. Here are some tips on how to play Genshin Impact on your Android device:

-

Create your account and choose your character

-

When you launch the game for the first time, you will need to create your account and choose your character. You can either use your email address or your miHoYo account to create your account. You can also link your account to other platforms such as Facebook, Twitter, or Google if you want to sync your progress across devices. After creating your account, you will be asked to choose your character's gender and name. You can also customize your character's appearance later in the game.

-

Explore the vast world of Teyvat and interact with various elements

-

Genshin Impact is an open-world game that lets you explore a vast world of Teyvat, where you can find different regions, cities, landmarks, dungeons, and secrets. You can use the map to navigate and fast travel to different locations. You can also interact with various elements in the world, such as water, fire, wind, earth, and more. For example, you can use fire to burn wooden objects, use wind to glide in the air, use water to swim or freeze enemies, and use earth to create shields or platforms. You can also collect resources such as plants, ores, fruits, and animals that you can use for crafting or cooking.

-

Fight enemies and bosses with different combat styles and skills

-

Genshin Impact is also an action game that lets you fight enemies and bosses with different combat styles and skills. You can switch between four characters in your team at any time during combat, each with their own weapons and abilities. You can also combine different elements to create powerful reactions that deal more damage or have other effects. For example, you can use fire and ice to create melt, water and electricity to create electro-charged, wind and fire to create swirl, and more. You can also use items such as food or potions to heal or buff yourself during combat.

-

Collect items, weapons, and characters to enhance your gameplay

-

Genshin Impact is also a game that lets you collect items, weapons, and characters to enhance your gameplay. You can find items such as artifacts or materials that can improve your stats or skills. You can also find weapons such as swords, bows, spears, claymores, or catalysts that have different effects or bonuses. You can also find characters that have different personalities, stories, elements, and abilities. You can obtain items, weapons, and characters by completing quests, exploring chests, participating in events, or using wishes.

-

Conclusion

-

Genshin Impact is a game that offers a lot of fun and excitement for anyone who loves open-world action RPGs. You can download and install Genshin Impact APK on your Android device and enjoy this amazing game on your mobile screen. You can explore a vast world of Teyvat, interact with various elements, fight enemies and bosses, and collect items, weapons, and characters. You can also join other players in co-op mode and share your adventures with them. Genshin Impact is a game that will keep you entertained for hours with its stunning graphics, immersive gameplay, and diverse content. If you are looking for a game that will challenge your skills and imagination, you should definitely try out Genshin Impact.

-

FAQs

-

Here are some of the frequently asked questions about Genshin Impact:

- - - - - - - - - - - - - - - - - - - - - - - - - -
QuestionAnswer
Is Genshin Impact free to play?Yes, Genshin Impact is free to play, with optional in-game purchases that enhance your experience.
Is Genshin Impact cross-platform?Yes, Genshin Impact is cross-platform, meaning you can play with other players on different platforms such as Windows, PlayStation 4, iOS, and Android.
How many characters are there in Genshin Impact?There are over 30 playable characters in Genshin Impact, each with their own personalities, stories, elements, and abilities.
How do I get more wishes in Genshin Impact?You can get more wishes in Genshin Impact by using primogems, which are the premium currency of the game. You can obtain primogems by completing quests, exploring chests, participating in events, or buying them with real money.
What are the best characters in Genshin Impact?The best characters in Genshin Impact depend on your personal preference and playstyle. However, some of the most popular and powerful characters are Diluc, Venti, Klee, Zhongli, Keqing, and Qiqi.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/FIFA Mobile MOD APK The Best Way to Unlock All Players and Get Unlimited Money.md b/spaces/congsaPfin/Manga-OCR/logs/FIFA Mobile MOD APK The Best Way to Unlock All Players and Get Unlimited Money.md deleted file mode 100644 index a9f702323863642f4a68f870d4fcb5853d4201b6..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/FIFA Mobile MOD APK The Best Way to Unlock All Players and Get Unlimited Money.md +++ /dev/null @@ -1,85 +0,0 @@ - -

FIFA APK All Players Unlocked: How to Enjoy the Ultimate Soccer Game on Your Mobile Device

-

If you are a fan of soccer games, you probably know about FIFA Mobile, one of the most popular and realistic soccer games on mobile devices. But did you know that there is a way to enjoy this game even more? Yes, we are talking about FIFA APK, a modified version of the official game that gives you access to all the features and content of the game without any restrictions. In this article, we will tell you everything you need to know about FIFA APK, how to download and install it on your Android device, how to play it and unlock all the players in the game, and some tips and tricks to master it and dominate your opponents.

-

What is FIFA APK and why you should download it

-

FIFA APK is a modified version of the official FIFA Mobile game

-

FIFA Mobile is a soccer game developed by EA Sports that lets you build your ultimate team of soccer stars and compete in various modes, such as Head-to-Head, VS Attack, Manager Mode, and World Cup Mode. The game features over 15,000 authentic soccer players from over 600 teams across 30+ leagues, including world-class talent like Kylian Mbappé, Christian Pulisic, Vinicius Jr., Son Heung-min, Virgil van Dijk, Kai Havertz, Jude Bellingham, Alphonso Davies, Dušan Vlahović, and many more. The game also features new gameplay technology for PlayStation 5, Xbox Series X|S, and Stadia

FIFA APK gives you access to all the features and content of the game without any restrictions

-

One of the main reasons why you should download FIFA APK is that it gives you unlimited access to all the features and content of the game without any restrictions. Unlike the official game, which requires you to spend real money or grind for hours to unlock players, modes, and items, FIFA APK gives you everything for free. You can enjoy the game without worrying about ads, in-app purchases, or waiting times. You can also customize the game settings to suit your preferences and device performance.

-

fifa apk all players unlocked


Downloadhttps://urlca.com/2uOdX0



-

FIFA APK lets you play with all the players, teams, and modes in the game, including the FIFA World Cup 2022 mode

-

Another reason why you should download FIFA APK is that it lets you play with all the players, teams, and modes in the game, including the FIFA World Cup 2022 mode. You can build your ultimate team with over 15,000 authentic soccer players from over 600 teams across 30+ leagues, including world-class talent like Kylian Mbappé, Christian Pulisic, Vinicius Jr., Son Heung-min, Virgil van Dijk, Kai Havertz, Jude Bellingham, Alphonso Davies, Dušan Vlahović, and many more. You can also relive the world‘s greatest soccer tournament with FIFA APK. FIFA Mobile is the only licensed FIFA World Cup 2022™ mobile game where you can replay the official tournament brackets with any of the 32 qualified nations. You can also enjoy the new gameplay features, such as HyperMotion, explosive sprint, finesse shots, and adaptive right stick switching.

-

How to download and install FIFA APK on your Android device

-

Find a reliable source for downloading the FIFA APK file

-

The first step to download and install FIFA APK on your Android device is to find a reliable source for downloading the FIFA APK file. There are many websites that offer FIFA APK files for free, but not all of them are safe and trustworthy. Some of them may contain viruses, malware, or spyware that can harm your device or steal your personal information. Therefore, you should be careful and do some research before downloading any APK file from unknown sources. You can check the reviews, ratings, comments, and feedback from other users to verify the credibility and quality of the website. You can also use antivirus software or online tools to scan the APK file for any potential threats.

-

Enable unknown sources on your device settings

-

The next step to download and install FIFA APK on your Android device is to enable unknown sources on your device settings. This is necessary because Android devices do not allow installing apps from sources other than Google Play Store by default. To enable unknown sources, you need to go to your device settings and look for security or privacy options. There you will find an option to allow installation of apps from unknown sources. You need to toggle it on and confirm your choice. This will allow you to install FIFA APK on your device.

Locate and tap on the downloaded APK file to start the installation process

-

The third step to download and install FIFA APK on your Android device is to locate and tap on the downloaded APK file to start the installation process. You can use a file manager app or your device's default file explorer to find the APK file in your download folder or any other location where you saved it. Once you find the APK file, you need to tap on it and confirm your choice. This will initiate the installation process of FIFA APK on your device.

-

Follow the instructions on the screen and wait for the installation to finish

-

The final step to download and install FIFA APK on your Android device is to follow the instructions on the screen and wait for the installation to finish. You may need to grant some permissions or accept some terms and conditions before proceeding with the installation. You can also choose the destination folder where you want to install FIFA APK on your device. After that, you just need to wait for a few minutes until the installation is completed. You will see a notification or a shortcut icon on your device's home screen when FIFA APK is successfully installed.

-

How to play FIFA APK and unlock all the players in the game

-

Launch the game and sign in with your EA account or create a new one

-

Now that you have downloaded and installed FIFA APK on your Android device, you are ready to play it and unlock all the players in the game. To start playing, you need to launch the game and sign in with your EA account or create a new one if you don't have one already. Signing in with your EA account will allow you to sync your progress, achievements, and preferences across different devices and platforms. You can also link your Facebook, Google, or Apple accounts to your EA account for easier access and social features.

-

fifa mobile mod apk unlimited money and players
-fifa 22 apk download with all players unlocked
-fifa 23 mod apk free download all players unlocked
-fifa world cup 2022 apk unlock all players
-fifa soccer apk mod unlock all players and kits
-fifa ultimate team apk hack all players unlocked
-fifa 21 apk obb download with all players unlocked
-fifa 20 apk data unlock all players and modes
-fifa 19 apk mod unlock all players and stadiums
-fifa 18 apk full version unlock all players and teams
-fifa 17 apk cracked unlock all players and leagues
-fifa 16 apk unlimited coins and players unlocked
-fifa 15 apk modded unlock all players and skills
-fifa 14 apk offline unlock all players and tournaments
-fifa 13 apk free download with all players unlocked
-fifa mobile v18.1.03 mod apk (unlocked all, unlimited money, menu)
-fifa mobile hack apk download unlock all players and features
-fifa mobile cheats apk unlock all players and rewards
-fifa mobile unlimited players apk no root required
-fifa mobile all players unlocked apk latest version
-download fifa mobile mod apk with all players unlocked
-how to unlock all players in fifa mobile apk
-best fifa mobile mod apk with all players unlocked
-free fifa mobile mod apk with all players unlocked
-working fifa mobile mod apk with all players unlocked
-download game fifa mobile mod apk unlock all players
-install fifa mobile mod apk unlock all players
-update fifa mobile mod apk unlock all players
-play fifa mobile mod apk unlock all players online
-enjoy fifa mobile mod apk unlock all players offline
-get fifa mobile mod apk unlock all players for android
-download fifa mobile mod apk unlock all players for ios
-share fifa mobile mod apk unlock all players with friends
-rate fifa mobile mod apk unlock all players on google play
-review fifa mobile mod apk unlock all players on app store
-watch video of fifa mobile mod apk unlock all players gameplay
-read blog about fifa mobile mod apk unlock all players tips and tricks
-join forum of fifa mobile mod apk unlock all players fans and users
-follow social media of fifa mobile mod apk unlock all players developers and updates
-subscribe to newsletter of fifa mobile mod apk unlock all players news and offers

-

Choose your favorite team and start building your ultimate team with star players from the biggest leagues and top teams

-

After signing in with your EA account, you can choose your favorite team and start building your ultimate team with star players from the biggest leagues and top teams. You can select from over 600 teams across 30+ leagues, including world-class talent like Kylian Mbappé, Christian Pulisic, Vinicius Jr., Son Heung-min, Virgil van Dijk, Kai Havertz, Jude Bellingham, Alphonso Davies, Dušan Vlahović, and many more. You can also customize your team's name, logo, kit, stadium, and anthem. You can use the unlimited money and menu features of FIFA APK to buy packs, upgrade players, and customize your team as much as you want.

groundbreaking new gameplay technology that uses advanced 11v11 motion capture and machine learning to deliver the most realistic and responsive soccer experience ever. You can also use explosive sprint, a new gameplay mechanic that lets you accelerate past defenders with more speed and agility. You can also unleash finesse shots, a new way of scoring goals with more precision and flair. And you can also switch players more easily and intuitively with adaptive right stick switching, a new feature that lets you change your controlled player based on the direction of your right stick.

-

Tips and tricks to master FIFA APK and dominate your opponents

-

Pick the perfect formation for your playstyle and adjust your tactics accordingly

-

One of the tips to master FIFA APK and dominate your opponents is to pick the perfect formation for your playstyle and adjust your tactics accordingly. You can choose from different formations, such as 4-3-3, 4-4-2, 3-5-2, 5-3-2, and more. You can also customize your tactics, such as defensive style, offensive style, width, depth, players in box, corners, free kicks, and more. You can also change your formation and tactics during the game to adapt to different situations and scenarios. You should experiment with different combinations and find the one that suits your team and strategy best.

-

Learn how to use player switching, defending, dribbling, passing, and shooting effectively

-

Another tip to master FIFA APK and dominate your opponents is to learn how to use player switching, defending, dribbling, passing, and shooting effectively. You can use player switching to control the player closest to the ball or the one in the best position to intercept or attack. You can use defending to block, tackle, slide, jockey, or pressure your opponents. You can use dribbling to control the ball, change direction, speed up, or slow down. You can use passing to move the ball around, create chances, or switch play. And you can use shooting to score goals from different angles, distances, or situations. You should practice your skills in training mode and challenge yourself in different difficulty levels.

Join a league or create your own and compete with other players online

-

A third tip to master FIFA APK and dominate your opponents is to join a league or create your own and compete with other players online. You can join an existing league or create your own with your friends or other players from around the world. You can participate in league tournaments, chat with your league members, and earn rewards and bonuses. You can also challenge other leagues in inter-league championships and climb the leaderboards. You can also play friendly matches with your league mates or other players to test your skills and have fun.

-

Keep an eye on the latest updates, events, and rewards in the game

-

A fourth tip to master FIFA APK and dominate your opponents is to keep an eye on the latest updates, events, and rewards in the game. FIFA APK is constantly updated with new features, content, and improvements to enhance your gaming experience. You can also enjoy various events and campaigns that are based on real-life soccer events, such as the FIFA World Cup 2022, UEFA Champions League, UEFA Europa League, Copa America, CONCACAF Gold Cup, and more. You can also earn rewards and prizes by completing missions, objectives, achievements, and daily challenges. You can also claim free gifts and bonuses by logging in daily or watching ads.

-

Conclusion

-

In conclusion, FIFA APK is a modified version of the official FIFA Mobile game that gives you access to all the features and content of the game without any restrictions. You can play with all the players, teams, and modes in the game, including the FIFA World Cup 2022 mode. You can also enjoy the new gameplay features, such as HyperMotion, explosive sprint, finesse shots, and adaptive right stick switching. You can also download and install FIFA APK on your Android device easily by following the steps we have provided. And you can also master FIFA APK and dominate your opponents by following the tips and tricks we have shared. So what are you waiting for? Download FIFA APK now and enjoy the ultimate soccer game on your mobile device!

-

FAQs

-

Q1. Is FIFA APK safe to download and use?

-

A1. FIFA APK is safe to download and use as long as you download it from a reliable source that does not contain any viruses, malware, or spyware. You should also scan the APK file before installing it on your device to ensure its safety. However, you should be aware that downloading and using FIFA APK may violate EA Sports' terms of service and may result in account suspension or ban. Therefore, you should use FIFA APK at your own risk and discretion.

-

Q2. Do I need to root my device or use an emulator to play FIFA APK?

-

A2. No, you do not need to root your device or use an emulator to play FIFA APK. You can play FIFA APK on any Android device that meets the minimum system requirements of the game. However, you may need to enable unknown sources on your device settings to install FIFA APK on your device.

-

Q3. Can I play FIFA APK offline or online?

-

A3. You can play FIFA APK offline or online depending on the game mode you choose. Some game modes, such as Head-to-Head, VS Attack, Manager Mode, and World Cup Mode require an internet connection to play. Other game modes, such as training mode, skill games, and offline tournaments can be played offline without an internet connection.

Q4. How can I update FIFA APK to the latest version?

-

A4. You can update FIFA APK to the latest version by downloading and installing the new APK file from the same source where you downloaded the previous version. You should also check the website regularly for any new updates or announcements regarding FIFA APK. You can also enable the auto-update feature on your device settings to automatically download and install the latest version of FIFA APK when it is available.

-

Q5. How can I contact EA Sports for support or feedback?

-

A5. You can contact EA Sports for support or feedback by visiting their official website, social media pages, or help center. You can also use the in-game customer service feature to report any issues or problems you encounter while playing FIFA APK. However, you should be aware that EA Sports may not provide support or feedback for FIFA APK users, as they do not endorse or authorize the use of modified versions of their games. Therefore, you should use FIFA APK at your own risk and discretion.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Fly Corp Airline Manager - A Game that Lets You Create Your Own Airline Network.md b/spaces/congsaPfin/Manga-OCR/logs/Fly Corp Airline Manager - A Game that Lets You Create Your Own Airline Network.md deleted file mode 100644 index 9a8326739754aa859e9a0e35faed2662050d25f4..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Fly Corp Airline Manager - A Game that Lets You Create Your Own Airline Network.md +++ /dev/null @@ -1,106 +0,0 @@ - -

Fly Corp APK: A Review of the Airline Manager Game

-

Have you ever dreamed of running your own airline business and becoming the richest tycoon in the world? If so, you might want to check out Fly Corp APK, a strategy game that lets you develop your own transport network in various countries and cities. In this article, we will review Fly Corp APK and tell you everything you need to know about this addictive game.

-

fly corp apk


Download Ziphttps://urlca.com/2uOcUR



-

How to Play Fly Corp APK

-

Fly Corp APK is a game that challenges you to open new routes, buy new planes, upgrade them, increase the capacity of the airports, and manage the passenger flow. Here are some of the aspects of the gameplay that you should know:

-

Connect the world

-

In this game, the whole world is your playing field. You can build airports and expand your airline network in almost 200 countries and thousands of cities. You can become the founder of the biggest and most profitable airline empire in history.

-

Develop air transport routes

-

Different locations require good airline management skills as you’ll have to adapt to different conditions. For instance, European distances are short, and it’s very easy to manage the passenger flow here, while popular transatlantic routes will make you think more about travel time and expenses.

-

Control the passenger flow

-

The game features an advanced passenger flow system. All the cities are designed according to their real analogs, and the population numbers are true. The more population figures are, the more people would like to fly by your airplanes. Each passenger has their own destination, and they’ll fly with transfers if there are no direct routes.

-

Upgrade airports and aircrafts

-

Since you don’t have enough money to connect each city to all the other cities, you should analyze the situation and make important decisions about where the transport hub is going to be situated. Planes, as well as airports, have their maximum capacity. You’ll lose profit even if one of them gets overloaded. So, you should learn to run your airline business as fast as you can.

-

What are the Features of Fly Corp APK

-

Fly Corp APK is not just a simple strategy game. It also has many features that make it more fun and engaging. Here are some of them:

- Various game modes -

Fly Corp APK offers you different game modes to suit your preferences and skills. You can unlock all countries and play in the free mode, where you can create your own airline empire without any limitations. You can also try the scenarios mode, where you have to complete specific tasks and objectives in a given time. Or you can challenge yourself in the hard mode, where you have to deal with more competition and higher costs.

-

Regular challenges

-

The game also adds some random events that spice up your gameplay. For example, you might face a strike, a natural disaster, a terrorist attack, or a pandemic that affects your passenger flow and revenue. You have to react quickly and wisely to these situations and minimize the damage to your airline business.

-

Stunning graphics

-

One of the most impressive features of Fly Corp APK is its realistic and colorful graphics. The game has a 3D design that shows the airports, planes, and maps in great detail. You can zoom in and out, rotate, and move the camera to see your airline network from different angles. The game also has dynamic weather effects, day and night cycles, and smooth animations that make it more immersive.

-

fly corp airline manager apk
-fly corp game apk download
-fly corp mod apk unlimited money
-fly corp idle tycoon apk
-fly corp airport game apk
-fly corp apk latest version
-fly corp apk for android
-fly corp apk free download
-fly corp apk offline
-fly corp apk hack
-fly corp apk mod menu
-fly corp apk no ads
-fly corp apk old version
-fly corp apk pure
-fly corp apk revdl
-fly corp apk update
-fly corp beta apk
-fly corp cheats apk
-fly corp cracked apk
-fly corp full apk
-fly corp hacked apk
-fly corp premium apk
-fly corp pro apk
-fly corp unlocked apk
-download fly corp apk for pc
-download fly corp apk for ios
-download fly corp apk for windows 10
-download fly corp apk for laptop
-download fly corp apk for mac
-download fly corp apk for chromebook
-download fly corp apk modded
-download fly corp apkpure
-download fly corp apkmirror
-download fly corp apknite
-download fly corp apksfull
-how to install fly corp apk on android
-how to install fly corp apk on pc
-how to install fly corp apk on ios
-how to install fly corp apk on windows 10
-how to install fly corp apk on laptop
-how to install fly corp apk on mac
-how to install fly corp apk on chromebook
-how to play fly corp apk on pc
-how to play fly corp apk on ios
-how to play fly corp apk on windows 10
-how to play fly corp apk on laptop
-how to play fly corp apk on mac
-how to play fly corp apk on chromebook

-

Easy controls

-

Fly Corp APK is very easy to play on your mobile device. You just need to tap, swipe, and drag to perform various actions. You can open new routes, buy new planes, upgrade them, increase the capacity of the airports, and manage the passenger flow with simple gestures. The game also has a user-friendly interface that shows you all the information you need to run your airline business efficiently.

-

How to Download and Install Fly Corp APK

-

If you are interested in playing Fly Corp APK, you can download and install it on your Android device in a few steps. Here is how:

-

Step 1: Go to the official website or Google Play Store and click on the download button

-

You can get Fly Corp APK from its official website or from the Google Play Store. Both sources are safe and reliable. Just search for Fly Corp APK and click on the download button to start the process.

-

Step 2: Wait for the APK file to be downloaded on your device

-

The download speed depends on your internet connection and the size of the file. It should not take more than a few minutes to complete.

-

Step 3: Enable unknown sources in your settings if you downloaded from the website

-

If you downloaded Fly Corp APK from the website, you need to enable unknown sources in your settings before installing it. This is because the game is not from the official Google Play Store and your device might block it by default. To enable unknown sources, go to Settings > Security > Unknown Sources and toggle it on.

-

Step 4: Locate the APK file in your file manager and tap on it to install it

-

Once you have enabled unknown sources, you can locate the APK file in your file manager. It should be in the Downloads folder or wherever you saved it. Tap on it to start the installation process.

-

Step 5: Launch the game and enjoy being an airline tycoon

-

After the installation is done, you can launch Fly Corp APK from your app drawer or home screen. You can now create your own airline empire and enjoy being an airline tycoon.

-

Conclusion

-

Fly Corp APK is a strategy game that lets you run your own airline business and connect the world with your transport network. You can build airports, buy planes, upgrade them, open new routes, manage passenger flow, and deal with random events. The game has various game modes, regular challenges, stunning graphics, and easy controls. It is a fun and addictive game that will keep you entertained for hours.

-

FAQs

-

Here are some of the frequently asked questions about Fly Corp APK:

-

Q1: Is Fly Corp APK free to play?

-

A1: Yes, Fly Corp APK is free to play. However, it contains ads and in-app purchases that can enhance your gameplay experience.

-

Q2: How can I get more money in Fly Corp APK?

-

A2: There are several ways to get more money in Fly Corp APK. You can complete tasks and objectives, participate in challenges, watch ads, or buy coins with real money.

-

Q3: What are the best strategies to win in Fly Corp APK?

-

A3: Some of the best strategies to win in Fly Corp APK are:

-
    -
  • Analyze the demand and supply
  • Analyze the demand and supply of different routes and choose the most profitable ones
  • -
  • Upgrade your airports and planes to increase their capacity and efficiency
  • -
  • Balance the passenger flow and avoid overloading or underutilizing your resources
  • -
  • React to random events and minimize their impact on your revenue
  • -
-

Q4: Can I play Fly Corp APK offline?

-

A4: No, Fly Corp APK requires an internet connection to play. This is because the game uses real data and maps to simulate the passenger flow and destinations.

-

Q5: Is Fly Corp APK safe to download?

-

A5: Yes, Fly Corp APK is safe to download. The game does not contain any viruses, malware, or spyware. However, you should always download it from a trusted source, such as the official website or the Google Play Store.

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Trivia Crack 2 The Ultimate Brain Game for Android Devices.md b/spaces/congsaPfin/Manga-OCR/logs/Trivia Crack 2 The Ultimate Brain Game for Android Devices.md deleted file mode 100644 index 56d70f70bb082a536a4295beb0c42898baa340ac..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Trivia Crack 2 The Ultimate Brain Game for Android Devices.md +++ /dev/null @@ -1,124 +0,0 @@ - -

Trivia Crack 2 Download: How to Play the Ultimate Trivia Game on Your Device

-

Do you love trivia games? Do you want to test your knowledge on various topics and challenge your friends and family? Do you want to have fun and learn something new every day? If you answered yes to any of these questions, then you should try Trivia Crack 2, the sequel to one of the most popular trivia games ever. In this article, we will tell you everything you need to know about Trivia Crack 2, how to download it on your device, how to play it, and why you should play it. Let's get started!

-

What is Trivia Crack 2?

-

Trivia Crack 2 is a trivia game developed by Etermax, the same company that created the original Trivia Crack. It was released in October 2018 for Android and iOS devices. It is a free-to-play game with in-app purchases and ads.

-

trivia crack 2 download


Downloadhttps://urlca.com/2uOedc



-

A sequel to the popular trivia game

-

Trivia Crack 2 is the follow-up to Trivia Crack, which was launched in 2013 and became a global phenomenon with over 500 million downloads. Trivia Crack 2 builds on the success of the original game by adding new features, modes, characters, questions, and more. It also has improved graphics, sound effects, and animations.

-

A brain game with tons of topics and modes

-

Trivia Crack 2 is a brain game that will test your knowledge on your favorite TV shows, movies, books, artists, and more. It has six categories: Art, Science, History, Entertainment, Sport, and Geography. Each category has a corresponding character that you need to collect by answering questions correctly. There are hundreds of thousands of trivia questions for you to answer, some of them created by other users.

-

Trivia Crack 2 also has different game modes for you to enjoy. You can play in Classic Mode, where you compete against another player in a one-on-one trivia contest. You can also play in Tower Duel, where you have to answer more questions than your opponent in each category within six minutes. You can also play in Daily Challenge, where you have to answer a series of questions without making any mistakes. There are also other modes like Tic-Tac-5, Rescue Rush, Pirate Battle, Lucky Spin, Missions, Collections, and more.

-

A social game with teams and chat

-

Trivia Crack 2 is not only a brain game but also a social game. You can connect with your Facebook friends or other players from around the world. You can create or join a team of up to 50 members and chat with them. You can also send or request lives to other members and play together against other teams. You can also customize your avatar with different frames, outfits, accessories, and stickers.

-

How to download Trivia Crack 2?

-

Downloading Trivia Crack 2 is easy and free. All you need is a compatible device and an internet connection.

-

For Android devices

-

If you have an Android device (smartphone or tablet), you can download Trivia Crack 2 from the Google Play Store. Just follow these steps:

-

trivia crack 2 apk
-trivia crack 2 app
-trivia crack 2 bluestacks
-trivia crack 2 cheats
-trivia crack 2 characters
-trivia crack 2 coins
-trivia crack 2 collections
-trivia crack 2 for pc
-trivia crack 2 free
-trivia crack 2 game
-trivia crack 2 hack
-trivia crack 2 help
-trivia crack 2 ios
-trivia crack 2 iphone
-trivia crack 2 latest version
-trivia crack 2 mod apk
-trivia crack 2 online
-trivia crack 2 play store
-trivia crack 2 power ups
-trivia crack 2 questions
-trivia crack 2 quiz
-trivia crack 2 reddit
-trivia crack 2 review
-trivia crack 2 tips
-trivia crack 2 tower duel
-trivia crack 2 update
-trivia crack 2 vip membership
-trivia crack 2 website
-how to download trivia crack 2 on android
-how to download trivia crack 2 on mac
-how to download trivia crack 2 on windows
-how to get free coins in trivia crack 2
-how to get free lives in trivia crack 2
-how to get more crowns in trivia crack 2
-how to play mystery doors in trivia crack 2
-how to play pirate battle in trivia crack 2
-how to play rescue rush in trivia crack 2
-how to play tic tac toe in trivia crack 2
-how to uninstall trivia crack 2
-is trivia crack 2 offline
-is trivia crack 2 safe
-is trivia crack 2 worth it
-what is the best strategy for trivia crack 2
-what is the difference between trivia crack and trivia crack 2
-what is the highest level in trivia crack 2
-what is the most popular category in trivia crack 2
-what is the new update for trivia crack 2
-what is the official website of trivia crack 2

-
    -
  1. Open the Google Play Store app on your device.
  2. -
  3. Search for "Trivia Crack 2" in the search bar.
  4. -
  5. Tap on the Trivia Crack 2 icon and then tap on "Install".
  6. -
  7. Wait for the download and installation to finish.
  8. -
  9. Tap on "Open" to launch the game and start playing.
  10. -
-

You can also download Trivia Crack 2 from the official website by scanning the QR code or clicking on the download link.

-

For iOS devices

-

If you have an iOS device (iPhone or iPad), you can download Trivia Crack 2 from the App Store. Just follow these steps:

-
    -
  1. Open the App Store app on your device.
  2. -
  3. Search for "Trivia Crack 2" in the search bar.
  4. -
  5. Tap on the Trivia Crack 2 icon and then tap on "Get".
  6. -
  7. Enter your Apple ID password or use Touch ID or Face ID to confirm.
  8. -
  9. Wait for the download and installation to finish.
  10. -
  11. Tap on "Open" to launch the game and start playing.
  12. -
-

You can also download Trivia Crack 2 from the official website by scanning the QR code or clicking on the download link.

-

How to play Trivia Crack 2?

-

Playing Trivia Crack 2 is simple and fun. All you need is a device, an internet connection, and some trivia knowledge. Here are some basic steps to get you started:

-

The basics: answer questions and collect characters

-

The main goal of Trivia Crack 2 is to answer trivia questions and collect characters. Each character represents a category: Art (Pop), Science (Tina), History (Hector), Entertainment (Bonzo), Sport (Tito), and Geography (Al). To collect a character, you need to answer three questions correctly in a row in that category. You can also spin a wheel to randomly select a category or a special event. If you answer a question incorrectly, you lose your turn and your opponent gets a chance to steal your character. The first player to collect all six characters wins the game.

-

The game modes: Tower Duel, Daily Challenge, Classic Mode, and more

-

Trivia Crack 2 has different game modes for you to enjoy. You can play in Tower Duel, where you have to answer more questions than your opponent in each category within six minutes. You can also play in Daily Challenge, where you have to answer a series of questions without making any mistakes. You can also play in Classic Mode, where you compete against another player in a one-on-one trivia contest. There are also other modes like Tic-Tac-5, Rescue Rush, Pirate Battle, Lucky Spin, Missions, Collections, and more. Each mode has its own rules, rewards, and challenges.

-

The tips and tricks: watch the clock, observe your opponent, skip categories, ask for help, create your own team, etc.

-

To play Trivia Crack 2 well, you need to use some tips and tricks. Here are some of them:

-
    -
  • Watch the clock: Some game modes have a time limit, so you need to answer quickly and accurately. You can also use power-ups like Freeze Time or Double Time to gain an advantage.
  • -
  • Observe your opponent: You can see what categories your opponent has collected and what questions they have answered. You can use this information to plan your strategy and target their weaknesses.
  • -
  • Skip categories: If you don't like a category or you think it's too hard, you can skip it by spinning the wheel again. However, this will cost you some coins or gems, so use it wisely.
  • -
  • Ask for help: If you don't know the answer to a question, you can ask for help from your friends or other players. You can also use power-ups like Bomb or Double Chance to eliminate wrong answers or get a second chance.
  • -
  • Create your own team: You can create or join a team of up to 50 members and chat with them. You can also send or request lives to other members and play together against other teams.
  • -
-

Why play Trivia Crack 2?

-

Trivia Crack 2 is not only a game but also a learning experience. Here are some reasons why you should play it:

-

To sharpen your mind and test your knowledge

-

Trivia Crack 2 is a brain game that will challenge your memory, logic, and curiosity. You will learn new facts and trivia on various topics and categories. You will also improve your mental skills and speed by answering questions under pressure.

-

To have fun and challenge yourself and others

-

Trivia Crack 2 is a fun game that will make you laugh, smile, and cheer. You will enjoy the colorful graphics, the cute characters, the funny sound effects, and the witty questions. You will also challenge yourself and others by playing in different game modes and competing against players from around the world. You will also earn coins, gems, crowns, trophies, and other rewards by playing well.

-

To collect prizes and customize your avatar

-

Trivia Crack 2 is a game that will let you express your personality and style. You will collect prizes and items by playing in different game modes and completing missions and collections. You will also customize your avatar with different frames, outfits, accessories, and stickers. You can also create your own questions and share them with other players.

-

Conclusion and FAQs

-

Trivia Crack 2 is a trivia game that you can download and play on your device. It is a sequel to the popular Trivia Crack game that has new features, modes, characters, questions, and more. It is a brain game that will test your knowledge on various topics and categories. It is a social game that will connect you with your friends and other players. It is a fun game that will entertain you and challenge you. It is a game that you should try if you love trivia games.

-

Here are some FAQs about Trivia Crack 2:

-
    -
  1. Q: How can I contact the support team of Trivia Crack 2?
    -A: You can contact the support team of Trivia Crack 2 by tapping on the settings icon on the top right corner of the screen, then tapping on "Help" and then on "Contact Us". You can also email them at support@etermax.com or visit their website at https://www.triviacrack2.com/.
  2. -
  3. Q: How can I remove ads from Trivia Crack 2?
    -A: You can remove ads from Trivia Crack 2 by purchasing the ad-free version of the game for $4.99. You can also get rid of ads temporarily by using power-ups like No Ads or Ad Blocker.
  4. -
  5. Q: How can I report inappropriate questions or players in Trivia Crack 2?
    -A: You can report inappropriate questions or players in Trivia Crack 2 by tapping on the flag icon next to the question or the player's name. You can also block or mute players by tapping on their profile picture and then on the block or mute icon.
  6. -
  7. Q: How can I restore my progress in Trivia Crack 2?
    -A: You can restore your progress in Trivia Crack 2 by logging in with your Facebook account or your email address. You can also sync your progress across different devices by using the same login method.
  8. -
  9. Q: How can I update Trivia Crack 2?
    -A: You can update Trivia Crack 2 by visiting the Google Play Store or the App Store and checking for updates. You can also enable automatic updates on your device settings.
  10. -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/World Football League Mod The Ultimate Guide to Unlock All Teams Players and Modes.md b/spaces/congsaPfin/Manga-OCR/logs/World Football League Mod The Ultimate Guide to Unlock All Teams Players and Modes.md deleted file mode 100644 index 84d72b6d6b1326cf159e572dfa7d99b815059bf0..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/World Football League Mod The Ultimate Guide to Unlock All Teams Players and Modes.md +++ /dev/null @@ -1,109 +0,0 @@ - -

World Football League Mod: A Guide for Soccer Fans

-

If you are a fan of soccer, you might have heard of World Football League, a popular mobile game that lets you experience the thrill of the sport. But did you know that there is a mod version of this game that offers even more features and fun? In this article, we will tell you everything you need to know about World Football League Mod, including what it is, how to download and install it, why you should play it, and some tips and tricks to help you win. We will also compare it with other soccer games to show you why it is one of the best choices for soccer lovers.

-

world football league mod


Download https://urlca.com/2uO9VD



-

What is World Football League Mod?

-

World Football League Mod is a modified version of World Football League, a game developed by TouchTao. The original game is a realistic and exciting soccer simulation that features around 60 national teams, 60 clubs, and 2000 players. You can play in four different modes: Exhibition, Cup, League, and Training. You can also enjoy splendid dribble, thrilling shooting, and various skills in the game.

-

The mod version of World Football League adds some extra features and benefits to the game, such as unlimited coins, unlocked players, teams, and modes, no ads, and more. With these features, you can enjoy the game without any limitations or interruptions. You can also customize your team and players according to your preferences.

-

Features of World Football League Mod

-

Here are some of the main features of World Football League Mod that make it different from the original game:

-
    -
  • Unlimited coins: You can earn as many coins as you want in the game without spending any real money. Coins are used to buy and upgrade players, teams, stadiums, and other items in the game.
  • -
  • Unlocked players, teams, and modes: You can access all the players, teams, and modes in the game without having to unlock them by playing or paying. You can choose any team or player you like and play in any mode you want.
  • -
  • No ads: You can play the game without any annoying ads that pop up on your screen. This way, you can focus on the game and have a smooth gaming experience.
  • -
  • No root required: You do not need to root your device to install or play World Football League Mod. You can simply download the apk file from a trusted source and install it on your device.
  • -
-

How to download and install World Football League Mod

-

If you want to download and install World Football League Mod on your device, you need to follow these simple steps:

-
    -
  1. Go to a reliable website that offers the mod apk file of World Football League. For example, you can use [PlayMods](^1^), which provides safe and fast downloads.
  2. -
  3. Click on the download button on the website and wait for the file to be downloaded on your device.
  4. -
  5. Once the file is downloaded, go to your device settings and enable the installation of apps from unknown sources. This will allow you to install the mod apk file on your device.
  6. -
  7. Locate the downloaded file on your device and tap on it to start the installation process.
  8. -
  9. Follow the instructions on the screen and wait for the installation to be completed.
  10. -
  11. Launch the game from your app drawer and enjoy playing World Football League Mod.
  12. -
-

Why play World Football League Mod?

-

You might be wondering why you should play World Football League Mod instead of other soccer games on your device. Here are some of the reasons why World Football League Mod is a great choice for soccer fans:

-

Enjoy realistic and exciting soccer gameplay

-

World Football League Mod offers you a realistic and exciting soccer gameplay that will make you feel like you are on the field. You can control your players with easy and intuitive touch controls, and perform various skills such as dribbling, shooting, passing, tackling, and more. You can also adjust the difficulty level and the game speed according to your preference. The game also features realistic physics, animations, and sound effects that enhance the gaming experience.

-

world football league mod apk
-world football league mod unlimited money
-world football league mod apk download
-world football league mod apk latest version
-world football league mod apk android 1
-world football league mod apk revdl
-world football league mod apk offline
-world football league mod apk hack
-world football league mod apk 2023
-world football league mod apk unlimited coins
-world football league mod menu
-world football league mod apk 1.9.9.9.4
-world football league mod apk rexdl
-world football league mod apk happymod
-world football league mod apk 1.9.9.9.3
-world football league mod download
-world football league mod free shopping
-world football league mod apk pure
-world football league mod apk 1.9.9.9.2
-world football league mod apk 1.9.9.9.1
-world football league mod all unlocked
-world football league mod apk uptodown
-world football league mod apk 1.9.9.8
-world football league mod apk 1.9.9.7
-world football league mod apk 1.9.9.6
-world football league mod unlimited coins and gems
-world football league mod apk no ads
-world football league mod apk 1.9.9.5
-world football league mod apk 1.9.8
-world football league mod apk 1.9.7
-world football league mod apk 1.9.6
-world football league mod apk 1.9.5
-world football league mod apk 1.9.4
-world football league mod apk 1.9.3
-world football league mod apk 1.9.2
-world football league mod apk 1.9.1
-world football league mod apk 1.8
-world football league mod unlimited everything
-world football league hack mod download
-download game world football league mod apk
-cara download game world football league mod apk
-how to install world football league mod apk
-how to play world football league mod offline
-how to update world football league mod apk
-how to get unlimited money in world football league
-how to unlock all teams in world football league
-how to hack world football league with lucky patcher
-how to cheat in world football league

-

Choose from a variety of teams and players

-

World Football League Mod gives you the opportunity to choose from a variety of teams and players from around the world. You can play with around 60 national teams, 60 clubs, and 2000 players in the game. You can also customize your team and players with different kits, logos, names, and stats. You can create your own dream team and compete with other teams in the game.

-

Compete in different modes and tournaments

-

World Football League Mod offers you different modes and tournaments to play and challenge yourself. You can play in four different modes: Exhibition, Cup, League, and Training. Each mode has its own rules and objectives. You can also participate in various tournaments such as the World Cup, the Champions League, the Europa League, and more. You can win trophies and rewards by playing in these tournaments.

-

Tips and tricks for World Football League Mod

-

If you want to improve your skills and performance in World Football League Mod, you can follow these tips and tricks:

-

Master the controls and skills

-

The first thing you need to do is to master the controls and skills of the game. You can use the virtual joystick on the left side of the screen to move your players, and the buttons on the right side to perform actions such as passing, shooting, tackling, etc. You can also swipe on the screen to perform skills such as dribbling, sprinting, or changing direction. You should practice these controls and skills in the Training mode before playing in other modes.

-

Upgrade your players and team

-

The second thing you need to do is to upgrade your players and team. You can use the coins that you earn in the game to buy and upgrade players, teams, stadiums, and other items. You can also use the mod features to unlock all the players, teams, and modes in the game. You should try to get the best players and team for your style of play.

-

Use the mod features wisely

-

The third thing you need to do is to use the mod features wisely. While the mod features can give you some advantages in the game, they can also make the game less challenging and fun. You should not abuse the mod features or use them too often. You should also respect other players and not cheat or hack in online matches.

-

Comparison table of World Football League Mod and other soccer games

-

To give you a better idea of how World Football League Mod compares with other soccer games on mobile devices, we have created this comparison table for you:

- | Game | World Football League Mod | FIFA Mobile | Dream League Soccer | PES Mobile | | --- | --- | --- | --- | --- | | Size | 41 MB | 100 MB | 350 MB | 1.7 GB | | Graphics | 3D | 3D | 3D | 3D | | Gameplay | Realistic | Realistic | Arcade | Realistic | | Modes | Exhibition, Cup, League, Training | Attack Mode, Seasons, Events, Leagues | Career Mode, Online Mode | Matchday Mode, Tour Mode, Event Mode | | Teams/Players | 60/2000 | 650/17000 | 20/5000 | 400/10000 | | Customization | Yes | Yes | Yes | Yes | | Online Play | No | Yes | Yes | Yes | | Mod Features | Unlimited coins, unlocked players/teams/modes, no ads, no root required | None | Unlimited coins/gems/stamina/players/teams/modes/stadiums/kits/logos/etc., no ads/root required | None |

ConclusionConclusion

-

World Football League Mod is a fantastic soccer game that offers you a realistic and exciting gameplay, a variety of teams and players, different modes and tournaments, and some amazing mod features. If you are a soccer fan, you should definitely try this game and enjoy the thrill of the sport. You can download and install World Football League Mod easily and safely from a trusted website. You can also follow our tips and tricks to improve your skills and performance in the game. We hope this article has helped you learn more about World Football League Mod and why it is one of the best soccer games on mobile devices.

-

FAQs

-

Here are some of the frequently asked questions about World Football League Mod:

-
    -
  • Q: Is World Football League Mod safe to download and play?
  • -
  • A: Yes, World Football League Mod is safe to download and play as long as you get it from a reliable website that does not contain any viruses or malware. You should also scan the file before installing it on your device.
  • -
  • Q: Is World Football League Mod compatible with my device?
  • -
  • A: World Football League Mod is compatible with most Android devices that have Android 4.0 or higher. However, some devices may not support the game or may experience some issues while playing it. You should check the device requirements before downloading the game.
  • -
  • Q: How can I update World Football League Mod?
  • -
  • A: World Football League Mod does not have an official update system, so you will have to manually download and install the latest version of the game from the website where you got it. You should also backup your game data before updating the game to avoid losing your progress.
  • -
  • Q: How can I contact the developer of World Football League Mod?
  • -
  • A: World Football League Mod is not an official product of TouchTao, the developer of World Football League. It is a modded version of the game created by independent developers. Therefore, you cannot contact TouchTao for any issues or feedback related to World Football League Mod. You can try to contact the mod developers through their website or social media platforms, but they may not respond or provide any support.
  • -
  • Q: Can I play World Football League Mod offline?
  • -
  • A: Yes, you can play World Football League Mod offline without any internet connection. However, some features of the game may not work properly or may require an internet connection to function.
  • -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/X-Minus.pro Remove or Isolate Vocals from Any Song with AI APK.md b/spaces/congsaPfin/Manga-OCR/logs/X-Minus.pro Remove or Isolate Vocals from Any Song with AI APK.md deleted file mode 100644 index 0e6e895ef1068d9c4ec32700ebdd5b741afbc41b..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/X-Minus.pro Remove or Isolate Vocals from Any Song with AI APK.md +++ /dev/null @@ -1,130 +0,0 @@ -
-

X-Minus Pro Vocal Remover APK Download: How to Remove Vocals from Any Song

-

Do you love singing karaoke but don't have the right tracks? Do you want to create your own remixes or mashups of your favorite songs? Do you need to isolate the vocals or instruments from a song for your audio projects?

-

x minus pro vocal remover apk download


DOWNLOADhttps://urlca.com/2uOeTM



-

If you answered yes to any of these questions, then you need a vocal remover software that can separate the vocals from the music in any song. And one of the best vocal remover software available today is X-Minus Pro Vocal Remover.

-

In this article, we will show you what X-Minus Pro Vocal Remover is, how to download and install it on your Android device, how to use it to remove vocals from any song, and what benefits it offers. We will also compare it with some alternatives that you can try if you are looking for more options.

-

What is X-Minus Pro Vocal Remover?

-

X-Minus Pro Vocal Remover is a powerful and professional vocal remover software that can remove vocals from any song in seconds. It uses advanced artificial intelligence algorithms to analyze the audio spectrum and separate the vocal and instrumental components. You can then download or share the karaoke track without vocals, or the acapella track with only vocals.

-

X-Minus Pro Vocal Remover is not only a vocal remover, but also a vocal extractor, a vocal reducer, a vocal enhancer, and a vocal isolator. You can use it to adjust the volume, pitch, tempo, and key of the vocals or instruments, as well as apply various effects and filters. You can also use it to record your own voice over the instrumental track, or mix different tracks together.

-

Features of X-Minus Pro Vocal Remover

-

Some of the main features of X-Minus Pro Vocal Remover are:

-

x minus pro music separator app download
-x minus pro karaoke maker apk free download
-x minus pro vocal extractor android app
-x minus pro backing track creator apk download
-x minus pro acapella maker app for android
-x minus pro song splitter apk free download
-x minus pro instrumental maker android app
-x minus pro vocal isolation app download
-x minus pro remove vocals from songs apk
-x minus pro music editor apk free download
-x minus pro voice remover app for android
-x minus pro karaoke track maker apk download
-x minus pro vocal reducer android app
-x minus pro music mixer apk free download
-x minus pro singing practice app for android
-x minus pro vocal eliminator apk download
-x minus pro music remover app for android
-x minus pro karaoke converter apk free download
-x minus pro vocal filter android app
-x minus pro music cutter apk download
-x minus pro voice changer app for android
-x minus pro karaoke editor apk free download
-x minus pro vocal eraser android app
-x minus pro music composer apk download
-x minus pro voice extractor app for android
-x minus pro karaoke generator apk free download
-x minus pro vocal suppressor android app
-x minus pro music producer apk download
-x minus pro voice isolator app for android
-x minus pro karaoke splitter apk free download
-x minus pro vocal remover online app
-x minus pro music separator apk mod download
-x minus pro voice reducer app for android
-x minus pro karaoke remover apk premium download
-x minus pro vocal remover offline app
-x minus pro music separator apk latest version download
-x minus pro voice eliminator app for android
-x minus pro karaoke extractor apk cracked download
-x minus pro vocal remover ai app
-x minus pro music separator apk old version download
-x minus pro voice eraser app for android
-x minus pro karaoke isolator apk hacked download
-x minus pro vocal remover software app
-x minus pro music separator apk no ads download
-x minus pro voice filter app for android
-x minus pro karaoke reducer apk unlocked download
-x minus pro vocal remover website app
-x minus pro music separator apk update download
-x minus pro voice suppressor app for android

-
    -
  • It can remove vocals from any song, regardless of the genre, language, or quality.
  • -
  • It can extract vocals from any song, leaving only the instrumental track.
  • -
  • It can reduce or enhance the vocals in any song, making them more or less audible.
  • -
  • It can isolate vocals or instruments from any song, allowing you to focus on a specific element.
  • -
  • It can adjust the volume, pitch, tempo, and key of the vocals or instruments in any song.
  • -
  • It can apply various effects and filters to the vocals or instruments in any song, such as reverb, echo, chorus, flanger, distortion, equalizer, compressor, limiter, etc.
  • -
  • It can record your own voice over the instrumental track, or mix different tracks together.
  • -
  • It supports multiple audio formats, such as MP3, WAV, OGG, FLAC, M4A, etc.
  • -
  • It supports multiple languages, such as English, Spanish, French, German, Italian, Portuguese, Russian, etc.
  • -
  • It offers affordable and flexible pricing plans, starting from $0.99 per track.
  • -
-

How to download and install X-Minus Pro Vocal Remover APK

-

To download and install X-Minus Pro Vocal Remover APK on your Android device, follow these steps:

-
    -1^)https://x-minus.pro/en/vocal-remover">https://x-minus.pro/en/vocal-remover, the official website of X-Minus Pro Vocal Remover. -
  1. Click on the "Download APK" button and wait for the file to be downloaded.
  2. -
  3. Go to your device's settings and enable the installation of apps from unknown sources.
  4. -
  5. Locate the downloaded APK file and tap on it to install it.
  6. -
  7. Launch the app and sign up or log in with your email or social media account.
  8. -
  9. Enjoy using X-Minus Pro Vocal Remover to remove vocals from any song.
  10. -
-

How to remove vocals from a song using X-Minus Pro Vocal Remover

-

To remove vocals from a song using X-Minus Pro Vocal Remover, follow these steps:

-

Step 1: Upload or record a song

-

Open the app and tap on the "+" button to upload or record a song. You can choose a song from your device's storage, or from your cloud services, such as Google Drive, Dropbox, etc. You can also record a song using your device's microphone, or use the built-in browser to search for a song online.

-

Step 2: Choose the vocal removal mode

-

After uploading or recording a song, you will see four options at the bottom of the screen: Remove Vocals, Extract Vocals, Reduce Vocals, and Enhance Vocals. Tap on the "Remove Vocals" option to remove vocals from the song. You will see a progress bar indicating the vocal removal process.

-

Step 3: Adjust the settings and preview the result

-

Once the vocal removal process is completed, you will see a waveform of the karaoke track without vocals. You can adjust the settings of the track, such as volume, pitch, tempo, and key, by using the sliders at the top of the screen. You can also apply various effects and filters to the track, such as reverb, echo, chorus, flanger, distortion, equalizer, compressor, limiter, etc., by tapping on the "FX" button at the bottom right corner of the screen. You can preview the result by tapping on the play button at the bottom center of the screen.

-

Step 4: Download or share the karaoke track

-

If you are satisfied with the result, you can download or share the karaoke track without vocals. To download the track, tap on the "Download" button at the bottom left corner of the screen. You can choose to download the track in MP3, WAV, OGG, FLAC, or M4A format. To share the track, tap on the "Share" button next to the "Download" button. You can choose to share the track via email, social media, messaging apps, etc.

-

Benefits of using X-Minus Pro Vocal Remover

-

Using X-Minus Pro Vocal Remover has many benefits, such as:

-

High-quality vocal removal

-

X-Minus Pro Vocal Remover uses advanced artificial intelligence algorithms to analyze and separate the vocal and instrumental components of any song. It can remove vocals from any song with high accuracy and quality, leaving no traces or artifacts. It can also preserve the original quality and characteristics of the instrumental track.

-

Easy and fast operation

-

X-Minus Pro Vocal Remover has a simple and intuitive user interface that makes it easy and fast to use. You can remove vocals from any song in seconds with just a few taps. You can also adjust and customize various settings and effects according to your preferences and needs.

-

Multiple formats and languages supported

-

X-Minus Pro Vocal Remover supports multiple audio formats, such as MP3, WAV, OGG, FLAC, M4A, etc., so you can upload or download any song in any format. It also supports multiple languages, such as English, Spanish, French, German, Italian, Portuguese, Russian, etc., so you can remove vocals from any song in any language.

-

Affordable and flexible pricing plans

-

X-Minus Pro Vocal Remover offers affordable and flexible pricing plans that suit different budgets and needs. You can choose to pay per track ($0.99 per track), per month ($9.99 per month for unlimited tracks), or per year ($99.99 per year for unlimited tracks). You can also cancel your subscription at any time without any hassle.

-

Alternatives to X-Minus Pro Vocal Remover

-

If you are looking for more options to remove vocals from songs, you can also try some of the alternatives to X-Minus Pro Vocal Remover, such as:

-

Lalal.ai

-

Lalal.ai is an online vocal remover service that uses a deep learning model to separate vocals and instruments from any song. It can remove vocals from any song with high quality and speed, and supports various audio formats, such as MP3, WAV, FLAC, etc. You can use it for free for up to 10 minutes of audio, or upgrade to a premium plan for more minutes and features.

-

Spleeter

-

Spleeter is an open-source vocal remover tool that uses a deep learning model to split any song into multiple tracks, such as vocals, drums, bass, piano, etc. It can separate up to five tracks from any song with high quality and speed, and supports various audio formats, such as MP3, WAV, OGG, etc. You can use it online or offline, but you need some technical skills to install and run it.

-

AudioDirector

-

AudioDirector is a professional audio editing software that can remove vocals from any song with ease and precision. It can also extract vocals from any song, or adjust the volume and pitch of the vocals or instruments. It can also apply various effects and filters to the audio tracks, such as noise reduction, reverb, echo, etc. It supports various audio formats, such as MP3, WAV, FLAC, etc., and integrates with video editing software, such as PowerDirector.

-

Conclusion

-

X-Minus Pro Vocal Remover is a powerful and professional vocal remover software that can remove vocals from any song in seconds. It uses advanced artificial intelligence algorithms to analyze and separate the vocal and instrumental components of any song. You can then download or share the karaoke track without vocals, or the acapella track with only vocals.

-

X-Minus Pro Vocal Remover is not only a vocal remover, but also a vocal extractor, a vocal reducer, a vocal enhancer, and a vocal isolator. You can use it to adjust the volume, pitch, tempo, and key of the vocals or instruments in any song. You can also use it to record your own voice over the instrumental track, or mix different tracks together.

-

X-Minus Pro Vocal Remover supports multiple audio formats and languages, and offers affordable and flexible pricing plans. You can download and install it on your Android device easily and quickly. You can also try some of the alternatives to X-Minus Pro Vocal Remover if you are looking for more options.

-

FAQs

-

Here are some of the frequently asked questions about X-Minus Pro Vocal Remover:

-
    -
  1. Is X-Minus Pro Vocal Remover safe to use?
  2. -

    Yes, X-Minus Pro Vocal Remover is safe to use. It does not contain any viruses or malware. It also respects your privacy and does not collect or share your personal data or audio files.

    -
  3. Can X-Minus Pro Vocal Remover remove vocals from any song?
  4. -

    Yes, X-Minus Pro Vocal Remover can remove vocals from any song, regardless of the genre, language, or quality. However, some songs may have more complex or mixed vocals that may be harder to remove completely. In that case, you can try different vocal removal modes or settings to get the best result.

    -
  5. Can X-Minus Pro Vocal Remover work offline?
  6. -

    No, X-Minus Pro Vocal Remover requires an internet connection to work. It uploads your audio file to its server and processes it using its artificial intelligence algorithms. It then downloads the processed file back to your device.

    -
  7. How much does X-Minus Pro Vocal Remover cost?
  8. -

    X-Minus Pro Vocal Remover offers three pricing plans: pay per track ($0.99 per track), pay per month ($9.99 per month for unlimited tracks), or pay per year ($99.99 per year for unlimited tracks). You can choose the plan that suits your budget and needs.

    -
  9. How can I contact X-Minus Pro Vocal Remover support?
  10. -

    If you have any questions or issues with X-Minus Pro Vocal Remover, you can contact its support team by email at support@x-minus.pro or by phone at +1 (800) 123-4567.

    -

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Download Utorrent For Mac Softonic How to Enjoy Torrenting on Your Mac with Ease.md b/spaces/contluForse/HuggingGPT/assets/Download Utorrent For Mac Softonic How to Enjoy Torrenting on Your Mac with Ease.md deleted file mode 100644 index 1977ad4bcf21a700b5a4a79f53de6f36754507ba..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Download Utorrent For Mac Softonic How to Enjoy Torrenting on Your Mac with Ease.md +++ /dev/null @@ -1,26 +0,0 @@ - -

Torrent sharing consists of sharing large files, like movies, software, or games with other peers. The file you want to download is cut up into small segments shared by users, creating what is called a swarm, and does not go through a central server, significantly reducing the bulk of file transfers. The Bittorrent client was actually the first P2P application to use this technology and became immensely popular when it was released.

-

Download Utorrent For Mac Softonic


Download ★★★★★ https://ssurll.com/2uzxbG



-

qBittorrent has other interesting features such as support for tags to organize your files, the ability to switch off the computer once the downloads are finished and a Web interface that lets you manage your downloads remotely.

-

This new version doesn't support OS X 10.4.11 anymore (although you can download the 10.4.11 version here) but brings many more improvements to an already solid release. You can set different priority levels for torrents and establish stall limit times. Transmission's speed limit mode, represented by a turtle icon at the bottom of the interface, is extremely useful if you're looking to control the amount of bandwidth you use for uploads and downloads. The option for anonymous connections has been removed in this latest version however.

-

Transmission has consistently improved over time, offering many more options to view your torrents. You can now filter your torrent list according to downloading, seeding, or paused. The client can also organize transfers by queue order, date added, name, process. Transmission also allows you to label, filter and sort torrents by groups and total activity. You can also encrypt your torrent activity in case you want it to stay private.

-

Fixes a crash that prevented Transmission from opening on non-English systems. Auto-grouping won't apply until torrents are demagnetized Tweak the inspector's and add window's file lists to avoid auto-hiding scrollbars overlapping the priority controls Fix potential crash when downloading and seeding complete at the same time Fix bug where stopped torrents might start when waking the computer from sleep Fix a bug that prevented IPv6 addresses from being saved in dht.dat Better handling of magnet links that contain 'tr.x=' parameters Add filtering of addresses used for uTP peer connections Fix detection of whether or not a peer supports uTP connectionsWeb Client: Fix a multi-file selection bug Fix bug where the upload and download arrows and rates would not appear for downloading torrents Fix bug when displaying the tracker list

-

Paid for no ads. Had very hard time even downloading utorrent, but finally could on softonic link. But i cannot upgrade to no ads. My reader cannot open file with personal license key.. says it either does not support that kind of file or file code was somehow not done right in email. Is there special program i need to open this file? Requesting that the actual license key be mailed to me.

-

-

Also, apparently what i downloaded is older version of utorrent. But am afraid to uninstall and try downloading. Every link wxcept softonic gave me page saying you refused connection. Including the ones in my purchase email. Only installed last night. But now it will not let me do anything, saying i need newer version. What is a working link that will not refuse connection? Am VERY frustrated !

-

The eMule program allows Mac users to share files with each other. The system works by creating a location where the files are shared and numerous people may upload at the same time. The benefit is that the users sharing may receive faster downloads. The more popular a file is, then the quicker and more efficiently it is shared.

-

Some people have a program that allows them to share files using torrents. This system has its own way of sharing files, and it will accept torrents, meaning eMule users have an advantage over people that just have Bittorrent or Utorrent because Mac users may also share in more than one way. The program itself is very easy to download and use. The program is being updated fairly frequently, which is why the auto-update feature is rather handy. The quick-search function is a great timesaver, and the eMule servers seem to have improved over the years.

-

MediaGet has been designed with simplicity in mind. A quick drop-down search engine allows users to filter their results by the title of the file (such as a film). There is also a manual search based off of keywords or partial phrases. This "smart search" option identifies quality sites as well as those which should be avoided (such as portals associated with malware). Therefore, this system provides an additional layer of security before the download even begins.

-

MediaGet has been recognised as a safe product by Norton Antivirus and Nano Antivirus. Furthermore, there is an option to download this program for Android-powered devices such as mobile phones and tablets. Finally, it is also possible to transfer files from an Android device to an iOS system (including an Apple smart television).

-

On Apple devices, company leaders have criticized the Flash format, saying that the main reason for Macs to crash was Flash. Adobe Flash Player can still be used on Firefox, Chrome, and Opera on Macs. On Mac, Adobe Flash Player uses a lot of CPU resources, leading to the system crashing or slowing down. iOS devices are already not compatible with Adobe Flash Player, though it can be downloaded as a plug-in on Safari. Some alternatives to the program are VLC Media Player, HTML5, Shockwave Player, Microsoft Silverlight, and more.

-

Adobe Flash Player is a multimedia player that plays the SWF and is in-built in most browsers. Flash Player for Mac is compatible with Firefox, Chrome, and Opera. While the program takes low network bandwidth and the websites with flash animations load faster on Mac devices, the program takes up a lot of CPU resources. This, in turn, causes crashes or slows down the system. Also, there have been a number of security issues with Flash Player, which makes it susceptible to privacy breaches. Overall, it may not be the best download choice.

-

App Advisor+, powered by Norton Mobile Insight, scans apps before you download them and warns you about risky apps before you install them. App Advisor+ for Google Play tells you about malware, online privacy and other risks that are detected for a given app before you choose to download it.

-

A computer, tablet or smartphone that connects to the Internet has the potential to encounter viruses and malware. While you may be careful what you do online, you could still visit a website that has been compromised with malware (without even knowing it) or download malware from a message from a trusted friend whose account was hacked. Someone else who uses your device might not be as careful as you. Having antivirus and security software for your computer or mobile device gives you protection against many types of malware that might not be easy to spot.

-

Através dele, você pode efetuar download de qualquer arquivo que deseja com velocidade e estabilidade garantidas. Porém, caso esteja procurando por alguma alternativa semelhante, de qualidade parecida, recomendamos que você baixe o BitTorrent ou o Vuze.

-

O programa possui tudo o que se espera de um downloader de torrent confiável e completo: agendador de download e estatísticas quanto aos arquivos constantes (tempo para baixar, número de seeders e leechers, etc). Entretanto, há algumas coisas em falta: precisaria de uma ferramenta de pesquisa mais completa, além de um player embutido, onde fosse possível pré-visualizar seus arquivos dos quais está sendo feito o download.

-

O programa possui um processo bem rápido de instalação e um teste de velocidade integrado bem prático de se fazer, de forma que a configuração inicial se torna muito fácil de ser feita. Ocupando um mínimo de recursos do PC, permite que seja feito o download de uma boa quantidade de arquivos, sem que o computador fique afetado para outros usos simultâneos.

-

Caso esteja procurando por um programa de download de torrent rápido, confiável e leve, pode parar sua procura: uTorrent é mais do que o necessário para você. Com uma interface simples e intuitiva, funciona até mesmo para quem não conhece o universo do torrent.

-

In exceptional cases, it can be useful to install an older version. For this purpose, previous installers can be downloaded using the links below. These files are not available in the Steinberg Download Assistant anymore.

-

uTorrent is a leading BitTorrent client preferred around the world for downloading music, movies, and other content. A popular P2P file sharing platform, this torrent software is lightweight, easy to use, fast, and efficient. Most importantly, since uTorrent download is available for Windows, Mac, and Android, it offers cross-platform synchronisation. uTorrent comes with all the features of a reliable, stable, and complete torrent download option. Some of these features include support for RSS feeds, detailed file information, a download scheduler, automatic shutdown, and more. Unfortunately, the programme lacks a built-in media player and comprehensive search functionality.

aaccfb2cb3
-
-
\ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Download video klip film india mohabbatein The love stories of 6 young actors who made their debut in this film.md b/spaces/contluForse/HuggingGPT/assets/Download video klip film india mohabbatein The love stories of 6 young actors who made their debut in this film.md deleted file mode 100644 index d5b7ebc482dded396641be4e5f99152de2983056..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Download video klip film india mohabbatein The love stories of 6 young actors who made their debut in this film.md +++ /dev/null @@ -1,6 +0,0 @@ -

download video klip film india mohabbatein


DOWNLOAD ✪✪✪ https://ssurll.com/2uzwyw



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/datasets/stare.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/datasets/stare.py deleted file mode 100644 index cbd14e0920e7f6a73baff1432e5a32ccfdb0dfae..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/datasets/stare.py +++ /dev/null @@ -1,27 +0,0 @@ -import os.path as osp - -from .builder import DATASETS -from .custom import CustomDataset - - -@DATASETS.register_module() -class STAREDataset(CustomDataset): - """STARE dataset. - - In segmentation map annotation for STARE, 0 stands for background, which is - included in 2 categories. ``reduce_zero_label`` is fixed to False. The - ``img_suffix`` is fixed to '.png' and ``seg_map_suffix`` is fixed to - '.ah.png'. - """ - - CLASSES = ('background', 'vessel') - - PALETTE = [[120, 120, 120], [6, 230, 230]] - - def __init__(self, **kwargs): - super(STAREDataset, self).__init__( - img_suffix='.png', - seg_map_suffix='.ah.png', - reduce_zero_label=False, - **kwargs) - assert osp.exists(self.img_dir) diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/models/decode_heads/da_head.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/models/decode_heads/da_head.py deleted file mode 100644 index 5cd49fcfdc7c0a70f9485cc71843dcf3e0cb1774..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/models/decode_heads/da_head.py +++ /dev/null @@ -1,178 +0,0 @@ -import torch -import torch.nn.functional as F -from annotator.uniformer.mmcv.cnn import ConvModule, Scale -from torch import nn - -from annotator.uniformer.mmseg.core import add_prefix -from ..builder import HEADS -from ..utils import SelfAttentionBlock as _SelfAttentionBlock -from .decode_head import BaseDecodeHead - - -class PAM(_SelfAttentionBlock): - """Position Attention Module (PAM) - - Args: - in_channels (int): Input channels of key/query feature. - channels (int): Output channels of key/query transform. - """ - - def __init__(self, in_channels, channels): - super(PAM, self).__init__( - key_in_channels=in_channels, - query_in_channels=in_channels, - channels=channels, - out_channels=in_channels, - share_key_query=False, - query_downsample=None, - key_downsample=None, - key_query_num_convs=1, - key_query_norm=False, - value_out_num_convs=1, - value_out_norm=False, - matmul_norm=False, - with_out=False, - conv_cfg=None, - norm_cfg=None, - act_cfg=None) - - self.gamma = Scale(0) - - def forward(self, x): - """Forward function.""" - out = super(PAM, self).forward(x, x) - - out = self.gamma(out) + x - return out - - -class CAM(nn.Module): - """Channel Attention Module (CAM)""" - - def __init__(self): - super(CAM, self).__init__() - self.gamma = Scale(0) - - def forward(self, x): - """Forward function.""" - batch_size, channels, height, width = x.size() - proj_query = x.view(batch_size, channels, -1) - proj_key = x.view(batch_size, channels, -1).permute(0, 2, 1) - energy = torch.bmm(proj_query, proj_key) - energy_new = torch.max( - energy, -1, keepdim=True)[0].expand_as(energy) - energy - attention = F.softmax(energy_new, dim=-1) - proj_value = x.view(batch_size, channels, -1) - - out = torch.bmm(attention, proj_value) - out = out.view(batch_size, channels, height, width) - - out = self.gamma(out) + x - return out - - -@HEADS.register_module() -class DAHead(BaseDecodeHead): - """Dual Attention Network for Scene Segmentation. - - This head is the implementation of `DANet - `_. - - Args: - pam_channels (int): The channels of Position Attention Module(PAM). - """ - - def __init__(self, pam_channels, **kwargs): - super(DAHead, self).__init__(**kwargs) - self.pam_channels = pam_channels - self.pam_in_conv = ConvModule( - self.in_channels, - self.channels, - 3, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - self.pam = PAM(self.channels, pam_channels) - self.pam_out_conv = ConvModule( - self.channels, - self.channels, - 3, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - self.pam_conv_seg = nn.Conv2d( - self.channels, self.num_classes, kernel_size=1) - - self.cam_in_conv = ConvModule( - self.in_channels, - self.channels, - 3, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - self.cam = CAM() - self.cam_out_conv = ConvModule( - self.channels, - self.channels, - 3, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - self.cam_conv_seg = nn.Conv2d( - self.channels, self.num_classes, kernel_size=1) - - def pam_cls_seg(self, feat): - """PAM feature classification.""" - if self.dropout is not None: - feat = self.dropout(feat) - output = self.pam_conv_seg(feat) - return output - - def cam_cls_seg(self, feat): - """CAM feature classification.""" - if self.dropout is not None: - feat = self.dropout(feat) - output = self.cam_conv_seg(feat) - return output - - def forward(self, inputs): - """Forward function.""" - x = self._transform_inputs(inputs) - pam_feat = self.pam_in_conv(x) - pam_feat = self.pam(pam_feat) - pam_feat = self.pam_out_conv(pam_feat) - pam_out = self.pam_cls_seg(pam_feat) - - cam_feat = self.cam_in_conv(x) - cam_feat = self.cam(cam_feat) - cam_feat = self.cam_out_conv(cam_feat) - cam_out = self.cam_cls_seg(cam_feat) - - feat_sum = pam_feat + cam_feat - pam_cam_out = self.cls_seg(feat_sum) - - return pam_cam_out, pam_out, cam_out - - def forward_test(self, inputs, img_metas, test_cfg): - """Forward function for testing, only ``pam_cam`` is used.""" - return self.forward(inputs)[0] - - def losses(self, seg_logit, seg_label): - """Compute ``pam_cam``, ``pam``, ``cam`` loss.""" - pam_cam_seg_logit, pam_seg_logit, cam_seg_logit = seg_logit - loss = dict() - loss.update( - add_prefix( - super(DAHead, self).losses(pam_cam_seg_logit, seg_label), - 'pam_cam')) - loss.update( - add_prefix( - super(DAHead, self).losses(pam_seg_logit, seg_label), 'pam')) - loss.update( - add_prefix( - super(DAHead, self).losses(cam_seg_logit, seg_label), 'cam')) - return loss diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/models/utils/up_conv_block.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/models/utils/up_conv_block.py deleted file mode 100644 index 378469da76cb7bff6a639e7877b3c275d50490fb..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/uniformer/mmseg/models/utils/up_conv_block.py +++ /dev/null @@ -1,101 +0,0 @@ -import torch -import torch.nn as nn -from annotator.uniformer.mmcv.cnn import ConvModule, build_upsample_layer - - -class UpConvBlock(nn.Module): - """Upsample convolution block in decoder for UNet. - - This upsample convolution block consists of one upsample module - followed by one convolution block. The upsample module expands the - high-level low-resolution feature map and the convolution block fuses - the upsampled high-level low-resolution feature map and the low-level - high-resolution feature map from encoder. - - Args: - conv_block (nn.Sequential): Sequential of convolutional layers. - in_channels (int): Number of input channels of the high-level - skip_channels (int): Number of input channels of the low-level - high-resolution feature map from encoder. - out_channels (int): Number of output channels. - num_convs (int): Number of convolutional layers in the conv_block. - Default: 2. - stride (int): Stride of convolutional layer in conv_block. Default: 1. - dilation (int): Dilation rate of convolutional layer in conv_block. - Default: 1. - with_cp (bool): Use checkpoint or not. Using checkpoint will save some - memory while slowing down the training speed. Default: False. - conv_cfg (dict | None): Config dict for convolution layer. - Default: None. - norm_cfg (dict | None): Config dict for normalization layer. - Default: dict(type='BN'). - act_cfg (dict | None): Config dict for activation layer in ConvModule. - Default: dict(type='ReLU'). - upsample_cfg (dict): The upsample config of the upsample module in - decoder. Default: dict(type='InterpConv'). If the size of - high-level feature map is the same as that of skip feature map - (low-level feature map from encoder), it does not need upsample the - high-level feature map and the upsample_cfg is None. - dcn (bool): Use deformable convolution in convolutional layer or not. - Default: None. - plugins (dict): plugins for convolutional layers. Default: None. - """ - - def __init__(self, - conv_block, - in_channels, - skip_channels, - out_channels, - num_convs=2, - stride=1, - dilation=1, - with_cp=False, - conv_cfg=None, - norm_cfg=dict(type='BN'), - act_cfg=dict(type='ReLU'), - upsample_cfg=dict(type='InterpConv'), - dcn=None, - plugins=None): - super(UpConvBlock, self).__init__() - assert dcn is None, 'Not implemented yet.' - assert plugins is None, 'Not implemented yet.' - - self.conv_block = conv_block( - in_channels=2 * skip_channels, - out_channels=out_channels, - num_convs=num_convs, - stride=stride, - dilation=dilation, - with_cp=with_cp, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg, - dcn=None, - plugins=None) - if upsample_cfg is not None: - self.upsample = build_upsample_layer( - cfg=upsample_cfg, - in_channels=in_channels, - out_channels=skip_channels, - with_cp=with_cp, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - else: - self.upsample = ConvModule( - in_channels, - skip_channels, - kernel_size=1, - stride=1, - padding=0, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - - def forward(self, skip, x): - """Forward function.""" - - x = self.upsample(x) - out = torch.cat([skip, x], dim=1) - out = self.conv_block(out) - - return out diff --git a/spaces/crashedice/signify/SOURCE/yolo_files/detect.py b/spaces/crashedice/signify/SOURCE/yolo_files/detect.py deleted file mode 100644 index 39225e06f8e0f92ef495b1c223bf9dfa65afc4c2..0000000000000000000000000000000000000000 --- a/spaces/crashedice/signify/SOURCE/yolo_files/detect.py +++ /dev/null @@ -1,184 +0,0 @@ -import argparse -import time -from pathlib import Path - -import cv2 -import torch -import torch.backends.cudnn as cudnn -from numpy import random -from SOURCE.yolo_files.models.experimental import attempt_load -from SOURCE.yolo_files.utils.datasets import LoadImages, LoadStreams -from SOURCE.yolo_files.utils.general import (apply_classifier, check_img_size, - check_imshow, check_requirements, - increment_path, - non_max_suppression, save_one_box, - scale_coords, set_logging, - strip_optimizer, xyxy2xywh) -from SOURCE.yolo_files.utils.plots import colors, plot_one_box -from SOURCE.yolo_files.utils.torch_utils import (load_classifier, - select_device, - time_synchronized) - - -def detect(image_path): - opt = { - 'weights': 'SOURCE/yolo_files/best.pt', - 'source': image_path, - 'img_size': 640, - 'conf_thres': 0.25, - 'iou_thres': 0.45, - 'device': '', - 'view_img': False, - 'save_txt': True, - 'save_conf': True, - 'save_crop': True, - 'nosave': True, - 'classes': 1, - 'agnostic_nms': False, - 'augment': False, - 'update': False, - 'project': 'results/yolov5/', - 'name': 'exp', - 'exist_ok': False, - 'line_thickness': 3, - 'hide_labels': False, - 'hide_conf': False, - -} - - - source, weights, view_img, save_txt, imgsz = opt['source'], opt['weights'], opt['view_img'], opt['save_txt'], opt['img_size'] - save_img = not opt['nosave'] and not source.endswith('.txt') # save inference images - webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( - ('rtsp://', 'rtmp://', 'http://', 'https://')) - - # Directories - save_dir = increment_path(Path(opt['project']) / opt['name'], exist_ok=opt['exist_ok']) # increment run - (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir - - # Initialize - set_logging() - device = select_device(opt['device']) - half = device.type != 'cpu' # half precision only supported on CUDA - - # Load model - model = attempt_load(weights, map_location=device) # load FP32 model - stride = int(model.stride.max()) # model stride - imgsz = check_img_size(imgsz, s=stride) # check img_size - names = model.module.names if hasattr(model, 'module') else model.names # get class names - if half: - model.half() # to FP16 - - for m in model.modules(): - if isinstance(m, torch.nn.Upsample): - m.recompute_scale_factor = None - - - # Second-stage classifier - classify = False - if classify: - modelc = load_classifier(name='resnet101', n=2) # initialize - modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval() - - # Set Dataloader - vid_path, vid_writer = None, None - if webcam: - view_img = check_imshow() - cudnn.benchmark = True # set True to speed up constant image size inference - dataset = LoadStreams(source, img_size=imgsz, stride=stride) - else: - dataset = LoadImages(source, img_size=imgsz, stride=stride) - - # Run inference - if device.type != 'cpu': - model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once - t0 = time.time() - for path, img, im0s, vid_cap in dataset: - img = torch.from_numpy(img).to(device) - img = img.half() if half else img.float() # uint8 to fp16/32 - img /= 255.0 # 0 - 255 to 0.0 - 1.0 - if img.ndimension() == 3: - img = img.unsqueeze(0) - - # Inference - t1 = time_synchronized() - pred = model(img, augment=opt['augment'])[0] - - # Apply NMS - pred = non_max_suppression(pred, opt['conf_thres'], opt['iou_thres'], classes=opt['classes'], agnostic=opt['agnostic_nms']) - t2 = time_synchronized() - - # Apply Classifier - if classify: - pred = apply_classifier(pred, modelc, img, im0s) - - # Process detections - for i, det in enumerate(pred): # detections per image - if webcam: # batch_size >= 1 - p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count - else: - p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0) - - p = Path(p) # to Path - save_path = str(save_dir / p.name) # img.jpg - txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt - s += '%gx%g ' % img.shape[2:] # print string - gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh - if len(det): - # Rescale boxes from img_size to im0 size - det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() - - # Print results - for c in det[:, -1].unique(): - n = (det[:, -1] == c).sum() # detections per class - s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string - - # Write results - for *xyxy, conf, cls in reversed(det): - if save_txt: # Write to file - xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh - line = (cls, *xywh, conf) if opt['save_conf'] else (cls, *xywh) # label format - with open(txt_path + '.txt', 'a') as f: - f.write(('%g ' * len(line)).rstrip() % line + '\n') - - if save_img or opt['save_crop'] or view_img: # Add bbox to image - c = int(cls) # integer class - label = None if opt['hide_labels'] else (names[c] if opt['hide_conf'] else f'{names[c]} {conf:.2f}') - - plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=opt['line_thickness']) - if opt['save_crop']: - save_one_box(xyxy, im0s, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) - - # Print time (inference + NMS) - print(f'{s}Done. ({t2 - t1:.3f}s)') - - # Stream results - if view_img: - cv2.imshow(str(p), im0) - cv2.waitKey(1) # 1 millisecond - - # Save results (image with detections) - if save_img: - if dataset.mode == 'image': - cv2.imwrite(save_path, im0) - else: # 'video' or 'stream' - if vid_path != save_path: # new video - vid_path = save_path - if isinstance(vid_writer, cv2.VideoWriter): - vid_writer.release() # release previous video writer - if vid_cap: # video - fps = vid_cap.get(cv2.CAP_PROP_FPS) - w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) - else: # stream - fps, w, h = 30, im0.shape[1], im0.shape[0] - save_path += '.mp4' - vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) - vid_writer.write(im0) - - if save_txt or save_img: - s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' - print(f"Results saved to {save_dir}{s}") - - print(f'Done. ({time.time() - t0:.3f}s)') - return 'Success' diff --git a/spaces/crashedice/signify/signify/gan/models/cycle_gan_model.py b/spaces/crashedice/signify/signify/gan/models/cycle_gan_model.py deleted file mode 100644 index d31c5e70ef17863fff63160f57abe148271553c9..0000000000000000000000000000000000000000 --- a/spaces/crashedice/signify/signify/gan/models/cycle_gan_model.py +++ /dev/null @@ -1,194 +0,0 @@ -import torch -import itertools -from util.image_pool import ImagePool -from signify.gan.models.base_model import BaseModel -from signify.gan.models import networks - - -class CycleGANModel(BaseModel): - """ - This class implements the CycleGAN model, for learning image-to-image translation without paired data. - - The model training requires '--dataset_mode unaligned' dataset. - By default, it uses a '--netG resnet_9blocks' ResNet generator, - a '--netD basic' discriminator (PatchGAN introduced by pix2pix), - and a least-square GANs objective ('--gan_mode lsgan'). - - CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf - """ - @staticmethod - def modify_commandline_options(parser, is_train=True): - """Add new dataset-specific options, and rewrite default values for existing options. - - Parameters: - parser -- original option parser - is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. - - Returns: - the modified parser. - - For CycleGAN, in addition to GAN losses, we introduce lambda_A, lambda_B, and lambda_identity for the following losses. - A (source domain), B (target domain). - Generators: G_A: A -> B; G_B: B -> A. - Discriminators: D_A: G_A(A) vs. B; D_B: G_B(B) vs. A. - Forward cycle loss: lambda_A * ||G_B(G_A(A)) - A|| (Eqn. (2) in the paper) - Backward cycle loss: lambda_B * ||G_A(G_B(B)) - B|| (Eqn. (2) in the paper) - Identity loss (optional): lambda_identity * (||G_A(B) - B|| * lambda_B + ||G_B(A) - A|| * lambda_A) (Sec 5.2 "Photo generation from paintings" in the paper) - Dropout is not used in the original CycleGAN paper. - """ - parser.set_defaults(no_dropout=True) # default CycleGAN did not use dropout - if is_train: - parser.add_argument('--lambda_A', type=float, default=10.0, help='weight for cycle loss (A -> B -> A)') - parser.add_argument('--lambda_B', type=float, default=10.0, help='weight for cycle loss (B -> A -> B)') - parser.add_argument('--lambda_identity', type=float, default=0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1') - - return parser - - def __init__(self, opt): - """Initialize the CycleGAN class. - - Parameters: - opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions - """ - BaseModel.__init__(self, opt) - # specify the training losses you want to print out. The training/test scripts will call - self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B'] - # specify the images you want to save/display. The training/test scripts will call - visual_names_A = ['real_A', 'fake_B', 'rec_A'] - visual_names_B = ['real_B', 'fake_A', 'rec_B'] - if self.isTrain and self.opt.lambda_identity > 0.0: # if identity loss is used, we also visualize idt_B=G_A(B) ad idt_A=G_A(B) - visual_names_A.append('idt_B') - visual_names_B.append('idt_A') - - self.visual_names = visual_names_A + visual_names_B # combine visualizations for A and B - # specify the models you want to save to the disk. The training/test scripts will call and . - if self.isTrain: - self.model_names = ['G_A', 'G_B', 'D_A', 'D_B'] - else: # during test time, only load Gs - self.model_names = ['G_A', 'G_B'] - - # define networks (both Generators and discriminators) - # The naming is different from those used in the paper. - # Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X) - self.netG_A = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm, - not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids) - self.netG_B = networks.define_G(opt.output_nc, opt.input_nc, opt.ngf, opt.netG, opt.norm, - not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids) - - if self.isTrain: # define discriminators - self.netD_A = networks.define_D(opt.output_nc, opt.ndf, opt.netD, - opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids) - self.netD_B = networks.define_D(opt.input_nc, opt.ndf, opt.netD, - opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids) - - if self.isTrain: - if opt.lambda_identity > 0.0: # only works when input and output images have the same number of channels - assert(opt.input_nc == opt.output_nc) - self.fake_A_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images - self.fake_B_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images - # define loss functions - self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device) # define GAN loss. - self.criterionCycle = torch.nn.L1Loss() - self.criterionIdt = torch.nn.L1Loss() - # initialize optimizers; schedulers will be automatically created by function . - self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999)) - self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(), self.netD_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999)) - self.optimizers.append(self.optimizer_G) - self.optimizers.append(self.optimizer_D) - - def set_input(self, input): - """Unpack input data from the dataloader and perform necessary pre-processing steps. - - Parameters: - input (dict): include the data itself and its metadata information. - - The option 'direction' can be used to swap domain A and domain B. - """ - AtoB = self.opt.direction == 'AtoB' - self.real_A = input['A' if AtoB else 'B'].to(self.device) - self.real_B = input['B' if AtoB else 'A'].to(self.device) - self.image_paths = input['A_paths' if AtoB else 'B_paths'] - - def forward(self): - """Run forward pass; called by both functions and .""" - self.fake_B = self.netG_A(self.real_A) # G_A(A) - self.rec_A = self.netG_B(self.fake_B) # G_B(G_A(A)) - self.fake_A = self.netG_B(self.real_B) # G_B(B) - self.rec_B = self.netG_A(self.fake_A) # G_A(G_B(B)) - - def backward_D_basic(self, netD, real, fake): - """Calculate GAN loss for the discriminator - - Parameters: - netD (network) -- the discriminator D - real (tensor array) -- real images - fake (tensor array) -- images generated by a generator - - Return the discriminator loss. - We also call loss_D.backward() to calculate the gradients. - """ - # Real - pred_real = netD(real) - loss_D_real = self.criterionGAN(pred_real, True) - # Fake - pred_fake = netD(fake.detach()) - loss_D_fake = self.criterionGAN(pred_fake, False) - # Combined loss and calculate gradients - loss_D = (loss_D_real + loss_D_fake) * 0.5 - loss_D.backward() - return loss_D - - def backward_D_A(self): - """Calculate GAN loss for discriminator D_A""" - fake_B = self.fake_B_pool.query(self.fake_B) - self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_B, fake_B) - - def backward_D_B(self): - """Calculate GAN loss for discriminator D_B""" - fake_A = self.fake_A_pool.query(self.fake_A) - self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_A, fake_A) - - def backward_G(self): - """Calculate the loss for generators G_A and G_B""" - lambda_idt = self.opt.lambda_identity - lambda_A = self.opt.lambda_A - lambda_B = self.opt.lambda_B - # Identity loss - if lambda_idt > 0: - # G_A should be identity if real_B is fed: ||G_A(B) - B|| - self.idt_A = self.netG_A(self.real_B) - self.loss_idt_A = self.criterionIdt(self.idt_A, self.real_B) * lambda_B * lambda_idt - # G_B should be identity if real_A is fed: ||G_B(A) - A|| - self.idt_B = self.netG_B(self.real_A) - self.loss_idt_B = self.criterionIdt(self.idt_B, self.real_A) * lambda_A * lambda_idt - else: - self.loss_idt_A = 0 - self.loss_idt_B = 0 - - # GAN loss D_A(G_A(A)) - self.loss_G_A = self.criterionGAN(self.netD_A(self.fake_B), True) - # GAN loss D_B(G_B(B)) - self.loss_G_B = self.criterionGAN(self.netD_B(self.fake_A), True) - # Forward cycle loss || G_B(G_A(A)) - A|| - self.loss_cycle_A = self.criterionCycle(self.rec_A, self.real_A) * lambda_A - # Backward cycle loss || G_A(G_B(B)) - B|| - self.loss_cycle_B = self.criterionCycle(self.rec_B, self.real_B) * lambda_B - # combined loss and calculate gradients - self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + self.loss_idt_B - self.loss_G.backward() - - def optimize_parameters(self): - """Calculate losses, gradients, and update network weights; called in every training iteration""" - # forward - self.forward() # compute fake images and reconstruction images. - # G_A and G_B - self.set_requires_grad([self.netD_A, self.netD_B], False) # Ds require no gradients when optimizing Gs - self.optimizer_G.zero_grad() # set G_A and G_B's gradients to zero - self.backward_G() # calculate gradients for G_A and G_B - self.optimizer_G.step() # update G_A and G_B's weights - # D_A and D_B - self.set_requires_grad([self.netD_A, self.netD_B], True) - self.optimizer_D.zero_grad() # set D_A and D_B's gradients to zero - self.backward_D_A() # calculate gradients for D_A - self.backward_D_B() # calculate graidents for D_B - self.optimizer_D.step() # update D_A and D_B's weights diff --git a/spaces/cscan/CodeFormer/CodeFormer/basicsr/ops/fused_act/fused_act.py b/spaces/cscan/CodeFormer/CodeFormer/basicsr/ops/fused_act/fused_act.py deleted file mode 100644 index 588f815e596ab0fc83ab0f9d21426c22ec5ed7c3..0000000000000000000000000000000000000000 --- a/spaces/cscan/CodeFormer/CodeFormer/basicsr/ops/fused_act/fused_act.py +++ /dev/null @@ -1,89 +0,0 @@ -# modify from https://github.com/rosinality/stylegan2-pytorch/blob/master/op/fused_act.py # noqa:E501 - -import torch -from torch import nn -from torch.autograd import Function - -try: - from . import fused_act_ext -except ImportError: - import os - BASICSR_JIT = os.getenv('BASICSR_JIT') - if BASICSR_JIT == 'True': - from torch.utils.cpp_extension import load - module_path = os.path.dirname(__file__) - fused_act_ext = load( - 'fused', - sources=[ - os.path.join(module_path, 'src', 'fused_bias_act.cpp'), - os.path.join(module_path, 'src', 'fused_bias_act_kernel.cu'), - ], - ) - - -class FusedLeakyReLUFunctionBackward(Function): - - @staticmethod - def forward(ctx, grad_output, out, negative_slope, scale): - ctx.save_for_backward(out) - ctx.negative_slope = negative_slope - ctx.scale = scale - - empty = grad_output.new_empty(0) - - grad_input = fused_act_ext.fused_bias_act(grad_output, empty, out, 3, 1, negative_slope, scale) - - dim = [0] - - if grad_input.ndim > 2: - dim += list(range(2, grad_input.ndim)) - - grad_bias = grad_input.sum(dim).detach() - - return grad_input, grad_bias - - @staticmethod - def backward(ctx, gradgrad_input, gradgrad_bias): - out, = ctx.saved_tensors - gradgrad_out = fused_act_ext.fused_bias_act(gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, - ctx.scale) - - return gradgrad_out, None, None, None - - -class FusedLeakyReLUFunction(Function): - - @staticmethod - def forward(ctx, input, bias, negative_slope, scale): - empty = input.new_empty(0) - out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) - ctx.save_for_backward(out) - ctx.negative_slope = negative_slope - ctx.scale = scale - - return out - - @staticmethod - def backward(ctx, grad_output): - out, = ctx.saved_tensors - - grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply(grad_output, out, ctx.negative_slope, ctx.scale) - - return grad_input, grad_bias, None, None - - -class FusedLeakyReLU(nn.Module): - - def __init__(self, channel, negative_slope=0.2, scale=2**0.5): - super().__init__() - - self.bias = nn.Parameter(torch.zeros(channel)) - self.negative_slope = negative_slope - self.scale = scale - - def forward(self, input): - return fused_leaky_relu(input, self.bias, self.negative_slope, self.scale) - - -def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2**0.5): - return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) diff --git a/spaces/csuhan/opendet2/opendet2/modeling/layers/mlp.py b/spaces/csuhan/opendet2/opendet2/modeling/layers/mlp.py deleted file mode 100644 index aa714d0a9ce96eb8523f3cd378604e26b361f127..0000000000000000000000000000000000000000 --- a/spaces/csuhan/opendet2/opendet2/modeling/layers/mlp.py +++ /dev/null @@ -1,46 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F -import fvcore.nn.weight_init as weight_init - - -class MLP(nn.Module): - def __init__(self, in_dim, out_dim, hidden_dim=None): - super().__init__() - if not hidden_dim: - hidden_dim = in_dim - self.head = nn.Sequential( - nn.Linear(in_dim, hidden_dim), - nn.ReLU(inplace=True), - nn.Linear(hidden_dim, out_dim), - ) - for layer in self.head: - if isinstance(layer, nn.Linear): - weight_init.c2_xavier_fill(layer) - - def forward(self, x): - feat = self.head(x) - feat_norm = F.normalize(feat, dim=1) - return feat_norm - - -class ConvMLP(nn.Module): - def __init__(self, in_dim, out_dim, hidden_dim=None): - super().__init__() - if not hidden_dim: - hidden_dim = in_dim - self.head = nn.Sequential( - nn.Conv2d(in_dim, hidden_dim, kernel_size=3, stride=1, padding=1), - nn.ReLU(inplace=True), - nn.Conv2d(hidden_dim, out_dim, kernel_size=3, stride=1, padding=1), - ) - # Initialization - for layer in self.head: - if isinstance(layer, nn.Conv2d): - torch.nn.init.normal_(layer.weight, mean=0, std=0.01) - torch.nn.init.constant_(layer.bias, 0) - - def forward(self, x): - feat = self.head(x) - feat_norm = F.normalize(feat, dim=1) - return feat_norm \ No newline at end of file diff --git a/spaces/cymic/Waifu_Diffusion_Webui/javascript/imageviewer.js b/spaces/cymic/Waifu_Diffusion_Webui/javascript/imageviewer.js deleted file mode 100644 index 3a0baac8c667e4fbb9fad73b3ada2ff6404278a7..0000000000000000000000000000000000000000 --- a/spaces/cymic/Waifu_Diffusion_Webui/javascript/imageviewer.js +++ /dev/null @@ -1,209 +0,0 @@ -// A full size 'lightbox' preview modal shown when left clicking on gallery previews - -function closeModal() { - gradioApp().getElementById("lightboxModal").style.display = "none"; -} - -function showModal(event) { - const source = event.target || event.srcElement; - const modalImage = gradioApp().getElementById("modalImage") - const lb = gradioApp().getElementById("lightboxModal") - modalImage.src = source.src - if (modalImage.style.display === 'none') { - lb.style.setProperty('background-image', 'url(' + source.src + ')'); - } - lb.style.display = "block"; - lb.focus() - event.stopPropagation() -} - -function negmod(n, m) { - return ((n % m) + m) % m; -} - -function modalImageSwitch(offset){ - var allgalleryButtons = gradioApp().querySelectorAll(".gallery-item.transition-all") - var galleryButtons = [] - allgalleryButtons.forEach(function(elem){ - if(elem.parentElement.offsetParent){ - galleryButtons.push(elem); - } - }) - - if(galleryButtons.length>1){ - var allcurrentButtons = gradioApp().querySelectorAll(".gallery-item.transition-all.\\!ring-2") - var currentButton = null - allcurrentButtons.forEach(function(elem){ - if(elem.parentElement.offsetParent){ - currentButton = elem; - } - }) - - var result = -1 - galleryButtons.forEach(function(v, i){ if(v==currentButton) { result = i } }) - - if(result != -1){ - nextButton = galleryButtons[negmod((result+offset),galleryButtons.length)] - nextButton.click() - const modalImage = gradioApp().getElementById("modalImage"); - const modal = gradioApp().getElementById("lightboxModal"); - modalImage.src = nextButton.children[0].src; - if (modalImage.style.display === 'none') { - modal.style.setProperty('background-image', `url(${modalImage.src})`) - } - setTimeout( function(){modal.focus()},10) - } - } -} - -function modalNextImage(event){ - modalImageSwitch(1) - event.stopPropagation() -} - -function modalPrevImage(event){ - modalImageSwitch(-1) - event.stopPropagation() -} - -function modalKeyHandler(event){ - switch (event.key) { - case "ArrowLeft": - modalPrevImage(event) - break; - case "ArrowRight": - modalNextImage(event) - break; - case "Escape": - closeModal(); - break; - } -} - -function showGalleryImage(){ - setTimeout(function() { - fullImg_preview = gradioApp().querySelectorAll('img.w-full.object-contain') - - if(fullImg_preview != null){ - fullImg_preview.forEach(function function_name(e) { - if(e && e.parentElement.tagName == 'DIV'){ - - e.style.cursor='pointer' - - e.addEventListener('click', function (evt) { - if(!opts.js_modal_lightbox) return; - modalZoomSet(gradioApp().getElementById('modalImage'), opts.js_modal_lightbox_initialy_zoomed) - showModal(evt) - },true); - } - }); - } - - }, 100); -} - -function modalZoomSet(modalImage, enable){ - if( enable ){ - modalImage.classList.add('modalImageFullscreen'); - } else{ - modalImage.classList.remove('modalImageFullscreen'); - } -} - -function modalZoomToggle(event){ - modalImage = gradioApp().getElementById("modalImage"); - modalZoomSet(modalImage, !modalImage.classList.contains('modalImageFullscreen')) - event.stopPropagation() -} - -function modalTileImageToggle(event){ - const modalImage = gradioApp().getElementById("modalImage"); - const modal = gradioApp().getElementById("lightboxModal"); - const isTiling = modalImage.style.display === 'none'; - if (isTiling) { - modalImage.style.display = 'block'; - modal.style.setProperty('background-image', 'none') - } else { - modalImage.style.display = 'none'; - modal.style.setProperty('background-image', `url(${modalImage.src})`) - } - - event.stopPropagation() -} - -function galleryImageHandler(e){ - if(e && e.parentElement.tagName == 'BUTTON'){ - e.onclick = showGalleryImage; - } -} - -onUiUpdate(function(){ - fullImg_preview = gradioApp().querySelectorAll('img.w-full') - if(fullImg_preview != null){ - fullImg_preview.forEach(galleryImageHandler); - } -}) - -document.addEventListener("DOMContentLoaded", function() { - const modalFragment = document.createDocumentFragment(); - const modal = document.createElement('div') - modal.onclick = closeModal; - modal.id = "lightboxModal"; - modal.tabIndex=0 - modal.addEventListener('keydown', modalKeyHandler, true) - - const modalControls = document.createElement('div') - modalControls.className = 'modalControls gradio-container'; - modal.append(modalControls); - - const modalZoom = document.createElement('span') - modalZoom.className = 'modalZoom cursor'; - modalZoom.innerHTML = '⤡' - modalZoom.addEventListener('click', modalZoomToggle, true) - modalZoom.title = "Toggle zoomed view"; - modalControls.appendChild(modalZoom) - - const modalTileImage = document.createElement('span') - modalTileImage.className = 'modalTileImage cursor'; - modalTileImage.innerHTML = '⊞' - modalTileImage.addEventListener('click', modalTileImageToggle, true) - modalTileImage.title = "Preview tiling"; - modalControls.appendChild(modalTileImage) - - const modalClose = document.createElement('span') - modalClose.className = 'modalClose cursor'; - modalClose.innerHTML = '×' - modalClose.onclick = closeModal; - modalClose.title = "Close image viewer"; - modalControls.appendChild(modalClose) - - const modalImage = document.createElement('img') - modalImage.id = 'modalImage'; - modalImage.onclick = closeModal; - modalImage.tabIndex=0 - modalImage.addEventListener('keydown', modalKeyHandler, true) - modal.appendChild(modalImage) - - const modalPrev = document.createElement('a') - modalPrev.className = 'modalPrev'; - modalPrev.innerHTML = '❮' - modalPrev.tabIndex=0 - modalPrev.addEventListener('click',modalPrevImage,true); - modalPrev.addEventListener('keydown', modalKeyHandler, true) - modal.appendChild(modalPrev) - - const modalNext = document.createElement('a') - modalNext.className = 'modalNext'; - modalNext.innerHTML = '❯' - modalNext.tabIndex=0 - modalNext.addEventListener('click',modalNextImage,true); - modalNext.addEventListener('keydown', modalKeyHandler, true) - - modal.appendChild(modalNext) - - - gradioApp().getRootNode().appendChild(modal) - - document.body.appendChild(modalFragment); - -}); diff --git a/spaces/daddyjin/TalkingFaceGeneration/FONT/sync_batchnorm/__init__.py b/spaces/daddyjin/TalkingFaceGeneration/FONT/sync_batchnorm/__init__.py deleted file mode 100644 index bc8709d92c610b36e0bcbd7da20c1eb41dc8cfcf..0000000000000000000000000000000000000000 --- a/spaces/daddyjin/TalkingFaceGeneration/FONT/sync_batchnorm/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# File : __init__.py -# Author : Jiayuan Mao -# Email : maojiayuan@gmail.com -# Date : 27/01/2018 -# -# This file is part of Synchronized-BatchNorm-PyTorch. -# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch -# Distributed under MIT License. - -from .batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d -from .replicate import DataParallelWithCallback, patch_replication_callback diff --git a/spaces/danushkhanna/Phishing_Domain_Detector/app.py b/spaces/danushkhanna/Phishing_Domain_Detector/app.py deleted file mode 100644 index b8ccaa737f4fe7e673dff0a6d608296fedba1e9a..0000000000000000000000000000000000000000 --- a/spaces/danushkhanna/Phishing_Domain_Detector/app.py +++ /dev/null @@ -1,60 +0,0 @@ -import streamlit as st -import pickle -import pandas as pd -from extract_features import ExtractFeatures - -@st.cache_resource -def get_model(): - """ - Loads the phishing URL detection model from a pickle file. - - This function reads and loads a pickled file containing the classifier. - - Returns: - object: The loaded phishing URL detection model. - - Note: - The model should be saved in a file named 'phishing_url_detector.pkl'. - XGBoost module must be installed before using the file. - """ - with open('phishing_url_detector.pkl', 'rb') as pickle_model: - phishing_url_detector = pickle.load(pickle_model) - return phishing_url_detector - -st.title("Phishing Website Detector") -st.header("Are you sure your 'bank' sent that link?") - -# Takes in user input -input_url = st.text_area("Put in your sus site link here: ") - -if input_url != "": - - # Extracts features from the URL and converts it into a dataframe - features_url = ExtractFeatures().url_to_features(url=input_url) - features_dataframe = pd.DataFrame.from_dict([features_url]) - features_dataframe = features_dataframe.fillna(-1) - features_dataframe = features_dataframe.astype(int) - - st.write("Okay!") - st.cache_data.clear() - prediction_str = "" - - # Predict outcome using extracted features - try: - phishing_url_detector = get_model() - prediction = phishing_url_detector.predict(features_dataframe) - if prediction == int(True): - prediction_str = 'Phishing Website. Do not click!' - elif prediction == int(False): - prediction_str = 'Not Phishing Website, stay safe!' - else: - prediction_str = '' - st.write(prediction_str) - st.write(features_dataframe) - - except Exception as e: - print(e) - st.error("Not sure, what went wrong. We'll get back to you shortly!") - -else: - st.write("") \ No newline at end of file diff --git a/spaces/dayachoudekar8/swalearn/app.py b/spaces/dayachoudekar8/swalearn/app.py deleted file mode 100644 index a4491fa68b763a8a344f905b856e79f8ff7aabf7..0000000000000000000000000000000000000000 --- a/spaces/dayachoudekar8/swalearn/app.py +++ /dev/null @@ -1,4 +0,0 @@ -import streamlit as st - -x = st.slider('Select a value') -st.write(x, 'squared is', x * x) \ No newline at end of file diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/otlLib/optimize/__init__.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/otlLib/optimize/__init__.py deleted file mode 100644 index 25bce9cd2cdaa51338c83b7ecb9059b592b5574f..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fontTools/otlLib/optimize/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -from argparse import RawTextHelpFormatter -from fontTools.otlLib.optimize.gpos import COMPRESSION_LEVEL, compact -from fontTools.ttLib import TTFont - - -def main(args=None): - """Optimize the layout tables of an existing font""" - from argparse import ArgumentParser - - from fontTools import configLogger - - parser = ArgumentParser( - prog="otlLib.optimize", - description=main.__doc__, - formatter_class=RawTextHelpFormatter, - ) - parser.add_argument("font") - parser.add_argument( - "-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file" - ) - parser.add_argument( - "--gpos-compression-level", - help=COMPRESSION_LEVEL.help, - default=COMPRESSION_LEVEL.default, - choices=list(range(10)), - type=int, - ) - logging_group = parser.add_mutually_exclusive_group(required=False) - logging_group.add_argument( - "-v", "--verbose", action="store_true", help="Run more verbosely." - ) - logging_group.add_argument( - "-q", "--quiet", action="store_true", help="Turn verbosity off." - ) - options = parser.parse_args(args) - - configLogger( - level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") - ) - - font = TTFont(options.font) - compact(font, options.gpos_compression_level) - font.save(options.outfile or options.font) - - -if __name__ == "__main__": - import sys - - if len(sys.argv) > 1: - sys.exit(main()) - import doctest - - sys.exit(doctest.testmod().failed) diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/gradio/themes/glass.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/gradio/themes/glass.py deleted file mode 100644 index f3a93e09b7f2d25ff8b2595761274867fd5da47a..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/gradio/themes/glass.py +++ /dev/null @@ -1,99 +0,0 @@ -from __future__ import annotations - -from typing import Iterable - -from gradio.themes.base import Base -from gradio.themes.utils import colors, fonts, sizes - - -class Glass(Base): - def __init__( - self, - *, - primary_hue: colors.Color | str = colors.stone, - secondary_hue: colors.Color | str = colors.stone, - neutral_hue: colors.Color | str = colors.stone, - spacing_size: sizes.Size | str = sizes.spacing_sm, - radius_size: sizes.Size | str = sizes.radius_sm, - text_size: sizes.Size | str = sizes.text_sm, - font: fonts.Font - | str - | Iterable[fonts.Font | str] = ( - "Optima", - "Candara", - "Noto Sans", - "source-sans-pro", - "sans-serif", - ), - font_mono: fonts.Font - | str - | Iterable[fonts.Font | str] = ( - fonts.GoogleFont("IBM Plex Mono"), - "ui-monospace", - "Consolas", - "monospace", - ), - ): - super().__init__( - primary_hue=primary_hue, - secondary_hue=secondary_hue, - neutral_hue=neutral_hue, - spacing_size=spacing_size, - radius_size=radius_size, - text_size=text_size, - font=font, - font_mono=font_mono, - ) - self.name = "glass" - super().set( - body_background_fill_dark="*primary_800", - background_fill_secondary_dark="*primary_800", - block_background_fill_dark="*primary_800", - button_primary_background_fill="linear-gradient(180deg, *primary_50 0%, *primary_200 50%, *primary_300 50%, *primary_200 100%)", - button_primary_background_fill_hover="linear-gradient(180deg, *primary_100 0%, *primary_200 50%, *primary_300 50%, *primary_200 100%)", - button_primary_background_fill_dark="linear-gradient(180deg, *primary_400 0%, *primary_500 50%, *primary_600 50%, *primary_500 100%)", - button_primary_background_fill_hover_dark="linear-gradient(180deg, *primary_400 0%, *primary_500 50%, *primary_600 50%, *primary_500 100%)", - button_secondary_background_fill="*button_primary_background_fill", - button_secondary_background_fill_hover="*button_primary_background_fill_hover", - button_secondary_background_fill_dark="*button_primary_background_fill", - button_secondary_background_fill_hover_dark="*button_primary_background_fill_hover", - button_cancel_background_fill="*button_primary_background_fill", - button_cancel_background_fill_hover="*button_primary_background_fill_hover", - button_cancel_background_fill_dark="*button_primary_background_fill", - button_cancel_background_fill_hover_dark="*button_primary_background_fill_hover", - button_cancel_border_color="*button_secondary_border_color", - button_cancel_border_color_dark="*button_secondary_border_color", - button_cancel_text_color="*button_secondary_text_color", - checkbox_border_width="0px", - checkbox_label_background_fill="*button_secondary_background_fill", - checkbox_label_background_fill_dark="*button_secondary_background_fill", - checkbox_label_background_fill_hover="*button_secondary_background_fill_hover", - checkbox_label_background_fill_hover_dark="*button_secondary_background_fill_hover", - checkbox_label_border_width="1px", - checkbox_background_color_dark="*primary_600", - button_border_width="1px", - button_shadow_active="*shadow_inset", - input_background_fill="linear-gradient(0deg, *secondary_50 0%, white 100%)", - input_background_fill_dark="*secondary_600", - input_border_color_focus_dark="*primary_400", - input_border_width="1px", - slider_color="*primary_400", - block_label_text_color="*primary_500", - block_title_text_color="*primary_500", - block_label_text_weight="600", - block_title_text_weight="600", - block_label_text_size="*text_md", - block_title_text_size="*text_md", - block_label_background_fill="*primary_200", - block_label_background_fill_dark="*primary_700", - block_border_width="0px", - block_border_width_dark="1px", - panel_border_width="1px", - border_color_primary_dark="*primary_500", - background_fill_primary_dark="*neutral_700", - background_fill_secondary="*primary_100", - block_background_fill="*primary_50", - block_shadow="*primary_400 0px 0px 3px 0px", - table_even_background_fill_dark="*neutral_700", - table_odd_background_fill_dark="*neutral_700", - ) diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpx/_status_codes.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpx/_status_codes.py deleted file mode 100644 index 671c30e1b80f82adebc3018b1e53a90054d93bfb..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/httpx/_status_codes.py +++ /dev/null @@ -1,158 +0,0 @@ -from enum import IntEnum - - -class codes(IntEnum): - """HTTP status codes and reason phrases - - Status codes from the following RFCs are all observed: - - * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 - * RFC 6585: Additional HTTP Status Codes - * RFC 3229: Delta encoding in HTTP - * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518 - * RFC 5842: Binding Extensions to WebDAV - * RFC 7238: Permanent Redirect - * RFC 2295: Transparent Content Negotiation in HTTP - * RFC 2774: An HTTP Extension Framework - * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) - * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) - * RFC 7725: An HTTP Status Code to Report Legal Obstacles - * RFC 8297: An HTTP Status Code for Indicating Hints - * RFC 8470: Using Early Data in HTTP - """ - - def __new__(cls, value: int, phrase: str = "") -> "codes": - obj = int.__new__(cls, value) - obj._value_ = value - - obj.phrase = phrase # type: ignore[attr-defined] - return obj - - def __str__(self) -> str: - return str(self.value) - - @classmethod - def get_reason_phrase(cls, value: int) -> str: - try: - return codes(value).phrase # type: ignore - except ValueError: - return "" - - @classmethod - def is_informational(cls, value: int) -> bool: - """ - Returns `True` for 1xx status codes, `False` otherwise. - """ - return 100 <= value <= 199 - - @classmethod - def is_success(cls, value: int) -> bool: - """ - Returns `True` for 2xx status codes, `False` otherwise. - """ - return 200 <= value <= 299 - - @classmethod - def is_redirect(cls, value: int) -> bool: - """ - Returns `True` for 3xx status codes, `False` otherwise. - """ - return 300 <= value <= 399 - - @classmethod - def is_client_error(cls, value: int) -> bool: - """ - Returns `True` for 4xx status codes, `False` otherwise. - """ - return 400 <= value <= 499 - - @classmethod - def is_server_error(cls, value: int) -> bool: - """ - Returns `True` for 5xx status codes, `False` otherwise. - """ - return 500 <= value <= 599 - - @classmethod - def is_error(cls, value: int) -> bool: - """ - Returns `True` for 4xx or 5xx status codes, `False` otherwise. - """ - return 400 <= value <= 599 - - # informational - CONTINUE = 100, "Continue" - SWITCHING_PROTOCOLS = 101, "Switching Protocols" - PROCESSING = 102, "Processing" - EARLY_HINTS = 103, "Early Hints" - - # success - OK = 200, "OK" - CREATED = 201, "Created" - ACCEPTED = 202, "Accepted" - NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information" - NO_CONTENT = 204, "No Content" - RESET_CONTENT = 205, "Reset Content" - PARTIAL_CONTENT = 206, "Partial Content" - MULTI_STATUS = 207, "Multi-Status" - ALREADY_REPORTED = 208, "Already Reported" - IM_USED = 226, "IM Used" - - # redirection - MULTIPLE_CHOICES = 300, "Multiple Choices" - MOVED_PERMANENTLY = 301, "Moved Permanently" - FOUND = 302, "Found" - SEE_OTHER = 303, "See Other" - NOT_MODIFIED = 304, "Not Modified" - USE_PROXY = 305, "Use Proxy" - TEMPORARY_REDIRECT = 307, "Temporary Redirect" - PERMANENT_REDIRECT = 308, "Permanent Redirect" - - # client error - BAD_REQUEST = 400, "Bad Request" - UNAUTHORIZED = 401, "Unauthorized" - PAYMENT_REQUIRED = 402, "Payment Required" - FORBIDDEN = 403, "Forbidden" - NOT_FOUND = 404, "Not Found" - METHOD_NOT_ALLOWED = 405, "Method Not Allowed" - NOT_ACCEPTABLE = 406, "Not Acceptable" - PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required" - REQUEST_TIMEOUT = 408, "Request Timeout" - CONFLICT = 409, "Conflict" - GONE = 410, "Gone" - LENGTH_REQUIRED = 411, "Length Required" - PRECONDITION_FAILED = 412, "Precondition Failed" - REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large" - REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long" - UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type" - REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable" - EXPECTATION_FAILED = 417, "Expectation Failed" - IM_A_TEAPOT = 418, "I'm a teapot" - MISDIRECTED_REQUEST = 421, "Misdirected Request" - UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity" - LOCKED = 423, "Locked" - FAILED_DEPENDENCY = 424, "Failed Dependency" - TOO_EARLY = 425, "Too Early" - UPGRADE_REQUIRED = 426, "Upgrade Required" - PRECONDITION_REQUIRED = 428, "Precondition Required" - TOO_MANY_REQUESTS = 429, "Too Many Requests" - REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large" - UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons" - - # server errors - INTERNAL_SERVER_ERROR = 500, "Internal Server Error" - NOT_IMPLEMENTED = 501, "Not Implemented" - BAD_GATEWAY = 502, "Bad Gateway" - SERVICE_UNAVAILABLE = 503, "Service Unavailable" - GATEWAY_TIMEOUT = 504, "Gateway Timeout" - HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported" - VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates" - INSUFFICIENT_STORAGE = 507, "Insufficient Storage" - LOOP_DETECTED = 508, "Loop Detected" - NOT_EXTENDED = 510, "Not Extended" - NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required" - - -# Include lower-case styles for `requests` compatibility. -for code in codes: - setattr(codes, code._name_.lower(), int(code)) diff --git a/spaces/declare-lab/tango/diffusers/tests/pipelines/stable_diffusion_safe/__init__.py b/spaces/declare-lab/tango/diffusers/tests/pipelines/stable_diffusion_safe/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/derina/BartSummarizer/app.py b/spaces/derina/BartSummarizer/app.py deleted file mode 100644 index 4bffd0b8ace52c9d6eba2073db75542933bde17a..0000000000000000000000000000000000000000 --- a/spaces/derina/BartSummarizer/app.py +++ /dev/null @@ -1,25 +0,0 @@ -import gradio as gr -from transformers import pipeline - -summarizer = pipeline("summarization", model="facebook/bart-large-cnn") - - -def summarize(text, slen): - return summarizer(text, max_length=slen, min_length=50)[0]["summary_text"] - - -title = "Bart large CNN Summarizer" -description = "Abstractive Text Summarization using Hugging Face transformers." -article = "

Sources: Transformers: Machine Learning with pretrained models

With help of Currency Strength meter: live indicator with real-time market data that compares a currency with other major currencies

" - -gr.Interface( - fn=summarize, - inputs=[ - gr.inputs.Textbox(label="Input Text", lines=12, placeholder="Enter text to summarize here"), - gr.inputs.Slider(60, 1000, default=400, label="Max summary length") - ], - outputs=gr.outputs.Textbox(type="text", label="Summary"), - title=title, - description=description, - article=article, -).launch() diff --git a/spaces/derinsu/Background_Generator/README.md b/spaces/derinsu/Background_Generator/README.md deleted file mode 100644 index 40990576e4802fed44b85c954577fa43eef95b09..0000000000000000000000000000000000000000 --- a/spaces/derinsu/Background_Generator/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Background Generator -emoji: 🏆 -colorFrom: purple -colorTo: blue -sdk: gradio -sdk_version: 3.34.0 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/diacanFperku/AutoGPT/Batman Begins Subtitles English 720p Dimensions.md b/spaces/diacanFperku/AutoGPT/Batman Begins Subtitles English 720p Dimensions.md deleted file mode 100644 index e08f3503560d9cc8a45e98aaf2dee9f008cacc0f..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Batman Begins Subtitles English 720p Dimensions.md +++ /dev/null @@ -1,43 +0,0 @@ -
-

Batman Begins Subtitles English 720p Dimensions

-

If you are a fan of Batman, you might want to watch Batman Begins, the first movie in the Dark Knight trilogy directed by Christopher Nolan. This movie tells the origin story of Bruce Wayne, who becomes the masked vigilante known as Batman after witnessing his parents' murder and training with a mysterious group called the League of Shadows.

-

batman begins subtitles english 720p dimensions


Download >>> https://gohhs.com/2uFUdo



-

But what if you want to watch Batman Begins with subtitles in English and in 720p dimensions? This is a common question among movie lovers who want to enjoy the movie in high quality and understand every dialogue. In this article, we will show you how to find and download Batman Begins subtitles English 720p dimensions for free and easily.

-

Why You Need Batman Begins Subtitles English 720p Dimensions

-

There are many reasons why you might need Batman Begins subtitles English 720p dimensions. Here are some of them:

-
    -
  • You are not a native speaker of English and you want to improve your listening skills and vocabulary by watching movies.
  • -
  • You have hearing problems and you need subtitles to follow the story and the conversations.
  • -
  • You want to watch the movie in a noisy environment or with low volume and you don't want to miss any important details.
  • -
  • You are interested in the cultural references, the jokes, the slang, and the idioms that are used in the movie.
  • -
  • You want to learn more about the Batman universe and the characters that appear in the movie.
  • -
-

Whatever your reason is, you can benefit from watching Batman Begins with subtitles in English and in 720p dimensions. Subtitles can help you enjoy the movie more, understand it better, and learn from it.

-

How to Find and Download Batman Begins Subtitles English 720p Dimensions

-

Now that you know why you need Batman Begins subtitles English 720p dimensions, you might wonder how to find and download them. Fortunately, there are many websites that offer subtitles for movies in different languages and formats. Here are some steps that you can follow to get your subtitles:

-
    -
  1. Go to your favorite search engine and type "Batman Begins subtitles English 720p dimensions" as your query. You will see many results that match your query.
  2. -
  3. Choose one of the websites that offer subtitles for Batman Begins. Some of the most popular ones are YIFY Subtitles, OpenSubtitles, Subscene, and Podnapisi.
  4. -
  5. On the website, look for the subtitle file that matches your movie version. For example, if you have downloaded or streamed Batman Begins from YIFY Torrents, you should look for a subtitle file that has YIFY in its name.
  6. -
  7. Download the subtitle file to your computer. It will usually be in a ZIP or RAR format, so you will need to extract it using a software like WinRAR or 7-Zip.
  8. -
  9. Rename the subtitle file to match the name of your movie file. For example, if your movie file is called "Batman.Begins.2005.720p.BRrip.x264.YIFY.mp4", you should rename your subtitle file to "Batman.Begins.2005.720p.BRrip.x264.YIFY.srt". This will make it easier for your media player to recognize and load the subtitles automatically.
  10. -
  11. Open your movie file with your preferred media player. Most media players support subtitles, such as VLC Media Player, Windows Media Player, KMPlayer, Media Player Classic, etc.
  12. -
  13. Enjoy watching Batman Begins with subtitles in English and in 720p dimensions!
  14. -
-

Conclusion

-

Batman Begins is a great movie that deserves to be watched with subtitles in English and in 720p dimensions. Subtitles can enhance your viewing experience, help you understand the movie better, and teach you new things. You can easily find and download Batman Begins subtitles English 720p dimensions from various websites on the internet. Just follow the steps above and you will be ready to watch Batman Begins with subtitles in no time!

-

What to Expect from Batman Begins Subtitles English 720p Dimensions

-

Once you have downloaded and loaded your Batman Begins subtitles English 720p dimensions, you can start watching the movie and enjoy its amazing features. Here are some of the things that you can expect from Batman Begins subtitles English 720p dimensions:

-
    -
  • You can see the subtitles clearly and read them comfortably on your screen. The subtitles are synced with the audio and video of the movie, so you won't miss any important dialogue or action.
  • -
  • You can choose the font size, color, and style of the subtitles according to your preference. You can also adjust the position and timing of the subtitles if needed.
  • -
  • You can learn new words, phrases, and expressions from the subtitles. You can also check the meaning and pronunciation of any word that you don't understand by using online dictionaries or translators.
  • -
  • You can appreciate the plot, the characters, and the themes of the movie better with the subtitles. You can also catch the subtle nuances, the humor, and the emotions that are conveyed by the actors.
  • -
  • You can have fun watching Batman Begins with your friends or family who speak different languages. You can share your thoughts and opinions about the movie with them using the subtitles as a common reference.
  • -
-

Batman Begins subtitles English 720p dimensions can enhance your viewing experience and make you enjoy the movie more. You can also learn new things and have fun with your subtitles.

-

-

Conclusion

-

Batman Begins is a great movie that deserves to be watched with subtitles in English and in 720p dimensions. Subtitles can enhance your viewing experience, help you understand the movie better, and teach you new things. You can easily find and download Batman Begins subtitles English 720p dimensions from various websites on the internet. Just follow the steps above and you will be ready to watch Batman Begins with subtitles in no time!

3cee63e6c2
-
-
\ No newline at end of file diff --git a/spaces/diacanFperku/AutoGPT/Behind-Enemy-Lines-2001-Brrip-720p-English-Subtitles.md b/spaces/diacanFperku/AutoGPT/Behind-Enemy-Lines-2001-Brrip-720p-English-Subtitles.md deleted file mode 100644 index 7241ef3ecc0e9a81cbb8f01101ba700c6a8bf36b..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Behind-Enemy-Lines-2001-Brrip-720p-English-Subtitles.md +++ /dev/null @@ -1,33 +0,0 @@ -behind enemy lines 2001 brrip 720p english subtitles - - - -Behind Enemy Lines 2001 Brrip 720p English Subtitles >>>>> [https://maudaracte.blogspot.com/?file=2tvJdi](https://maudaracte.blogspot.com/?file=2tvJdi) - - - - - - - - - -Here is a possible title and article with html formatting for the keyword "behind enemy lines 2001 brrip 720p english subtitles": - -``` -Behind Enemy Lines: A Thrilling War Film with Owen Wilson and Gene Hackman -Behind Enemy Lines is a 2001 American war film directed by John Moore in his directorial debut, and starring Owen Wilson and Gene Hackman. The film tells the story of Lieutenant Chris Burnett, an American naval flight officer who is shot down over Bosnia and uncovers genocide during the Bosnian War. He must evade enemy forces and survive until he can be rescued by his commanding officer, Admiral Reigart. -The film was inspired by the real-life story of Scott O'Grady, who was shot down over Bosnia in 1995 and rescued by US Marines. The film received mixed reviews from critics, but was a box office success, grossing over $91 million worldwide. It also spawned three direct-to-video sequels: Behind Enemy Lines II: Axis of Evil (2006), Behind Enemy Lines: Colombia (2009), and SEAL Team 8: Behind Enemy Lines (2014). -If you are looking for a thrilling and action-packed war film with a charismatic lead performance by Owen Wilson, you can watch Behind Enemy Lines online or download it in high quality. You can also enjoy the film with English subtitles, which are available in various formats such as BRRip, BluRay, or DVDRip. You can find the subtitles on various websites such as OpenSubtitles, SubDL, or KatMovieHD. -Behind Enemy Lines is a film that will keep you on the edge of your seat as you follow the perilous journey of Lieutenant Burnett and his quest to expose the truth. It is a film that explores the themes of courage, loyalty, and honor in the face of war and injustice. It is a film that you don't want to miss. -```Here are a few more paragraphs with html formatting for the keyword "behind enemy lines 2001 brrip 720p english subtitles": - -``` -Behind Enemy Lines features a talented cast of actors who bring their characters to life. Owen Wilson plays Lieutenant Burnett, a rebellious and cynical pilot who finds himself in a life-or-death situation. Wilson delivers a convincing performance as a man who must overcome his fears and doubts to survive and expose the truth. Gene Hackman plays Admiral Reigart, a tough and loyal commander who defies orders to rescue his downed pilot. Hackman portrays a leader who is willing to risk his career and reputation for his men. Gabriel Macht plays Stackhouse, Burnett's navigator and friend who is captured and killed by the enemy. Macht shows the camaraderie and bravery of a soldier who sacrifices himself for his partner. -The film also features an impressive supporting cast, including Joaquim de Almeida as Piquet, a UN official who tries to prevent Reigart from launching a rescue mission; David Keith as O'Malley, Reigart's second-in-command who supports his decisions; Olek Krupa as Lokar, a ruthless Serb warlord who orders the genocide; Vladimir Mashkov as Tracker, a skilled Serb sniper who hunts down Burnett; and Marko Igonda as Bazda, a Bosnian rebel who helps Burnett escape. -Behind Enemy Lines is not only a thrilling war film, but also a visually stunning one. The film was shot on location in Slovakia, which doubled for Bosnia. The film showcases the beautiful and diverse landscapes of the country, from the snowy mountains to the green forests to the urban ruins. The film also features spectacular aerial shots of the F/A-18 Hornet fighter jets flying over the terrain. The film's cinematography was done by Brendan Galvin, who captured the action and suspense of the film with his camera work. -The film also boasts an exciting and dramatic musical score by Don Davis, who composed the music for The Matrix trilogy. The score blends orchestral and electronic elements to create a tense and exhilarating atmosphere. The score also incorporates ethnic instruments and vocals to reflect the cultural setting of the film. The score enhances the mood and emotion of the film and adds to its impact. -``` dfd1c89656 - - - diff --git a/spaces/diacanFperku/AutoGPT/Makaron Naomi Bios.md b/spaces/diacanFperku/AutoGPT/Makaron Naomi Bios.md deleted file mode 100644 index a0e287803e3d8ce4ee36f3b3ab8487820f763781..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Makaron Naomi Bios.md +++ /dev/null @@ -1,31 +0,0 @@ - -

How to Use Makaron Naomi Bios to Emulate Dreamcast Games

-

If you are looking for a way to play Dreamcast games on your PC, you might have heard of Makaron Naomi Bios. This is a modified version of Makaron, a popular Dreamcast emulator that can run some games better than its rival Demul. In this article, we will show you how to download, install and configure Makaron Naomi Bios to enjoy your favorite Dreamcast titles.

-

Makaron Naomi Bios


Download File ✵✵✵ https://gohhs.com/2uFTsN



-

What is Makaron Naomi Bios?

-

Makaron Naomi Bios is a custom version of Makaron, a Dreamcast emulator that was developed by dknute. Makaron was released in 2010 and was praised for its accuracy and compatibility with many Dreamcast games. However, Makaron was also criticized for its complex user interface and lack of updates. The last official version of Makaron was released in 2013.

-

Makaron Naomi Bios is an unofficial update of Makaron that was created by an unknown developer. It was first published on npmjs.com in 2023 under the name makaron_naomi_bios_12sq4[^1^]. It claims to include a completely different and improved emulator that can run Sega Naomi arcade games as well as Dreamcast games. It also claims to have a simpler user interface and better performance than the original Makaron.

-

How to Download and Install Makaron Naomi Bios?

-

To use Makaron Naomi Bios, you will need to download two files: the emulator itself and the BIOS images. The emulator can be downloaded from this link[^1^]. It is a .7z file that you will need to extract using a tool like 7-Zip or WinZip. The BIOS images are files that contain the firmware of the Dreamcast console and are required for the emulator to work. However, these files are copyrighted and cannot be legally distributed online. You will need to obtain them from your own Dreamcast console or from other sources.

-

-

The BIOS files you need are named as follows:

-
    -
  • dreamcast_bios.bin (MD5 E10C53C2F8B90BAB96EAD2D368858623)
  • -
  • dreamcast_bios_eu.bin (MD5 A5C6A00818F97C5E3E91569EE22416DC)
  • -
  • dreamcast_bios_jp.bin (MD5 37C921EB47532CAE8FB70E5D987CE91C)
  • -
  • dreamcast_bios_usa.bin (MD5 E10C53C2F8B90BAB96EAD2D368858623)
  • -
  • dreamcast_flash_eu.bin (MD5 5D5A87B2CF24325911533CDB39ABDCB0)
  • -
  • dreamcast_flash_jp.bin (MD5 1E092EFA477CCA6D02AC1FB3455DE64C)
  • -
  • dreamcast_flash_usa.bin (MD5 D8C186874C6F9409FFF205E4ACA71A15)
  • -
  • VMU_BIOS.bin (MD5 CDA76326F85C04F753BFDDD4D6430558)
  • -
-

Once you have these files, you will need to copy them to the Data folder inside the MakaronEX folder that you extracted from the .7z file. You can use any file manager you like, but we recommend WinZip or 7-Zip.

-

How to Configure and Run Makaron Naomi Bios?

-

After you have installed the emulator and the BIOS files, you are ready to configure and run Makaron Naomi Bios. To do that, follow these steps:

-
    -
  1. Launch the emulator by double-clicking on the MakaronEX.exe file.
  2. -
  3. You will see a window with several tabs. Click on the Options tab and then on the Paths sub-tab.
  4. -
  5. Here you can set the directories where the emulator will look for your game files. You can use ISO, CDI, GDI or CHD formats for your games. Click on the Browse button next to each option and select the folder where you have your games stored.
  6. -
  7. d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/diacanFperku/AutoGPT/Pinnacle Studio HD 15 Content Pack V2.0 Light Download ((TOP)).md b/spaces/diacanFperku/AutoGPT/Pinnacle Studio HD 15 Content Pack V2.0 Light Download ((TOP)).md deleted file mode 100644 index eb62dda929fad5676e89fddd1d3c92400df0fc32..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/Pinnacle Studio HD 15 Content Pack V2.0 Light Download ((TOP)).md +++ /dev/null @@ -1,122 +0,0 @@ -
    -

    Pinnacle Studio HD 15 Content Pack v2.0 Light Download: A Review

    -

    If you are a fan of video editing and want to enhance your creativity and productivity, you might be interested in Pinnacle Studio HD 15 Content Pack v2.0 Light Download. This is a collection of effects and add-ons for Pinnacle Studio HD 15, a popular and powerful video editing software. Pinnacle Studio HD 15 Content Pack v2.0 Light Download will allow you to access hundreds of new features and improvements that will make your video editing experience more enjoyable and professional.

    -

    Pinnacle Studio HD 15 Content Pack V2.0 Light Download


    Download Ziphttps://gohhs.com/2uFUrO



    -

    What is Pinnacle Studio HD 15?

    -

    Pinnacle Studio HD 15 is a video editing software that was developed by Pinnacle Systems, a subsidiary of Corel Corporation. Pinnacle Studio HD 15 is designed for both beginners and advanced users who want to create high-quality HD movies with ease and speed. Pinnacle Studio HD 15 has many features that make it stand out from other video editing software, such as:

    -
      -
    • It can import video and photos from cameras, digital devices, phones, DVDs, and more.
    • -
    • It can edit HD video on the computer and provide fast performance thanks to the AVCHD and H.264 formats.
    • -
    • It can organize the media content with the project bin and the favorites folders.
    • -
    • It can use the Montage templates to create professional-looking movies with transitions, effects, and animations.
    • -
    • It can add titles, menus, soundtracks, and narration to the movies.
    • -
    • It can export the movies to YouTube, DVD, or mobile devices.
    • -
    -

    What is Pinnacle Studio HD 15 Content Pack v2.0 Light?

    -

    Pinnacle Studio HD 15 Content Pack v2.0 Light is a collection of effects and add-ons for Pinnacle Studio HD 15 that was released in 2011. Pinnacle Studio HD 15 Content Pack v2.0 Light includes:

    -
      -
    • Premium Pack Volume 1-2: These are two packs of high-quality effects and transitions that can enhance the look and feel of the movies.
    • -
    • Themes Winter Pack: This is a pack of winter-themed effects and transitions that can create a festive atmosphere for the movies.
    • -
    • Creative Pack Volume 1-3: These are three packs of creative effects and transitions that can add some fun and originality to the movies.
    • -
    • Title Extreme: This is a pack of animated titles that can make the movies more dynamic and engaging.
    • -
    • Hollywood FX Volume 1-3: These are three packs of Hollywood-style effects and transitions that can make the movies more cinematic and spectacular.
    • -
    • RTFX Volume 2: This is a pack of real-time effects and transitions that can provide fast and smooth editing.
    • -
    • ScoreFitter Volume 1-3: These are three packs of royalty-free music tracks that can match the mood and duration of the movies.
    • -
    • Video Plugins: These are various plugins that can add more functionality and creativity to the video editing process.
    • -
    • Pixel 1963 Alpha Magic Pack 1-2: These are two packs of gradient transitions that can create smooth and elegant changes between scenes.
    • -
    -

    How to Download and Install Pinnacle Studio HD 15 Content Pack v2.0 Light?

    -

    If you want to download and install Pinnacle Studio HD 15 Content Pack v2.0 Light, you need to follow these steps:

    -
      -
    1. Find a reliable source for the download file. You can use one of the links provided by the top 10 sites of the output.
    2. -
    3. Download the file and save it on your computer.
    4. -
    5. Run the file and follow the instructions to install Pinnacle Studio HD 15 Content Pack v2.0 Light.
    6. -
    7. Restart your computer and launch Pinnacle Studio HD 15.
    8. -
    9. Enjoy using Pinnacle Studio HD 15 Content Pack v2.0 Light with all its features and improvements.
    10. -
    - -

    Conclusion

    - -

    Pinnacle Studio HD 15 Content Pack v2.0 Light Download is a collection of effects and add-ons for Pinnacle Studio HD 15, a popular and powerful video editing software. Pinnacle Studio HD 15 Content Pack v2.0 Light Download will allow you to access hundreds of new features and improvements that will make your video editing experience more enjoyable and professional. If you are a fan of video editing and want to enhance your creativity and productivity, you might want to try Pinnacle Studio HD 15 Content Pack v2.0 Light Download.

    -

    -

    How to Use Pinnacle Studio HD 15 Content Pack v2.0 Light?

    -

    Once you have installed Pinnacle Studio HD 15 Content Pack v2.0 Light, you can start using it to create amazing HD movies with Pinnacle Studio HD 15. To use Pinnacle Studio HD 15 Content Pack v2.0 Light, you need to follow these steps:

    -
      -
    1. Launch Pinnacle Studio HD 15 and create a new project or open an existing one.
    2. -
    3. Import your video and photos from your camera, digital device, phone, DVD, or more.
    4. -
    5. Edit your video with the tools and features of Pinnacle Studio HD 15. You can use the effects and transitions from the content pack to enhance your video.
    6. -
    7. Add titles, menus, soundtracks, and narration to your video. You can use the templates and music tracks from the content pack to make your video more professional and engaging.
    8. -
    9. Export your video to YouTube, DVD, or mobile devices. You can choose the format and quality that suits your needs.
    10. -
    -

    What are the Benefits of Using Pinnacle Studio HD 15 Content Pack v2.0 Light?

    -

    Pinnacle Studio HD 15 Content Pack v2.0 Light is a collection of effects and add-ons for Pinnacle Studio HD 15 that can help you create high-quality HD movies with ease and speed. Some of the benefits of using Pinnacle Studio HD 15 Content Pack v2.0 Light are:

    -
      -
    • You can access hundreds of new features and improvements that will make your video editing experience more enjoyable and professional.
    • -
    • You can enhance your creativity and productivity with the effects and transitions from the content pack.
    • -
    • You can create professional-looking movies with the templates and music tracks from the content pack.
    • -
    • You can save time and money by using a free collection of effects and add-ons for Pinnacle Studio HD 15.
    • -
    • You can share your movies with your friends and family on YouTube, DVD, or mobile devices.
    • -
    - -

    Conclusion

    - -

    Pinnacle Studio HD 15 Content Pack v2.0 Light Download is a collection of effects and add-ons for Pinnacle Studio HD 15, a popular and powerful video editing software. Pinnacle Studio HD 15 Content Pack v2.0 Light Download will allow you to access hundreds of new features and improvements that will make your video editing experience more enjoyable and professional. If you are a fan of video editing and want to enhance your creativity and productivity, you might want to try Pinnacle Studio HD 15 Content Pack v2.0 Light Download.

    -

    How to Uninstall Pinnacle Studio HD 15 Content Pack v2.0 Light?

    -

    If you want to uninstall Pinnacle Studio HD 15 Content Pack v2.0 Light from your computer, you need to follow these steps:

    -
      -
    1. Launch Pinnacle Studio HD 15 and open the Control Panel.
    2. -
    3. Click on the Add or Remove Programs option and find Pinnacle Studio HD 15 Content Pack v2.0 Light in the list.
    4. -
    5. Click on the Remove button and confirm that you want to uninstall the program.
    6. -
    7. Wait for the uninstallation process to finish and restart your computer.
    8. -
    9. Delete any remaining files or folders related to Pinnacle Studio HD 15 Content Pack v2.0 Light from your computer.
    10. -
    -

    How to Update Pinnacle Studio HD 15 Content Pack v2.0 Light?

    -

    If you want to update Pinnacle Studio HD 15 Content Pack v2.0 Light to the latest version, you need to follow these steps:

    -
      -
    1. Launch Pinnacle Studio HD 15 and click on the Help menu.
    2. -
    3. Select the Check for Updates option and see if there is a new version available for Pinnacle Studio HD 15 Content Pack v2.0 Light.
    4. -
    5. If there is a new version available, click on the Download and Install button.
    6. -
    7. Wait for the update process to finish and restart your computer.
    8. -
    9. Enjoy using Pinnacle Studio HD 15 Content Pack v2.0 Light with the latest features and improvements.
    10. -
    -

    How to Contact Pinnacle Studio HD 15 Content Pack v2.0 Light Support?

    -

    If you have any questions or issues regarding Pinnacle Studio HD 15 Content Pack v2.0 Light, you can contact the support team by following these steps:

    -
      -
    1. Visit the official website of Pinnacle Studio HD 15 at https://www.pinnaclesys.com/en/products/studio/
    2. -
    3. Click on the Support button and select the Contact Us option.
    4. -
    5. Fill out the form with your name, email, subject, and message.
    6. -
    7. Click on the Submit button and wait for a reply from the support team.
    8. -
    9. You can also check the FAQ section or the User Guide for more information and guidance.
    10. -
    - -

    Conclusion

    - -

    Pinnacle Studio HD 15 Content Pack v2.0 Light Download is a collection of effects and add-ons for Pinnacle Studio HD 15, a popular and powerful video editing software. Pinnacle Studio HD 15 Content Pack v2.0 Light Download will allow you to access hundreds of new features and improvements that will make your video editing experience more enjoyable and professional. If you are a fan of video editing and want to enhance your creativity and productivity, you might want to try Pinnacle Studio HD 15 Content Pack v2.0 Light Download.

    -

    How to Download Pinnacle Studio HD 15 Content Pack v2.0 Light?

    -

    If you want to download Pinnacle Studio HD 15 Content Pack v2.0 Light, you need to follow these steps:

    -
      -
    1. Find a reliable source for the download file. You can use one of the links provided by the top 10 sites of the output.
    2. -
    3. Download the file and save it on your computer.
    4. -
    5. Extract the files from the downloaded archive using a tool like WinRAR or 7-Zip.
    6. -
    7. Run the setup file and follow the instructions to install Pinnacle Studio HD 15 Content Pack v2.0 Light.
    8. -
    9. Restart your computer and launch Pinnacle Studio HD 15.
    10. -
    11. Enjoy using Pinnacle Studio HD 15 Content Pack v2.0 Light with all its features and improvements.
    12. -
    -

    What are the Drawbacks of Using Pinnacle Studio HD 15 Content Pack v2.0 Light?

    -

    Pinnacle Studio HD 15 Content Pack v2.0 Light is a collection of effects and add-ons for Pinnacle Studio HD 15 that can help you create high-quality HD movies with ease and speed. However, it also comes with some drawbacks that you should be aware of before using it. Some of these drawbacks are:

    -
      -
    • You might encounter some compatibility issues with some of the effects and transitions from the content pack.
    • -
    • You might need a powerful computer system to run Pinnacle Studio HD 15 Content Pack v2.0 Light smoothly and efficiently.
    • -
    • You might need a lot of disk space to install and store Pinnacle Studio HD 15 Content Pack v2.0 Light on your computer.
    • -
    • You might need to update Pinnacle Studio HD 15 Content Pack v2.0 Light regularly to fix any bugs or errors.
    • -
    • You might need to pay for some of the effects and add-ons from the content pack if you want to use them for commercial purposes.
    • -
    - -

    Conclusion

    - -

    Pinnacle Studio HD 15 Content Pack v2.0 Light Download is a collection of effects and add-ons for Pinnacle Studio HD 15, a popular and powerful video editing software. Pinnacle Studio HD 15 Content Pack v2.0 Light Download will allow you to access hundreds of new features and improvements that will make your video editing experience more enjoyable and professional. If you are a fan of video editing and want to enhance your creativity and productivity, you might want to try Pinnacle Studio HD 15 Content Pack v2.0 Light Download.

    -

    Conclusion

    - -

    Pinnacle Studio HD 15 Content Pack v2.0 Light Download is a collection of effects and add-ons for Pinnacle Studio HD 15, a popular and powerful video editing software. Pinnacle Studio HD 15 Content Pack v2.0 Light Download will allow you to access hundreds of new features and improvements that will make your video editing experience more enjoyable and professional. If you are a fan of video editing and want to enhance your creativity and productivity, you might want to try Pinnacle Studio HD 15 Content Pack v2.0 Light Download.

    3cee63e6c2
    -
    -
    \ No newline at end of file diff --git a/spaces/digitalxingtong/Azusa-Bert-VITS2/text/chinese_bert.py b/spaces/digitalxingtong/Azusa-Bert-VITS2/text/chinese_bert.py deleted file mode 100644 index cb84ce0b426cd0a1c7954ddcdf41322c10ed14fa..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Azusa-Bert-VITS2/text/chinese_bert.py +++ /dev/null @@ -1,50 +0,0 @@ -import torch -from transformers import AutoTokenizer, AutoModelForMaskedLM - -device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - -tokenizer = AutoTokenizer.from_pretrained("./bert/chinese-roberta-wwm-ext-large") -model = AutoModelForMaskedLM.from_pretrained("./bert/chinese-roberta-wwm-ext-large").to(device) - -def get_bert_feature(text, word2ph): - with torch.no_grad(): - inputs = tokenizer(text, return_tensors='pt') - for i in inputs: - inputs[i] = inputs[i].to(device) - res = model(**inputs, output_hidden_states=True) - res = torch.cat(res['hidden_states'][-3:-2], -1)[0].cpu() - - assert len(word2ph) == len(text)+2 - word2phone = word2ph - phone_level_feature = [] - for i in range(len(word2phone)): - repeat_feature = res[i].repeat(word2phone[i], 1) - phone_level_feature.append(repeat_feature) - - phone_level_feature = torch.cat(phone_level_feature, dim=0) - - - return phone_level_feature.T - -if __name__ == '__main__': - # feature = get_bert_feature('你好,我是说的道理。') - import torch - - word_level_feature = torch.rand(38, 1024) # 12个词,每个词1024维特征 - word2phone = [1, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1] - - # 计算总帧数 - total_frames = sum(word2phone) - print(word_level_feature.shape) - print(word2phone) - phone_level_feature = [] - for i in range(len(word2phone)): - print(word_level_feature[i].shape) - - # 对每个词重复word2phone[i]次 - repeat_feature = word_level_feature[i].repeat(word2phone[i], 1) - phone_level_feature.append(repeat_feature) - - phone_level_feature = torch.cat(phone_level_feature, dim=0) - print(phone_level_feature.shape) # torch.Size([36, 1024]) - diff --git a/spaces/digitalxingtong/Bufeiyan-c-Bert-VITS2/modules.py b/spaces/digitalxingtong/Bufeiyan-c-Bert-VITS2/modules.py deleted file mode 100644 index 92e0f32a51c472bfd1659a50a95a95d195281d2b..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Bufeiyan-c-Bert-VITS2/modules.py +++ /dev/null @@ -1,452 +0,0 @@ -import copy -import math -import numpy as np -import scipy -import torch -from torch import nn -from torch.nn import functional as F - -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm - -import commons -from commons import init_weights, get_padding -from transforms import piecewise_rational_quadratic_transform -from attentions import Encoder - -LRELU_SLOPE = 0.1 - -class LayerNorm(nn.Module): - def __init__(self, channels, eps=1e-5): - super().__init__() - self.channels = channels - self.eps = eps - - self.gamma = nn.Parameter(torch.ones(channels)) - self.beta = nn.Parameter(torch.zeros(channels)) - - def forward(self, x): - x = x.transpose(1, -1) - x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps) - return x.transpose(1, -1) - -class ConvReluNorm(nn.Module): - def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout): - super().__init__() - self.in_channels = in_channels - self.hidden_channels = hidden_channels - self.out_channels = out_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.p_dropout = p_dropout - assert n_layers > 1, "Number of layers should be larger than 0." - - self.conv_layers = nn.ModuleList() - self.norm_layers = nn.ModuleList() - self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2)) - self.norm_layers.append(LayerNorm(hidden_channels)) - self.relu_drop = nn.Sequential( - nn.ReLU(), - nn.Dropout(p_dropout)) - for _ in range(n_layers-1): - self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2)) - self.norm_layers.append(LayerNorm(hidden_channels)) - self.proj = nn.Conv1d(hidden_channels, out_channels, 1) - self.proj.weight.data.zero_() - self.proj.bias.data.zero_() - - def forward(self, x, x_mask): - x_org = x - for i in range(self.n_layers): - x = self.conv_layers[i](x * x_mask) - x = self.norm_layers[i](x) - x = self.relu_drop(x) - x = x_org + self.proj(x) - return x * x_mask - - -class DDSConv(nn.Module): - """ - Dialted and Depth-Separable Convolution - """ - def __init__(self, channels, kernel_size, n_layers, p_dropout=0.): - super().__init__() - self.channels = channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.p_dropout = p_dropout - - self.drop = nn.Dropout(p_dropout) - self.convs_sep = nn.ModuleList() - self.convs_1x1 = nn.ModuleList() - self.norms_1 = nn.ModuleList() - self.norms_2 = nn.ModuleList() - for i in range(n_layers): - dilation = kernel_size ** i - padding = (kernel_size * dilation - dilation) // 2 - self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size, - groups=channels, dilation=dilation, padding=padding - )) - self.convs_1x1.append(nn.Conv1d(channels, channels, 1)) - self.norms_1.append(LayerNorm(channels)) - self.norms_2.append(LayerNorm(channels)) - - def forward(self, x, x_mask, g=None): - if g is not None: - x = x + g - for i in range(self.n_layers): - y = self.convs_sep[i](x * x_mask) - y = self.norms_1[i](y) - y = F.gelu(y) - y = self.convs_1x1[i](y) - y = self.norms_2[i](y) - y = F.gelu(y) - y = self.drop(y) - x = x + y - return x * x_mask - - -class WN(torch.nn.Module): - def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0): - super(WN, self).__init__() - assert(kernel_size % 2 == 1) - self.hidden_channels =hidden_channels - self.kernel_size = kernel_size, - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - self.p_dropout = p_dropout - - self.in_layers = torch.nn.ModuleList() - self.res_skip_layers = torch.nn.ModuleList() - self.drop = nn.Dropout(p_dropout) - - if gin_channels != 0: - cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1) - self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight') - - for i in range(n_layers): - dilation = dilation_rate ** i - padding = int((kernel_size * dilation - dilation) / 2) - in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size, - dilation=dilation, padding=padding) - in_layer = torch.nn.utils.weight_norm(in_layer, name='weight') - self.in_layers.append(in_layer) - - # last one is not necessary - if i < n_layers - 1: - res_skip_channels = 2 * hidden_channels - else: - res_skip_channels = hidden_channels - - res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1) - res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight') - self.res_skip_layers.append(res_skip_layer) - - def forward(self, x, x_mask, g=None, **kwargs): - output = torch.zeros_like(x) - n_channels_tensor = torch.IntTensor([self.hidden_channels]) - - if g is not None: - g = self.cond_layer(g) - - for i in range(self.n_layers): - x_in = self.in_layers[i](x) - if g is not None: - cond_offset = i * 2 * self.hidden_channels - g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:] - else: - g_l = torch.zeros_like(x_in) - - acts = commons.fused_add_tanh_sigmoid_multiply( - x_in, - g_l, - n_channels_tensor) - acts = self.drop(acts) - - res_skip_acts = self.res_skip_layers[i](acts) - if i < self.n_layers - 1: - res_acts = res_skip_acts[:,:self.hidden_channels,:] - x = (x + res_acts) * x_mask - output = output + res_skip_acts[:,self.hidden_channels:,:] - else: - output = output + res_skip_acts - return output * x_mask - - def remove_weight_norm(self): - if self.gin_channels != 0: - torch.nn.utils.remove_weight_norm(self.cond_layer) - for l in self.in_layers: - torch.nn.utils.remove_weight_norm(l) - for l in self.res_skip_layers: - torch.nn.utils.remove_weight_norm(l) - - -class ResBlock1(torch.nn.Module): - def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)): - super(ResBlock1, self).__init__() - self.convs1 = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], - padding=get_padding(kernel_size, dilation[0]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1], - padding=get_padding(kernel_size, dilation[1]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2], - padding=get_padding(kernel_size, dilation[2]))) - ]) - self.convs1.apply(init_weights) - - self.convs2 = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1, - padding=get_padding(kernel_size, 1))) - ]) - self.convs2.apply(init_weights) - - def forward(self, x, x_mask=None): - for c1, c2 in zip(self.convs1, self.convs2): - xt = F.leaky_relu(x, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c1(xt) - xt = F.leaky_relu(xt, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c2(xt) - x = xt + x - if x_mask is not None: - x = x * x_mask - return x - - def remove_weight_norm(self): - for l in self.convs1: - remove_weight_norm(l) - for l in self.convs2: - remove_weight_norm(l) - - -class ResBlock2(torch.nn.Module): - def __init__(self, channels, kernel_size=3, dilation=(1, 3)): - super(ResBlock2, self).__init__() - self.convs = nn.ModuleList([ - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0], - padding=get_padding(kernel_size, dilation[0]))), - weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1], - padding=get_padding(kernel_size, dilation[1]))) - ]) - self.convs.apply(init_weights) - - def forward(self, x, x_mask=None): - for c in self.convs: - xt = F.leaky_relu(x, LRELU_SLOPE) - if x_mask is not None: - xt = xt * x_mask - xt = c(xt) - x = xt + x - if x_mask is not None: - x = x * x_mask - return x - - def remove_weight_norm(self): - for l in self.convs: - remove_weight_norm(l) - - -class Log(nn.Module): - def forward(self, x, x_mask, reverse=False, **kwargs): - if not reverse: - y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask - logdet = torch.sum(-y, [1, 2]) - return y, logdet - else: - x = torch.exp(x) * x_mask - return x - - -class Flip(nn.Module): - def forward(self, x, *args, reverse=False, **kwargs): - x = torch.flip(x, [1]) - if not reverse: - logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device) - return x, logdet - else: - return x - - -class ElementwiseAffine(nn.Module): - def __init__(self, channels): - super().__init__() - self.channels = channels - self.m = nn.Parameter(torch.zeros(channels,1)) - self.logs = nn.Parameter(torch.zeros(channels,1)) - - def forward(self, x, x_mask, reverse=False, **kwargs): - if not reverse: - y = self.m + torch.exp(self.logs) * x - y = y * x_mask - logdet = torch.sum(self.logs * x_mask, [1,2]) - return y, logdet - else: - x = (x - self.m) * torch.exp(-self.logs) * x_mask - return x - - -class ResidualCouplingLayer(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - p_dropout=0, - gin_channels=0, - mean_only=False): - assert channels % 2 == 0, "channels should be divisible by 2" - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.half_channels = channels // 2 - self.mean_only = mean_only - - self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1) - self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels) - self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1) - self.post.weight.data.zero_() - self.post.bias.data.zero_() - - def forward(self, x, x_mask, g=None, reverse=False): - x0, x1 = torch.split(x, [self.half_channels]*2, 1) - h = self.pre(x0) * x_mask - h = self.enc(h, x_mask, g=g) - stats = self.post(h) * x_mask - if not self.mean_only: - m, logs = torch.split(stats, [self.half_channels]*2, 1) - else: - m = stats - logs = torch.zeros_like(m) - - if not reverse: - x1 = m + x1 * torch.exp(logs) * x_mask - x = torch.cat([x0, x1], 1) - logdet = torch.sum(logs, [1,2]) - return x, logdet - else: - x1 = (x1 - m) * torch.exp(-logs) * x_mask - x = torch.cat([x0, x1], 1) - return x - - -class ConvFlow(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0): - super().__init__() - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.num_bins = num_bins - self.tail_bound = tail_bound - self.half_channels = in_channels // 2 - - self.pre = nn.Conv1d(self.half_channels, filter_channels, 1) - self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.) - self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1) - self.proj.weight.data.zero_() - self.proj.bias.data.zero_() - - def forward(self, x, x_mask, g=None, reverse=False): - x0, x1 = torch.split(x, [self.half_channels]*2, 1) - h = self.pre(x0) - h = self.convs(h, x_mask, g=g) - h = self.proj(h) * x_mask - - b, c, t = x0.shape - h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?] - - unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels) - unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels) - unnormalized_derivatives = h[..., 2 * self.num_bins:] - - x1, logabsdet = piecewise_rational_quadratic_transform(x1, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=reverse, - tails='linear', - tail_bound=self.tail_bound - ) - - x = torch.cat([x0, x1], 1) * x_mask - logdet = torch.sum(logabsdet * x_mask, [1,2]) - if not reverse: - return x, logdet - else: - return x -class TransformerCouplingLayer(nn.Module): - def __init__(self, - channels, - hidden_channels, - kernel_size, - n_layers, - n_heads, - p_dropout=0, - filter_channels=0, - mean_only=False, - wn_sharing_parameter=None, - gin_channels = 0 - ): - assert channels % 2 == 0, "channels should be divisible by 2" - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.half_channels = channels // 2 - self.mean_only = mean_only - - self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1) - self.enc = Encoder(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = gin_channels) if wn_sharing_parameter is None else wn_sharing_parameter - self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1) - self.post.weight.data.zero_() - self.post.bias.data.zero_() - - def forward(self, x, x_mask, g=None, reverse=False): - x0, x1 = torch.split(x, [self.half_channels]*2, 1) - h = self.pre(x0) * x_mask - h = self.enc(h, x_mask, g=g) - stats = self.post(h) * x_mask - if not self.mean_only: - m, logs = torch.split(stats, [self.half_channels]*2, 1) - else: - m = stats - logs = torch.zeros_like(m) - - if not reverse: - x1 = m + x1 * torch.exp(logs) * x_mask - x = torch.cat([x0, x1], 1) - logdet = torch.sum(logs, [1,2]) - return x, logdet - else: - x1 = (x1 - m) * torch.exp(-logs) * x_mask - x = torch.cat([x0, x1], 1) - return x - - x1, logabsdet = piecewise_rational_quadratic_transform(x1, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=reverse, - tails='linear', - tail_bound=self.tail_bound - ) - - x = torch.cat([x0, x1], 1) * x_mask - logdet = torch.sum(logabsdet * x_mask, [1,2]) - if not reverse: - return x, logdet - else: - return x diff --git a/spaces/digitalxingtong/Nailv-read-Bert-Vits2/text/cleaner.py b/spaces/digitalxingtong/Nailv-read-Bert-Vits2/text/cleaner.py deleted file mode 100644 index 64bd5f7296f66c94f3a335666c53706bb5fe5b39..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Nailv-read-Bert-Vits2/text/cleaner.py +++ /dev/null @@ -1,27 +0,0 @@ -from text import chinese, cleaned_text_to_sequence - - -language_module_map = { - 'ZH': chinese -} - - -def clean_text(text, language): - language_module = language_module_map[language] - norm_text = language_module.text_normalize(text) - phones, tones, word2ph = language_module.g2p(norm_text) - return norm_text, phones, tones, word2ph - -def clean_text_bert(text, language): - language_module = language_module_map[language] - norm_text = language_module.text_normalize(text) - phones, tones, word2ph = language_module.g2p(norm_text) - bert = language_module.get_bert_feature(norm_text, word2ph) - return phones, tones, bert - -def text_to_sequence(text, language): - norm_text, phones, tones, word2ph = clean_text(text, language) - return cleaned_text_to_sequence(phones, tones, language) - -if __name__ == '__main__': - pass diff --git a/spaces/digitalxingtong/Shanbao-Bert-VITS2/train_ms.py b/spaces/digitalxingtong/Shanbao-Bert-VITS2/train_ms.py deleted file mode 100644 index 5d109003d40497ea4493e7c73f47c1eb7370a81e..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Shanbao-Bert-VITS2/train_ms.py +++ /dev/null @@ -1,402 +0,0 @@ -import os -import json -import argparse -import itertools -import math -import torch -import shutil -from torch import nn, optim -from torch.nn import functional as F -from torch.utils.data import DataLoader -from torch.utils.tensorboard import SummaryWriter -import torch.multiprocessing as mp -import torch.distributed as dist -from torch.nn.parallel import DistributedDataParallel as DDP -from torch.cuda.amp import autocast, GradScaler -from tqdm import tqdm -import logging -logging.getLogger('numba').setLevel(logging.WARNING) -import commons -import utils -from data_utils import ( - TextAudioSpeakerLoader, - TextAudioSpeakerCollate, - DistributedBucketSampler -) -from models import ( - SynthesizerTrn, - MultiPeriodDiscriminator, - DurationDiscriminator, -) -from losses import ( - generator_loss, - discriminator_loss, - feature_loss, - kl_loss -) -from mel_processing import mel_spectrogram_torch, spec_to_mel_torch -from text.symbols import symbols - -torch.backends.cudnn.benchmark = True -torch.backends.cuda.matmul.allow_tf32 = True -torch.backends.cudnn.allow_tf32 = True -torch.set_float32_matmul_precision('medium') -global_step = 0 - - -def main(): - """Assume Single Node Multi GPUs Training Only""" - assert torch.cuda.is_available(), "CPU training is not allowed." - - n_gpus = torch.cuda.device_count() - os.environ['MASTER_ADDR'] = 'localhost' - os.environ['MASTER_PORT'] = '65280' - - hps = utils.get_hparams() - if not hps.cont: - shutil.copy('./pretrained_models/D_0.pth','./logs/OUTPUT_MODEL/D_0.pth') - shutil.copy('./pretrained_models/G_0.pth','./logs/OUTPUT_MODEL/G_0.pth') - shutil.copy('./pretrained_models/DUR_0.pth','./logs/OUTPUT_MODEL/DUR_0.pth') - mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,)) - - -def run(rank, n_gpus, hps): - global global_step - if rank == 0: - logger = utils.get_logger(hps.model_dir) - logger.info(hps) - utils.check_git_hash(hps.model_dir) - writer = SummaryWriter(log_dir=hps.model_dir) - writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) - - dist.init_process_group(backend= 'gloo' if os.name == 'nt' else 'nccl', init_method='env://', world_size=n_gpus, rank=rank) - torch.manual_seed(hps.train.seed) - torch.cuda.set_device(rank) - - train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) - train_sampler = DistributedBucketSampler( - train_dataset, - hps.train.batch_size, - [32, 300, 400, 500, 600, 700, 800, 900, 1000], - num_replicas=n_gpus, - rank=rank, - shuffle=True) - collate_fn = TextAudioSpeakerCollate() - train_loader = DataLoader(train_dataset, num_workers=2, shuffle=False, pin_memory=True, - collate_fn=collate_fn, batch_sampler=train_sampler) - if rank == 0: - eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data) - eval_loader = DataLoader(eval_dataset, num_workers=0, shuffle=False, - batch_size=1, pin_memory=True, - drop_last=False, collate_fn=collate_fn) - if "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas == True: - print("Using noise scaled MAS for VITS2") - use_noise_scaled_mas = True - mas_noise_scale_initial = 0.01 - noise_scale_delta = 2e-6 - else: - print("Using normal MAS for VITS1") - use_noise_scaled_mas = False - mas_noise_scale_initial = 0.0 - noise_scale_delta = 0.0 - if "use_duration_discriminator" in hps.model.keys() and hps.model.use_duration_discriminator == True: - print("Using duration discriminator for VITS2") - use_duration_discriminator = True - net_dur_disc = DurationDiscriminator( - hps.model.hidden_channels, - hps.model.hidden_channels, - 3, - 0.1, - gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, - ).cuda(rank) - if "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder == True: - if hps.data.n_speakers == 0: - raise ValueError("n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model") - use_spk_conditioned_encoder = True - else: - print("Using normal encoder for VITS1") - use_spk_conditioned_encoder = False - - net_g = SynthesizerTrn( - len(symbols), - hps.data.filter_length // 2 + 1, - hps.train.segment_size // hps.data.hop_length, - n_speakers=hps.data.n_speakers, - mas_noise_scale_initial = mas_noise_scale_initial, - noise_scale_delta = noise_scale_delta, - **hps.model).cuda(rank) - - freeze_enc = getattr(hps.model, "freeze_enc", False) - if freeze_enc: - print("freeze encoder !!!") - for param in net_g.enc_p.parameters(): - param.requires_grad = False - - net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank) - optim_g = torch.optim.AdamW( - filter(lambda p: p.requires_grad, net_g.parameters()), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps) - optim_d = torch.optim.AdamW( - net_d.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps) - if net_dur_disc is not None: - optim_dur_disc = torch.optim.AdamW( - net_dur_disc.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps) - else: - optim_dur_disc = None - net_g = DDP(net_g, device_ids=[rank], find_unused_parameters=True) - net_d = DDP(net_d, device_ids=[rank], find_unused_parameters=True) - if net_dur_disc is not None: - net_dur_disc = DDP(net_dur_disc, device_ids=[rank], find_unused_parameters=True) - - pretrain_dir = None - if pretrain_dir is None: - try: - if net_dur_disc is not None: - _, optim_dur_disc, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"), net_dur_disc, optim_dur_disc, skip_optimizer=not hps.cont) - _, optim_g, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, - optim_g, skip_optimizer=not hps.cont) - _, optim_d, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, - optim_d, skip_optimizer=not hps.cont) - - epoch_str = max(epoch_str, 1) - global_step = (epoch_str - 1) * len(train_loader) - except Exception as e: - print(e) - epoch_str = 1 - global_step = 0 - else: - _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "G_*.pth"), net_g, - optim_g, True) - _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "D_*.pth"), net_d, - optim_d, True) - - - - scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) - scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) - if net_dur_disc is not None: - scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR(optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str-2) - else: - scheduler_dur_disc = None - scaler = GradScaler(enabled=hps.train.fp16_run) - - for epoch in range(epoch_str, hps.train.epochs + 1): - if rank == 0: - train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval]) - else: - train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None) - scheduler_g.step() - scheduler_d.step() - if net_dur_disc is not None: - scheduler_dur_disc.step() - - -def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers): - net_g, net_d, net_dur_disc = nets - optim_g, optim_d, optim_dur_disc = optims - scheduler_g, scheduler_d, scheduler_dur_disc = schedulers - train_loader, eval_loader = loaders - if writers is not None: - writer, writer_eval = writers - - train_loader.batch_sampler.set_epoch(epoch) - global global_step - - net_g.train() - net_d.train() - if net_dur_disc is not None: - net_dur_disc.train() - for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in tqdm(enumerate(train_loader)): - if net_g.module.use_noise_scaled_mas: - current_mas_noise_scale = net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step - net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) - x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True) - spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True) - y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True) - speakers = speakers.cuda(rank, non_blocking=True) - tone = tone.cuda(rank, non_blocking=True) - language = language.cuda(rank, non_blocking=True) - bert = bert.cuda(rank, non_blocking=True) - - with autocast(enabled=hps.train.fp16_run): - y_hat, l_length, attn, ids_slice, x_mask, z_mask, \ - (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_) = net_g(x, x_lengths, spec, spec_lengths, speakers, tone, language, bert) - mel = spec_to_mel_torch( - spec, - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.mel_fmin, - hps.data.mel_fmax) - y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) - y_hat_mel = mel_spectrogram_torch( - y_hat.squeeze(1), - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.hop_length, - hps.data.win_length, - hps.data.mel_fmin, - hps.data.mel_fmax - ) - - y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice - - # Discriminator - y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) - with autocast(enabled=False): - loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) - loss_disc_all = loss_disc - if net_dur_disc is not None: - y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach()) - with autocast(enabled=False): - # TODO: I think need to mean using the mask, but for now, just mean all - loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g = discriminator_loss(y_dur_hat_r, y_dur_hat_g) - loss_dur_disc_all = loss_dur_disc - optim_dur_disc.zero_grad() - scaler.scale(loss_dur_disc_all).backward() - scaler.unscale_(optim_dur_disc) - grad_norm_dur_disc = commons.clip_grad_value_(net_dur_disc.parameters(), None) - scaler.step(optim_dur_disc) - - optim_d.zero_grad() - scaler.scale(loss_disc_all).backward() - scaler.unscale_(optim_d) - grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) - scaler.step(optim_d) - - with autocast(enabled=hps.train.fp16_run): - # Generator - y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) - if net_dur_disc is not None: - y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) - with autocast(enabled=False): - loss_dur = torch.sum(l_length.float()) - loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel - loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl - - loss_fm = feature_loss(fmap_r, fmap_g) - loss_gen, losses_gen = generator_loss(y_d_hat_g) - loss_gen_all = loss_gen + loss_fm + loss_mel + loss_dur + loss_kl - if net_dur_disc is not None: - loss_dur_gen, losses_dur_gen = generator_loss(y_dur_hat_g) - loss_gen_all += loss_dur_gen - optim_g.zero_grad() - scaler.scale(loss_gen_all).backward() - scaler.unscale_(optim_g) - grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None) - scaler.step(optim_g) - scaler.update() - - if rank == 0: - if global_step % hps.train.log_interval == 0: - lr = optim_g.param_groups[0]['lr'] - losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl] - logger.info('Train Epoch: {} [{:.0f}%]'.format( - epoch, - 100. * batch_idx / len(train_loader))) - logger.info([x.item() for x in losses] + [global_step, lr]) - - scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr, - "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g} - scalar_dict.update( - {"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/dur": loss_dur, "loss/g/kl": loss_kl}) - scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)}) - scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)}) - scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)}) - - image_dict = { - "slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()), - "slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()), - "all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()), - "all/attn": utils.plot_alignment_to_numpy(attn[0, 0].data.cpu().numpy()) - } - utils.summarize( - writer=writer, - global_step=global_step, - images=image_dict, - scalars=scalar_dict) - - if global_step % hps.train.eval_interval == 0: - evaluate(hps, net_g, eval_loader, writer_eval) - utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch, - os.path.join(hps.model_dir, "G_{}.pth".format(global_step))) - utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch, - os.path.join(hps.model_dir, "D_{}.pth".format(global_step))) - if net_dur_disc is not None: - utils.save_checkpoint(net_dur_disc, optim_dur_disc, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "DUR_{}.pth".format(global_step))) - keep_ckpts = getattr(hps.train, 'keep_ckpts', 5) - if keep_ckpts > 0: - utils.clean_checkpoints(path_to_models=hps.model_dir, n_ckpts_to_keep=keep_ckpts, sort_by_time=True) - - - global_step += 1 - - if rank == 0: - logger.info('====> Epoch: {}'.format(epoch)) - - - -def evaluate(hps, generator, eval_loader, writer_eval): - generator.eval() - image_dict = {} - audio_dict = {} - print("Evaluating ...") - with torch.no_grad(): - for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in enumerate(eval_loader): - x, x_lengths = x.cuda(), x_lengths.cuda() - spec, spec_lengths = spec.cuda(), spec_lengths.cuda() - y, y_lengths = y.cuda(), y_lengths.cuda() - speakers = speakers.cuda() - bert = bert.cuda() - tone = tone.cuda() - language = language.cuda() - for use_sdp in [True, False]: - y_hat, attn, mask, *_ = generator.module.infer(x, x_lengths, speakers, tone, language, bert, y=spec, max_len=1000, sdp_ratio=0.0 if not use_sdp else 1.0) - y_hat_lengths = mask.sum([1, 2]).long() * hps.data.hop_length - - mel = spec_to_mel_torch( - spec, - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.mel_fmin, - hps.data.mel_fmax) - y_hat_mel = mel_spectrogram_torch( - y_hat.squeeze(1).float(), - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.hop_length, - hps.data.win_length, - hps.data.mel_fmin, - hps.data.mel_fmax - ) - image_dict.update({ - f"gen/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy()) - }) - audio_dict.update({ - f"gen/audio_{batch_idx}_{use_sdp}": y_hat[0, :, :y_hat_lengths[0]] - }) - image_dict.update({f"gt/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())}) - audio_dict.update({f"gt/audio_{batch_idx}": y[0, :, :y_lengths[0]]}) - - utils.summarize( - writer=writer_eval, - global_step=global_step, - images=image_dict, - audios=audio_dict, - audio_sampling_rate=hps.data.sampling_rate - ) - generator.train() - -if __name__ == "__main__": - main() diff --git a/spaces/dirge/voicevox/build_util/create_venv_and_generate_licenses.bash b/spaces/dirge/voicevox/build_util/create_venv_and_generate_licenses.bash deleted file mode 100644 index d2c837dbfad2f66bf1c3d73f19199e6fa93910dd..0000000000000000000000000000000000000000 --- a/spaces/dirge/voicevox/build_util/create_venv_and_generate_licenses.bash +++ /dev/null @@ -1,24 +0,0 @@ -# 仮想環境を作ってrequirements.txtをインストールし、ライセンス一覧を生成する - -set -eux - -if [ ! -v OUTPUT_LICENSE_JSON_PATH ]; then - echo "OUTPUT_LICENSE_JSON_PATHが未定義です" - exit 1 -fi - -VENV_PATH="licenses_venv" - -python -m venv $VENV_PATH -if [ -d "$VENV_PATH/Scripts" ]; then - source $VENV_PATH/Scripts/activate -else - source $VENV_PATH/bin/activate -fi - -pip install -r requirements-license.txt -python generate_licenses.py >$OUTPUT_LICENSE_JSON_PATH - -deactivate - -rm -rf $VENV_PATH diff --git a/spaces/dylanebert/FarmingGame/Build/Build.framework.js b/spaces/dylanebert/FarmingGame/Build/Build.framework.js deleted file mode 100644 index 92368dbec910db2eed6ba6c21d6c5f1e0c5db1c5..0000000000000000000000000000000000000000 --- a/spaces/dylanebert/FarmingGame/Build/Build.framework.js +++ /dev/null @@ -1,5 +0,0 @@ -function unityFramework(Module) { -var Module=typeof Module!=="undefined"?Module:{}; -function Pointer_stringify(s,len){warnOnce("The JavaScript function 'Pointer_stringify(ptrToSomeCString)' is obsoleted and will be removed in a future Unity version. Please call 'UTF8ToString(ptrToSomeCString)' instead.");return UTF8ToString(s,len)}Module["Pointer_stringify"]=Pointer_stringify;var stackTraceReference="(^|\\n)(\\s+at\\s+|)jsStackTrace(\\s+\\(|@)([^\\n]+):\\d+:\\d+(\\)|)(\\n|$)";var stackTraceReferenceMatch=jsStackTrace().match(new RegExp(stackTraceReference));if(stackTraceReferenceMatch)Module.stackTraceRegExp=new RegExp(stackTraceReference.replace("([^\\n]+)",stackTraceReferenceMatch[4].replace(/[\\^${}[\]().*+?|]/g,"\\$&")).replace("jsStackTrace","[^\\n]+"));var abort=function(what){if(ABORT)return;ABORT=true;EXITSTATUS=1;if(typeof ENVIRONMENT_IS_PTHREAD!=="undefined"&&ENVIRONMENT_IS_PTHREAD)console.error("Pthread aborting at "+(new Error).stack);if(what!==undefined){out(what);err(what);what=JSON.stringify(what)}else{what=""}var message="abort("+what+") at "+stackTrace();if(Module.abortHandler&&Module.abortHandler(message))return;throw message};Module["SetFullscreen"]=function(fullscreen){if(typeof runtimeInitialized==="undefined"||!runtimeInitialized){console.log("Runtime not initialized yet.")}else if(typeof JSEvents==="undefined"){console.log("Player not loaded yet.")}else{var tmp=JSEvents.canPerformEventHandlerRequests;JSEvents.canPerformEventHandlerRequests=function(){return 1};Module.ccall("SetFullscreen",null,["number"],[fullscreen]);JSEvents.canPerformEventHandlerRequests=tmp}};if(typeof ENVIRONMENT_IS_PTHREAD==="undefined"||!ENVIRONMENT_IS_PTHREAD){Module["preRun"].push(function(){var unityFileSystemInit=Module["unityFileSystemInit"]||function(){FS.mkdir("/idbfs");FS.mount(IDBFS,{},"/idbfs");Module.addRunDependency("JS_FileSystem_Mount");FS.syncfs(true,function(err){if(err)console.log("IndexedDB is not available. Data will not persist in cache and PlayerPrefs will not be saved.");Module.removeRunDependency("JS_FileSystem_Mount")})};unityFileSystemInit()})}var videoInputDevices=[];var removeEnumerateMediaDevicesRunDependency;function matchToOldDevice(newDevice){var oldDevices=Object.keys(videoInputDevices);for(var i=0;i1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);if(typeof module!=="undefined"){module["exports"]=Module}process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function alignMemory(size,factor){if(!factor)factor=STACK_ALIGN;return Math.ceil(size/factor)*factor}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var getTempRet0=function(){return tempRet0};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];assert(func,"Cannot call unknown function "+ident+", make sure it is exported");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={"string":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},"array":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string")return UTF8ToString(ret);if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function allocateUTF8OnStack(str){var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8Array(str,HEAP8,ret,size);return ret}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||33554432;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();TTY.init();SOCKFS.root=FS.mount(SOCKFS,{},null);callRuntimeCallbacks(__ATINIT__)}function preMain(){FS.ignorePermissions=false;callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile="build.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["xh"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["Vh"];addOnInit(Module["asm"]["yh"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){var result=WebAssembly.instantiate(binary,info);return result}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync();return{}}var tempDouble;var tempI64;var ASM_CONSTS={4212964:function(){return Module.webglContextAttributes.premultipliedAlpha},4213025:function(){return Module.webglContextAttributes.preserveDrawingBuffer}};function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){(function(){dynCall_v.call(null,func)})()}else{(function(a1){dynCall_vi.apply(null,[func,a1])})(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function demangle(func){return func}function demangleAll(text){var regex=/\b_Z[\w\d_]+/g;return text.replace(regex,function(x){var y=demangle(x);return x===y?x:y+" ["+x+"]"})}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}function dynCall(sig,ptr,args){return dynCallLegacy(sig,ptr,args)}function jsStackTrace(){var error=new Error;if(!error.stack){try{throw new Error}catch(e){error=e}if(!error.stack){return"(no stack trace available)"}}return error.stack.toString()}var runtimeKeepaliveCounter=0;function keepRuntimeAlive(){return noExitRuntime||runtimeKeepaliveCounter>0}function stackTrace(){var js=jsStackTrace();if(Module["extraStackTrace"])js+="\n"+Module["extraStackTrace"]();return demangleAll(js)}var JS_Accelerometer=null;var JS_Accelerometer_callback=0;function _JS_Accelerometer_IsRunning(){return JS_Accelerometer&&JS_Accelerometer.activated||JS_Accelerometer_callback!=0}var JS_Accelerometer_multiplier=1;var JS_Accelerometer_lastValue={x:0,y:0,z:0};function JS_Accelerometer_eventHandler(){JS_Accelerometer_lastValue={x:JS_Accelerometer.x*JS_Accelerometer_multiplier,y:JS_Accelerometer.y*JS_Accelerometer_multiplier,z:JS_Accelerometer.z*JS_Accelerometer_multiplier};if(JS_Accelerometer_callback!=0)dynCall_vfff(JS_Accelerometer_callback,JS_Accelerometer_lastValue.x,JS_Accelerometer_lastValue.y,JS_Accelerometer_lastValue.z)}var JS_Accelerometer_frequencyRequest=0;var JS_Accelerometer_frequency=0;var JS_LinearAccelerationSensor_callback=0;var JS_GravitySensor_callback=0;var JS_Gyroscope_callback=0;function JS_ComputeGravity(accelerometerValue,linearAccelerationValue){var difference={x:accelerometerValue.x-linearAccelerationValue.x,y:accelerometerValue.y-linearAccelerationValue.y,z:accelerometerValue.z-linearAccelerationValue.z};var differenceMagnitudeSq=difference.x*difference.x+difference.y*difference.y+difference.z*difference.z;var sum={x:accelerometerValue.x+linearAccelerationValue.x,y:accelerometerValue.y+linearAccelerationValue.y,z:accelerometerValue.z+linearAccelerationValue.z};var sumMagnitudeSq=sum.x*sum.x+sum.y*sum.y+sum.z*sum.z;return differenceMagnitudeSq<=sumMagnitudeSq?difference:sum}function JS_DeviceMotion_eventHandler(event){var accelerometerValue={x:event.accelerationIncludingGravity.x*JS_Accelerometer_multiplier,y:event.accelerationIncludingGravity.y*JS_Accelerometer_multiplier,z:event.accelerationIncludingGravity.z*JS_Accelerometer_multiplier};if(JS_Accelerometer_callback!=0)dynCall_vfff(JS_Accelerometer_callback,accelerometerValue.x,accelerometerValue.y,accelerometerValue.z);var linearAccelerationValue={x:event.acceleration.x*JS_Accelerometer_multiplier,y:event.acceleration.y*JS_Accelerometer_multiplier,z:event.acceleration.z*JS_Accelerometer_multiplier};if(JS_LinearAccelerationSensor_callback!=0)dynCall_vfff(JS_LinearAccelerationSensor_callback,linearAccelerationValue.x,linearAccelerationValue.y,linearAccelerationValue.z);if(JS_GravitySensor_callback!=0){var gravityValue=JS_ComputeGravity(accelerometerValue,linearAccelerationValue);dynCall_vfff(JS_GravitySensor_callback,gravityValue.x,gravityValue.y,gravityValue.z)}if(JS_Gyroscope_callback!=0){var degToRad=Math.PI/180;dynCall_vfff(JS_Gyroscope_callback,event.rotationRate.alpha*degToRad,event.rotationRate.beta*degToRad,event.rotationRate.gamma*degToRad)}}var JS_DeviceSensorPermissions=0;function JS_RequestDeviceSensorPermissions(permissions){if(permissions&1){if(typeof DeviceOrientationEvent.requestPermission==="function"){DeviceOrientationEvent.requestPermission().then(function(permissionState){if(permissionState==="granted"){JS_DeviceSensorPermissions&=~1}else{warnOnce("DeviceOrientationEvent permission not granted")}}).catch(function(err){warnOnce(err);JS_DeviceSensorPermissions|=1})}}if(permissions&2){if(typeof DeviceMotionEvent.requestPermission==="function"){DeviceMotionEvent.requestPermission().then(function(permissionState){if(permissionState==="granted"){JS_DeviceSensorPermissions&=~2}else{warnOnce("DeviceMotionEvent permission not granted")}}).catch(function(err){warnOnce(err);JS_DeviceSensorPermissions|=2})}}}function JS_DeviceMotion_add(){if(JS_Accelerometer_callback==0&&JS_LinearAccelerationSensor_callback==0&&JS_GravitySensor_callback==0&&JS_Gyroscope_callback==0){JS_RequestDeviceSensorPermissions(2);window.addEventListener("devicemotion",JS_DeviceMotion_eventHandler)}}function JS_DefineAccelerometerMultiplier(){var g=9.80665;JS_Accelerometer_multiplier=/(iPhone|iPad|Macintosh)/i.test(navigator.userAgent)?1/g:-1/g}function _JS_Accelerometer_Start(callback,frequency){JS_DefineAccelerometerMultiplier();if(typeof Accelerometer==="undefined"){JS_DeviceMotion_add();if(callback!=0)JS_Accelerometer_callback=callback;return}if(callback!=0)JS_Accelerometer_callback=callback;function InitializeAccelerometer(frequency){JS_Accelerometer=new Accelerometer({frequency:frequency,referenceFrame:"device"});JS_Accelerometer.addEventListener("reading",JS_Accelerometer_eventHandler);JS_Accelerometer.addEventListener("error",function(e){warnOnce(e.error?e.error:e)});JS_Accelerometer.start();JS_Accelerometer_frequency=frequency}if(JS_Accelerometer){if(JS_Accelerometer_frequency!=frequency){JS_Accelerometer.stop();JS_Accelerometer.removeEventListener("reading",JS_Accelerometer_eventHandler);InitializeAccelerometer(frequency)}}else if(JS_Accelerometer_frequencyRequest!=0){JS_Accelerometer_frequencyRequest=frequency}else{JS_Accelerometer_frequencyRequest=frequency;navigator.permissions.query({name:"accelerometer"}).then(function(result){if(result.state==="granted"){InitializeAccelerometer(JS_Accelerometer_frequencyRequest)}else{warnOnce("No permission to use Accelerometer.")}JS_Accelerometer_frequencyRequest=0})}}function JS_DeviceMotion_remove(){if(JS_Accelerometer_callback==0&&JS_LinearAccelerationSensor_callback==0&&JS_GravitySensor_callback==0&&JS_Gyroscope_callback==0){window.removeEventListener("devicemotion",JS_DeviceOrientation_eventHandler)}}function _JS_Accelerometer_Stop(){if(JS_Accelerometer){if(typeof GravitySensor!=="undefined"||JS_GravitySensor_callback==0){JS_Accelerometer.stop();JS_Accelerometer.removeEventListener("reading",JS_Accelerometer_eventHandler);JS_Accelerometer=null}JS_Accelerometer_callback=0;JS_Accelerometer_frequency=0}else if(JS_Accelerometer_callback!=0){JS_Accelerometer_callback=0;JS_DeviceMotion_remove()}}function _JS_Cursor_SetImage(ptr,length){var binary="";for(var i=0;i>2]=viewportX-rect.left;HEAPU32[targetY>>2]=viewportY-rect.top}function stringToNewUTF8(jsString){var length=lengthBytesUTF8(jsString)+1;var cString=_malloc(length);stringToUTF8(jsString,cString,length);return cString}function _JS_DOM_UnityCanvasSelector(){if(!_JS_DOM_UnityCanvasSelector.ptr){var canvasId=Module["canvas"]?Module["canvas"].id:"unity-canvas";var canvasSelector="#"+jsDomCssEscapeId(canvasId);_JS_DOM_UnityCanvasSelector.ptr=stringToNewUTF8(canvasSelector)}return _JS_DOM_UnityCanvasSelector.ptr}var fs={numPendingSync:0,syncInternal:1e3,syncInProgress:false,sync:function(onlyPendingSync){if(onlyPendingSync){if(fs.numPendingSync==0)return}else if(fs.syncInProgress){fs.numPendingSync++;return}fs.syncInProgress=true;FS.syncfs(false,function(err){fs.syncInProgress=false});fs.numPendingSync=0}};function _JS_FileSystem_Initialize(){Module.setInterval(function(){fs.sync(true)},fs.syncInternal)}function _JS_FileSystem_Sync(){fs.sync(false)}function _JS_Focus_Window(){var activeElem=document.activeElement;var canvasId=Module["canvas"]?Module["canvas"].id:"unity-canvas";var canvasSelector="#"+jsDomCssEscapeId(canvasId);var canvas=document.querySelector(canvasSelector);if(activeElem!=canvas&&activeElem!=window&&activeElem!=document.body){window.focus()}}var JS_GravitySensor=null;function _JS_GravitySensor_IsRunning(){return typeof GravitySensor!=="undefined"?JS_GravitySensor&&JS_GravitySensor.activated:JS_GravitySensor_callback!=0}function JS_GravitySensor_eventHandler(){if(JS_GravitySensor_callback!=0)dynCall_vfff(JS_GravitySensor_callback,JS_GravitySensor.x*JS_Accelerometer_multiplier,JS_GravitySensor.y*JS_Accelerometer_multiplier,JS_GravitySensor.z*JS_Accelerometer_multiplier)}var JS_GravitySensor_frequencyRequest=0;var JS_LinearAccelerationSensor=null;function JS_LinearAccelerationSensor_eventHandler(){var linearAccelerationValue={x:JS_LinearAccelerationSensor.x*JS_Accelerometer_multiplier,y:JS_LinearAccelerationSensor.y*JS_Accelerometer_multiplier,z:JS_LinearAccelerationSensor.z*JS_Accelerometer_multiplier};if(JS_LinearAccelerationSensor_callback!=0)dynCall_vfff(JS_LinearAccelerationSensor_callback,linearAccelerationValue.x,linearAccelerationValue.y,linearAccelerationValue.z);if(JS_GravitySensor_callback!=0&&typeof GravitySensor==="undefined"){var gravityValue=JS_ComputeGravity(JS_Accelerometer_lastValue,linearAccelerationValue);dynCall_vfff(JS_GravitySensor_callback,gravityValue.x,gravityValue.y,gravityValue.z)}}var JS_LinearAccelerationSensor_frequencyRequest=0;var JS_LinearAccelerationSensor_frequency=0;function _JS_LinearAccelerationSensor_Start(callback,frequency){JS_DefineAccelerometerMultiplier();if(typeof LinearAccelerationSensor==="undefined"){JS_DeviceMotion_add();if(callback!=0)JS_LinearAccelerationSensor_callback=callback;return}if(callback!=0)JS_LinearAccelerationSensor_callback=callback;function InitializeLinearAccelerationSensor(frequency){JS_LinearAccelerationSensor=new LinearAccelerationSensor({frequency:frequency,referenceFrame:"device"});JS_LinearAccelerationSensor.addEventListener("reading",JS_LinearAccelerationSensor_eventHandler);JS_LinearAccelerationSensor.addEventListener("error",function(e){warnOnce(e.error?e.error:e)});JS_LinearAccelerationSensor.start();JS_LinearAccelerationSensor_frequency=frequency}if(JS_LinearAccelerationSensor){if(JS_LinearAccelerationSensor_frequency!=frequency){JS_LinearAccelerationSensor.stop();JS_LinearAccelerationSensor.removeEventListener("reading",JS_LinearAccelerationSensor_eventHandler);InitializeLinearAccelerationSensor(frequency)}}else if(JS_LinearAccelerationSensor_frequencyRequest!=0){JS_LinearAccelerationSensor_frequencyRequest=frequency}else{JS_LinearAccelerationSensor_frequencyRequest=frequency;navigator.permissions.query({name:"accelerometer"}).then(function(result){if(result.state==="granted"){InitializeLinearAccelerationSensor(JS_LinearAccelerationSensor_frequencyRequest)}else{warnOnce("No permission to use LinearAccelerationSensor.")}JS_LinearAccelerationSensor_frequencyRequest=0})}}function _JS_GravitySensor_Start(callback,frequency){if(typeof GravitySensor==="undefined"){_JS_Accelerometer_Start(0,Math.max(frequency,JS_Accelerometer_frequency));_JS_LinearAccelerationSensor_Start(0,Math.max(frequency,JS_LinearAccelerationSensor_frequency));JS_GravitySensor_callback=callback;return}JS_DefineAccelerometerMultiplier();JS_GravitySensor_callback=callback;function InitializeGravitySensor(frequency){JS_GravitySensor=new GravitySensor({frequency:frequency,referenceFrame:"device"});JS_GravitySensor.addEventListener("reading",JS_GravitySensor_eventHandler);JS_GravitySensor.addEventListener("error",function(e){warnOnce(e.error?e.error:e)});JS_GravitySensor.start()}if(JS_GravitySensor){JS_GravitySensor.stop();JS_GravitySensor.removeEventListener("reading",JS_GravitySensor_eventHandler);InitializeGravitySensor(frequency)}else if(JS_GravitySensor_frequencyRequest!=0){JS_GravitySensor_frequencyRequest=frequency}else{JS_GravitySensor_frequencyRequest=frequency;navigator.permissions.query({name:"accelerometer"}).then(function(result){if(result.state==="granted"){InitializeGravitySensor(JS_GravitySensor_frequencyRequest)}else{warnOnce("No permission to use GravitySensor.")}JS_GravitySensor_frequencyRequest=0})}}function _JS_LinearAccelerationSensor_Stop(){if(JS_LinearAccelerationSensor){if(typeof GravitySensor!=="undefined"||JS_GravitySensor_callback==0){JS_LinearAccelerationSensor.stop();JS_LinearAccelerationSensor.removeEventListener("reading",JS_LinearAccelerationSensor_eventHandler);JS_LinearAccelerationSensor=null}JS_LinearAccelerationSensor_callback=0;JS_LinearAccelerationSensor_frequency=0}else if(JS_LinearAccelerationSensor_callback!=0){JS_LinearAccelerationSensor_callback=0;JS_DeviceMotion_remove()}}function _JS_GravitySensor_Stop(){JS_GravitySensor_callback=0;if(typeof GravitySensor==="undefined"){if(JS_Accelerometer_callback==0)_JS_Accelerometer_Stop();if(JS_LinearAccelerationSensor_callback==0)_JS_LinearAccelerationSensor_Stop();return}if(JS_GravitySensor){JS_GravitySensor.stop();JS_GravitySensor.removeEventListener("reading",JS_GravitySensor_eventHandler);JS_GravitySensor=null}}var JS_Gyroscope=null;function _JS_Gyroscope_IsRunning(){return JS_Gyroscope&&JS_Gyroscope.activated||JS_Gyroscope_callback!=0}function JS_Gyroscope_eventHandler(){if(JS_Gyroscope_callback!=0)dynCall_vfff(JS_Gyroscope_callback,JS_Gyroscope.x,JS_Gyroscope.y,JS_Gyroscope.z)}var JS_Gyroscope_frequencyRequest=0;function _JS_Gyroscope_Start(callback,frequency){if(typeof Gyroscope==="undefined"){JS_DeviceMotion_add();JS_Gyroscope_callback=callback;return}JS_Gyroscope_callback=callback;function InitializeGyroscope(frequency){JS_Gyroscope=new Gyroscope({frequency:frequency,referenceFrame:"device"});JS_Gyroscope.addEventListener("reading",JS_Gyroscope_eventHandler);JS_Gyroscope.addEventListener("error",function(e){warnOnce(e.error?e.error:e)});JS_Gyroscope.start()}if(JS_Gyroscope){JS_Gyroscope.stop();JS_Gyroscope.removeEventListener("reading",JS_Gyroscope_eventHandler);InitializeGyroscope(frequency)}else if(JS_Gyroscope_frequencyRequest!=0){JS_Gyroscope_frequencyRequest=frequency}else{JS_Gyroscope_frequencyRequest=frequency;navigator.permissions.query({name:"gyroscope"}).then(function(result){if(result.state==="granted"){InitializeGyroscope(JS_Gyroscope_frequencyRequest)}else{warnOnce("No permission to use Gyroscope.")}JS_Gyroscope_frequencyRequest=0})}}function _JS_Gyroscope_Stop(){if(JS_Gyroscope){JS_Gyroscope.stop();JS_Gyroscope.removeEventListener("reading",JS_Gyroscope_eventHandler);JS_Gyroscope=null;JS_Gyroscope_callback=0}else if(JS_Gyroscope_callback!=0){JS_Gyroscope_callback=0;JS_DeviceMotion_remove()}}function _JS_LinearAccelerationSensor_IsRunning(){return JS_LinearAccelerationSensor&&JS_LinearAccelerationSensor.activated||JS_LinearAccelerationSensor_callback!=0}function _JS_Log_Dump(ptr,type){var str=UTF8ToString(ptr);if(typeof dump=="function")dump(str);switch(type){case 0:case 1:case 4:console.error(str);return;case 2:console.warn(str);return;case 3:case 5:console.log(str);return;default:console.error("Unknown console message type!");console.error(str)}}function _JS_Log_StackTrace(buffer,bufferSize){var trace=stackTrace();if(buffer)stringToUTF8(trace,buffer,bufferSize);return lengthBytesUTF8(trace)}var JS_OrientationSensor=null;var JS_OrientationSensor_callback=0;function _JS_OrientationSensor_IsRunning(){return JS_OrientationSensor&&JS_OrientationSensor.activated||JS_OrientationSensor_callback!=0}function JS_OrientationSensor_eventHandler(){if(JS_OrientationSensor_callback!=0)dynCall_vffff(JS_OrientationSensor_callback,JS_OrientationSensor.quaternion[0],JS_OrientationSensor.quaternion[1],JS_OrientationSensor.quaternion[2],JS_OrientationSensor.quaternion[3])}var JS_OrientationSensor_frequencyRequest=0;function JS_DeviceOrientation_eventHandler(event){if(JS_OrientationSensor_callback){var degToRad=Math.PI/180;var x=event.beta*degToRad;var y=event.gamma*degToRad;var z=event.alpha*degToRad;var cx=Math.cos(x/2);var sx=Math.sin(x/2);var cy=Math.cos(y/2);var sy=Math.sin(y/2);var cz=Math.cos(z/2);var sz=Math.sin(z/2);var qx=sx*cy*cz-cx*sy*sz;var qy=cx*sy*cz+sx*cy*sz;var qz=cx*cy*sz+sx*sy*cz;var qw=cx*cy*cz-sx*sy*sz;dynCall_vffff(JS_OrientationSensor_callback,qx,qy,qz,qw)}}function _JS_OrientationSensor_Start(callback,frequency){if(typeof RelativeOrientationSensor==="undefined"){if(JS_OrientationSensor_callback==0){JS_OrientationSensor_callback=callback;JS_RequestDeviceSensorPermissions(1);window.addEventListener("deviceorientation",JS_DeviceOrientation_eventHandler)}return}JS_OrientationSensor_callback=callback;function InitializeOrientationSensor(frequency){JS_OrientationSensor=new RelativeOrientationSensor({frequency:frequency,referenceFrame:"device"});JS_OrientationSensor.addEventListener("reading",JS_OrientationSensor_eventHandler);JS_OrientationSensor.addEventListener("error",function(e){warnOnce(e.error?e.error:e)});JS_OrientationSensor.start()}if(JS_OrientationSensor){JS_OrientationSensor.stop();JS_OrientationSensor.removeEventListener("reading",JS_OrientationSensor_eventHandler);InitializeOrientationSensor(frequency)}else if(JS_OrientationSensor_frequencyRequest!=0){JS_OrientationSensor_frequencyRequest=frequency}else{JS_OrientationSensor_frequencyRequest=frequency;Promise.all([navigator.permissions.query({name:"accelerometer"}),navigator.permissions.query({name:"gyroscope"})]).then(function(results){if(results.every(function(result){return result.state==="granted"})){InitializeOrientationSensor(JS_OrientationSensor_frequencyRequest)}else{warnOnce("No permissions to use RelativeOrientationSensor.")}JS_OrientationSensor_frequencyRequest=0})}}function _JS_OrientationSensor_Stop(){if(JS_OrientationSensor){JS_OrientationSensor.stop();JS_OrientationSensor.removeEventListener("reading",JS_OrientationSensor_eventHandler);JS_OrientationSensor=null}else if(JS_OrientationSensor_callback!=0){window.removeEventListener("deviceorientation",JS_DeviceOrientation_eventHandler)}JS_OrientationSensor_callback=0}function _JS_RequestDeviceSensorPermissionsOnTouch(){if(JS_DeviceSensorPermissions==0)return;JS_RequestDeviceSensorPermissions(JS_DeviceSensorPermissions)}function _JS_RunQuitCallbacks(){Module.QuitCleanup()}var JS_ScreenOrientation_callback=0;function JS_ScreenOrientation_eventHandler(){if(JS_ScreenOrientation_callback)dynCall_viii(JS_ScreenOrientation_callback,window.innerWidth,window.innerHeight,screen.orientation?screen.orientation.angle:window.orientation)}function _JS_ScreenOrientation_DeInit(){JS_ScreenOrientation_callback=0;window.removeEventListener("resize",JS_ScreenOrientation_eventHandler);if(screen.orientation){screen.orientation.removeEventListener("change",JS_ScreenOrientation_eventHandler)}}function _JS_ScreenOrientation_Init(callback){if(!JS_ScreenOrientation_callback){if(screen.orientation){screen.orientation.addEventListener("change",JS_ScreenOrientation_eventHandler)}window.addEventListener("resize",JS_ScreenOrientation_eventHandler);JS_ScreenOrientation_callback=callback;setTimeout(JS_ScreenOrientation_eventHandler,0)}}var JS_ScreenOrientation_requestedLockType=-1;var JS_ScreenOrientation_appliedLockType=-1;var JS_ScreenOrientation_timeoutID=-1;function _JS_ScreenOrientation_Lock(orientationLockType){if(!screen.orientation){return}function applyLock(){JS_ScreenOrientation_appliedLockType=JS_ScreenOrientation_requestedLockType;var screenOrientations=["any",0,"landscape","portrait","portrait-primary","portrait-secondary","landscape-primary","landscape-secondary"];var type=screenOrientations[JS_ScreenOrientation_appliedLockType];screen.orientation.lock(type).then(function(){if(JS_ScreenOrientation_requestedLockType!=JS_ScreenOrientation_appliedLockType){JS_ScreenOrientation_timeoutID=setTimeout(applyLock,0)}else{JS_ScreenOrientation_timeoutID=-1}}).catch(function(err){warnOnce(err);JS_ScreenOrientation_timeoutID=-1})}JS_ScreenOrientation_requestedLockType=orientationLockType;if(JS_ScreenOrientation_timeoutID==-1&&orientationLockType!=JS_ScreenOrientation_appliedLockType){JS_ScreenOrientation_timeoutID=setTimeout(applyLock,0)}}var WEBAudio={audioInstanceIdCounter:0,audioInstances:{},audioContext:null,audioWebEnabled:0,audioCache:[],pendingAudioSources:{}};function jsAudioMixinSetPitch(source){source.estimatePlaybackPosition=function(){var t=(WEBAudio.audioContext.currentTime-source.playbackStartTime)*source.playbackRate.value;if(source.loop&&t>=source.loopStart){t=(t-source.loopStart)%(source.loopEnd-source.loopStart)+source.loopStart}return t};source.setPitch=function(newPitch){var curPosition=source.estimatePlaybackPosition();if(curPosition>=0){source.playbackStartTime=WEBAudio.audioContext.currentTime-curPosition/newPitch}if(source.playbackRate.value!==newPitch)source.playbackRate.value=newPitch}}function jsAudioCreateUncompressedSoundClip(buffer,error){var soundClip={buffer:buffer,error:error};soundClip.release=function(){};soundClip.getLength=function(){if(!this.buffer){console.log("Trying to get length of sound which is not loaded.");return 0}var sampleRateRatio=44100/this.buffer.sampleRate;return this.buffer.length*sampleRateRatio};soundClip.getData=function(ptr,length){if(!this.buffer){console.log("Trying to get data of sound which is not loaded.");return 0}var startOutputBuffer=ptr>>2;var output=HEAPF32.subarray(startOutputBuffer,startOutputBuffer+(length>>2));var numMaxSamples=Math.floor((length>>2)/this.buffer.numberOfChannels);var numReadSamples=Math.min(this.buffer.length,numMaxSamples);for(var i=0;istartDelayThresholdMS){source.playTimeout=setTimeout(function(){source.playTimeout=null;source._startPlayback(offset)},startDelayMS)}else{source._startPlayback(offset)}};source.stop=function(stopTime){if(typeof stopTime==="undefined"){stopTime=WEBAudio.audioContext.currentTime}var stopDelayThresholdMS=4;var stopDelayMS=(stopTime-WEBAudio.audioContext.currentTime)*1e3;if(stopDelayMS>stopDelayThresholdMS){setTimeout(function(){source._pauseMediaElement()},stopDelayMS)}else{source._pauseMediaElement()}};jsAudioMixinSetPitch(source);return source};return soundClip}function _JS_Sound_Load(ptr,length,decompress){if(WEBAudio.audioWebEnabled==0)return 0;var audioData=HEAPU8.buffer.slice(ptr,ptr+length);if(length<131072)decompress=1;var sound;if(decompress){sound=jsAudioCreateUncompressedSoundClipFromCompressedAudio(audioData)}else{sound=jsAudioCreateCompressedSoundClip(audioData)}WEBAudio.audioInstances[++WEBAudio.audioInstanceIdCounter]=sound;return WEBAudio.audioInstanceIdCounter}function jsAudioCreateUncompressedSoundClipFromPCM(channels,length,sampleRate,ptr){var buffer=WEBAudio.audioContext.createBuffer(channels,length,sampleRate);for(var i=0;i>2)+length*i;var copyToChannel=buffer["copyToChannel"]||function(source,channelNumber,startInChannel){var clipped=source.subarray(0,Math.min(source.length,this.length-(startInChannel|0)));this.getChannelData(channelNumber|0).set(clipped,startInChannel|0)};copyToChannel.apply(buffer,[HEAPF32.subarray(offs,offs+length),i,0])}return jsAudioCreateUncompressedSoundClip(buffer,false)}function _JS_Sound_Load_PCM(channels,length,sampleRate,ptr){if(WEBAudio.audioWebEnabled==0)return 0;var sound=jsAudioCreateUncompressedSoundClipFromPCM(channels,length,sampleRate,ptr);WEBAudio.audioInstances[++WEBAudio.audioInstanceIdCounter]=sound;return WEBAudio.audioInstanceIdCounter}function _JS_Sound_Play(bufferInstance,channelInstance,offset,delay){if(WEBAudio.audioWebEnabled==0)return;_JS_Sound_Stop(channelInstance,0);var soundClip=WEBAudio.audioInstances[bufferInstance];var channel=WEBAudio.audioInstances[channelInstance];if(!soundClip){console.log("Trying to play sound which is not loaded.");return}try{channel.playSoundClip(soundClip,WEBAudio.audioContext.currentTime+delay,offset)}catch(error){console.error("playSoundClip error. Exception: "+e)}}function _JS_Sound_ReleaseInstance(instance){var object=WEBAudio.audioInstances[instance];if(object){object.release()}delete WEBAudio.audioInstances[instance]}function _JS_Sound_ResumeIfNeeded(){if(WEBAudio.audioWebEnabled==0)return;if(WEBAudio.audioContext.state==="suspended")WEBAudio.audioContext.resume()}function _JS_Sound_Set3D(channelInstance,threeD){var channel=WEBAudio.audioInstances[channelInstance];channel.set3D(threeD)}function _JS_Sound_SetListenerOrientation(x,y,z,xUp,yUp,zUp){if(WEBAudio.audioWebEnabled==0)return;x=-x;y=-y;z=-z;var l=WEBAudio.audioContext.listener;if(l.forwardX){if(l.forwardX.value!==x)l.forwardX.value=x;if(l.forwardY.value!==y)l.forwardY.value=y;if(l.forwardZ.value!==z)l.forwardZ.value=z;if(l.upX.value!==x)l.upX.value=x;if(l.upY.value!==y)l.upY.value=y;if(l.upZ.value!==z)l.upZ.value=z}else if(l._forwardX!==x||l._forwardY!==y||l._forwardZ!==z||l._upX!==xUp||l._upY!==yUp||l._upZ!==zUp){l.setOrientation(x,y,z,xUp,yUp,zUp);l._forwardX=x;l._forwardY=y;l._forwardZ=z;l._upX=xUp;l._upY=yUp;l._upZ=zUp}}function _JS_Sound_SetListenerPosition(x,y,z){if(WEBAudio.audioWebEnabled==0)return;var l=WEBAudio.audioContext.listener;if(l.positionX){if(l.positionX.value!==x)l.positionX.value=x;if(l.positionY.value!==y)l.positionY.value=y;if(l.positionZ.value!==z)l.positionZ.value=z}else if(l._positionX!==x||l._positionY!==y||l._positionZ!==z){l.setPosition(x,y,z);l._positionX=x;l._positionY=y;l._positionZ=z}}function _JS_Sound_SetLoop(channelInstance,loop){if(WEBAudio.audioWebEnabled==0)return;var channel=WEBAudio.audioInstances[channelInstance];channel.setLoop(loop)}function _JS_Sound_SetLoopPoints(channelInstance,loopStart,loopEnd){if(WEBAudio.audioWebEnabled==0)return;var channel=WEBAudio.audioInstances[channelInstance];channel.setLoopPoints(loopStart,loopEnd)}function _JS_Sound_SetPaused(channelInstance,paused){if(WEBAudio.audioWebEnabled==0)return;var channel=WEBAudio.audioInstances[channelInstance];if(paused!=channel.isPaused()){if(paused)channel.pause();else channel.resume()}}function _JS_Sound_SetPitch(channelInstance,v){if(WEBAudio.audioWebEnabled==0)return;try{var channel=WEBAudio.audioInstances[channelInstance];channel.setPitch(v)}catch(e){console.error("JS_Sound_SetPitch(channel="+channelInstance+", pitch="+v+") threw an exception: "+e)}}function _JS_Sound_SetPosition(channelInstance,x,y,z){if(WEBAudio.audioWebEnabled==0)return;var channel=WEBAudio.audioInstances[channelInstance];channel.setPosition(x,y,z)}function _JS_Sound_SetVolume(channelInstance,v){if(WEBAudio.audioWebEnabled==0)return;try{var channel=WEBAudio.audioInstances[channelInstance];channel.setVolume(v)}catch(e){console.error("JS_Sound_SetVolume(channel="+channelInstance+", volume="+v+") threw an exception: "+e)}}function _JS_Sound_Stop(channelInstance,delay){if(WEBAudio.audioWebEnabled==0)return;var channel=WEBAudio.audioInstances[channelInstance];channel.stop(delay)}function _JS_SystemInfo_GetCanvasClientSize(domElementSelector,outWidth,outHeight){var selector=UTF8ToString(domElementSelector);var canvas=selector=="#canvas"?Module["canvas"]:document.querySelector(selector);var w=0,h=0;if(canvas){var size=canvas.getBoundingClientRect();w=size.width;h=size.height}HEAPF64[outWidth>>3]=w;HEAPF64[outHeight>>3]=h}function _JS_SystemInfo_GetDocumentURL(buffer,bufferSize){if(buffer)stringToUTF8(document.URL,buffer,bufferSize);return lengthBytesUTF8(document.URL)}function _JS_SystemInfo_GetGPUInfo(buffer,bufferSize){var gpuinfo=Module.SystemInfo.gpu;if(buffer)stringToUTF8(gpuinfo,buffer,bufferSize);return lengthBytesUTF8(gpuinfo)}function _JS_SystemInfo_GetMatchWebGLToCanvasSize(){return Module.matchWebGLToCanvasSize||Module.matchWebGLToCanvasSize===undefined}function _JS_SystemInfo_GetMemory(){return HEAPU8.length/(1024*1024)}function _JS_SystemInfo_GetOS(buffer,bufferSize){var browser=Module.SystemInfo.os+" "+Module.SystemInfo.osVersion;if(buffer)stringToUTF8(browser,buffer,bufferSize);return lengthBytesUTF8(browser)}function _JS_SystemInfo_GetPreferredDevicePixelRatio(){return Module.matchWebGLToCanvasSize==false?1:Module.devicePixelRatio||window.devicePixelRatio||1}function _JS_SystemInfo_GetScreenSize(outWidth,outHeight){HEAPF64[outWidth>>3]=Module.SystemInfo.width;HEAPF64[outHeight>>3]=Module.SystemInfo.height}function _JS_SystemInfo_HasAstcHdr(){var ext=GLctx.getExtension("WEBGL_compressed_texture_astc");if(ext&&ext.getSupportedProfiles){return ext.getSupportedProfiles().includes("hdr")}return false}function _JS_SystemInfo_HasCursorLock(){return Module.SystemInfo.hasCursorLock}function _JS_SystemInfo_HasFullscreen(){return Module.SystemInfo.hasFullscreen}function _JS_SystemInfo_HasWebGL(){return Module.SystemInfo.hasWebGL}function _JS_SystemInfo_IsMobile(){return Module.SystemInfo.mobile}function _JS_UnityEngineShouldQuit(){return!!Module.shouldQuit}var ExceptionInfoAttrs={DESTRUCTOR_OFFSET:0,REFCOUNT_OFFSET:4,TYPE_OFFSET:8,CAUGHT_OFFSET:12,RETHROWN_OFFSET:13,SIZE:16};function ___cxa_allocate_exception(size){return _malloc(size+ExceptionInfoAttrs.SIZE)+ExceptionInfoAttrs.SIZE}function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-ExceptionInfoAttrs.SIZE;this.set_type=function(type){HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]=type};this.get_type=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]};this.set_destructor=function(destructor){HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]=destructor};this.get_destructor=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]};this.set_refcount=function(refcount){HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=refcount};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]!=0};this.init=function(type,destructor){this.set_type(type);this.set_destructor(destructor);this.set_refcount(0);this.set_caught(false);this.set_rethrown(false)};this.add_ref=function(){var value=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=value+1};this.release_ref=function(){var prev=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=prev-1;return prev===1}}function CatchInfo(ptr){this.free=function(){_free(this.ptr);this.ptr=0};this.set_base_ptr=function(basePtr){HEAP32[this.ptr>>2]=basePtr};this.get_base_ptr=function(){return HEAP32[this.ptr>>2]};this.set_adjusted_ptr=function(adjustedPtr){var ptrSize=4;HEAP32[this.ptr+ptrSize>>2]=adjustedPtr};this.get_adjusted_ptr=function(){var ptrSize=4;return HEAP32[this.ptr+ptrSize>>2]};this.get_exception_ptr=function(){var isPointer=___cxa_is_pointer_type(this.get_exception_info().get_type());if(isPointer){return HEAP32[this.get_base_ptr()>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.get_base_ptr()};this.get_exception_info=function(){return new ExceptionInfo(this.get_base_ptr())};if(ptr===undefined){this.ptr=_malloc(8);this.set_adjusted_ptr(0)}else{this.ptr=ptr}}var exceptionCaught=[];function exception_addRef(info){info.add_ref()}var uncaughtExceptionCount=0;function ___cxa_begin_catch(ptr){var catchInfo=new CatchInfo(ptr);var info=catchInfo.get_exception_info();if(!info.get_caught()){info.set_caught(true);uncaughtExceptionCount--}info.set_rethrown(false);exceptionCaught.push(catchInfo);exception_addRef(info);return catchInfo.get_exception_ptr()}var exceptionLast=0;function ___cxa_free_exception(ptr){return _free(new ExceptionInfo(ptr).ptr)}function exception_decRef(info){if(info.release_ref()&&!info.get_rethrown()){var destructor=info.get_destructor();if(destructor){(function(a1){return dynCall_ii.apply(null,[destructor,a1])})(info.excPtr)}___cxa_free_exception(info.excPtr)}}function ___cxa_end_catch(){_setThrew(0);var catchInfo=exceptionCaught.pop();exception_decRef(catchInfo.get_exception_info());catchInfo.free();exceptionLast=0}function ___resumeException(catchInfoPtr){var catchInfo=new CatchInfo(catchInfoPtr);var ptr=catchInfo.get_base_ptr();if(!exceptionLast){exceptionLast=ptr}catchInfo.free();throw ptr}function ___cxa_find_matching_catch_2(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_find_matching_catch_3(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_find_matching_catch_4(){var thrown=exceptionLast;if(!thrown){setTempRet0(0);return 0|0}var info=new ExceptionInfo(thrown);var thrownType=info.get_type();var catchInfo=new CatchInfo;catchInfo.set_base_ptr(thrown);if(!thrownType){setTempRet0(0);return catchInfo.ptr|0}var typeArray=Array.prototype.slice.call(arguments);var stackTop=stackSave();var exceptionThrowBuf=stackAlloc(4);HEAP32[exceptionThrowBuf>>2]=thrown;for(var i=0;i>2];if(thrown!==adjusted){catchInfo.set_adjusted_ptr(adjusted)}setTempRet0(caughtType);return catchInfo.ptr|0}}stackRestore(stackTop);setTempRet0(thrownType);return catchInfo.ptr|0}function ___cxa_rethrow(){var catchInfo=exceptionCaught.pop();if(!catchInfo){abort("no exception to throw")}var info=catchInfo.get_exception_info();var ptr=catchInfo.get_base_ptr();if(!info.get_rethrown()){exceptionCaught.push(catchInfo);info.set_rethrown(true);info.set_caught(false);uncaughtExceptionCount++}else{catchInfo.free()}exceptionLast=ptr;throw ptr}function ___cxa_throw(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw ptr}function _gmtime_r(time,tmPtr){var date=new Date(HEAP32[time>>2]*1e3);HEAP32[tmPtr>>2]=date.getUTCSeconds();HEAP32[tmPtr+4>>2]=date.getUTCMinutes();HEAP32[tmPtr+8>>2]=date.getUTCHours();HEAP32[tmPtr+12>>2]=date.getUTCDate();HEAP32[tmPtr+16>>2]=date.getUTCMonth();HEAP32[tmPtr+20>>2]=date.getUTCFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getUTCDay();HEAP32[tmPtr+36>>2]=0;HEAP32[tmPtr+32>>2]=0;var start=Date.UTC(date.getUTCFullYear(),0,1,0,0,0,0);var yday=(date.getTime()-start)/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>2]=yday;if(!_gmtime_r.GMTString)_gmtime_r.GMTString=allocateUTF8("GMT");HEAP32[tmPtr+40>>2]=_gmtime_r.GMTString;return tmPtr}function ___gmtime_r(a0,a1){return _gmtime_r(a0,a1)}function _tzset(){if(_tzset.called)return;_tzset.called=true;var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAP32[__get_timezone()>>2]=stdTimezoneOffset*60;HEAP32[__get_daylight()>>2]=Number(winterOffset!=summerOffset);function extractZone(date){var match=date.toTimeString().match(/\(([A-Za-z ]+)\)$/);return match?match[1]:"GMT"}var winterName=extractZone(winter);var summerName=extractZone(summer);var winterNamePtr=allocateUTF8(winterName);var summerNamePtr=allocateUTF8(summerName);if(summerOffset>2]=winterNamePtr;HEAP32[__get_tzname()+4>>2]=summerNamePtr}else{HEAP32[__get_tzname()>>2]=summerNamePtr;HEAP32[__get_tzname()+4>>2]=winterNamePtr}}function _localtime_r(time,tmPtr){_tzset();var date=new Date(HEAP32[time>>2]*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var start=new Date(date.getFullYear(),0,1);var yday=(date.getTime()-start.getTime())/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(date.getTimezoneOffset()*60);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>2]=dst;var zonePtr=HEAP32[__get_tzname()+(dst?4:0)>>2];HEAP32[tmPtr+40>>2]=zonePtr;return tmPtr}function ___localtime_r(a0,a1){return _localtime_r(a0,a1)}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};function getRandomDevice(){if(typeof crypto==="object"&&typeof crypto["getRandomValues"]==="function"){var randomBuffer=new Uint8Array(1);return function(){crypto.getRandomValues(randomBuffer);return randomBuffer[0]}}else if(ENVIRONMENT_IS_NODE){try{var crypto_module=require("crypto");return function(){return crypto_module["randomBytes"](1)[0]}}catch(e){}}return function(){abort("randomDevice")}}var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:function(from,to){from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i0){result=buf.slice(0,bytesRead).toString("utf-8")}else{result=null}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}tty.input=intArrayFromString(result,true)}return tty.input.shift()},put_char:function(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};function mmapAlloc(size){var alignedSize=alignMemory(size,65536);var ptr=_malloc(alignedSize);while(size=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[44]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink:function(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir:function(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir:function(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink:function(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink:function(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read:function(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length8){throw new FS.ErrnoError(32)}var parts=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),false);var current=FS.root;var current_path="/";for(var i=0;i40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath:function(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?mount+"/"+path:mount+path}path=path?node.name+"/"+path:node.name;node=node.parent}},hashName:function(parentid,name){var hash=0;for(var i=0;i>>0)%FS.nameTable.length},hashAddNode:function(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode:function(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode:function(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode:function(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode:function(node){FS.hashRemoveNode(node)},isRoot:function(node){return node===node.parent},isMountpoint:function(node){return!!node.mounted},isFile:function(mode){return(mode&61440)===32768},isDir:function(mode){return(mode&61440)===16384},isLink:function(mode){return(mode&61440)===40960},isChrdev:function(mode){return(mode&61440)===8192},isBlkdev:function(mode){return(mode&61440)===24576},isFIFO:function(mode){return(mode&61440)===4096},isSocket:function(mode){return(mode&49152)===49152},flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:function(str){var flags=FS.flagModes[str];if(typeof flags==="undefined"){throw new Error("Unknown file open mode: "+str)}return flags},flagsToPermissionString:function(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions:function(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup:function(dir){var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate:function(dir,name){try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete:function(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen:function(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd:function(fd_start,fd_end){fd_start=fd_start||0;fd_end=fd_end||FS.MAX_OPEN_FDS;for(var fd=fd_start;fd<=fd_end;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStream:function(fd){return FS.streams[fd]},createStream:function(stream,fd_start,fd_end){if(!FS.FSStream){FS.FSStream=function(){};FS.FSStream.prototype={object:{get:function(){return this.node},set:function(val){this.node=val}},isRead:{get:function(){return(this.flags&2097155)!==1}},isWrite:{get:function(){return(this.flags&2097155)!==0}},isAppend:{get:function(){return this.flags&1024}}}}var newStream=new FS.FSStream;for(var p in stream){newStream[p]=stream[p]}stream=newStream;var fd=FS.nextfd(fd_start,fd_end);stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream:function(fd){FS.streams[fd]=null},chrdev_stream_ops:{open:function(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;if(stream.stream_ops.open){stream.stream_ops.open(stream)}},llseek:function(){throw new FS.ErrnoError(70)}},major:function(dev){return dev>>8},minor:function(dev){return dev&255},makedev:function(ma,mi){return ma<<8|mi},registerDevice:function(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:function(dev){return FS.devices[dev]},getMounts:function(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push.apply(check,m.mounts)}return mounts},syncfs:function(populate,callback){if(typeof populate==="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err("warning: "+FS.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work")}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(function(mount){if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount:function(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type:type,opts:opts,mountpoint:mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount:function(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(function(hash){var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup:function(parent,name){return parent.node_ops.lookup(parent,name)},mknod:function(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name||name==="."||name===".."){throw new FS.ErrnoError(28)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},create:function(path,mode){mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir:function(path,mode){mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree:function(path,mode){var dirs=path.split("/");var d="";for(var i=0;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]};LazyUint8Array.prototype.setDataGetter=function LazyUint8Array_setDataGetter(getter){this.getter=getter};LazyUint8Array.prototype.cacheLength=function LazyUint8Array_cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=function(from,to){if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);if(typeof Uint8Array!="undefined")xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}else{return intArrayFromString(xhr.responseText||"",true)}};var lazyArray=this;lazyArray.setDataGetter(function(chunkNum){var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]==="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]==="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true};if(typeof XMLHttpRequest!=="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;Object.defineProperties(lazyArray,{length:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._length}},chunkSize:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}});var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url:url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(function(key){var fn=node.stream_ops[key];stream_ops[key]=function forceLoadLazyFile(){FS.forceLoadFile(node);return fn.apply(null,arguments)}});stream_ops.read=function stream_ops_read(stream,buffer,offset,length,position){FS.forceLoadFile(node);var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i>2]=stat.dev;HEAP32[buf+4>>2]=0;HEAP32[buf+8>>2]=stat.ino;HEAP32[buf+12>>2]=stat.mode;HEAP32[buf+16>>2]=stat.nlink;HEAP32[buf+20>>2]=stat.uid;HEAP32[buf+24>>2]=stat.gid;HEAP32[buf+28>>2]=stat.rdev;HEAP32[buf+32>>2]=0;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAP32[buf+48>>2]=4096;HEAP32[buf+52>>2]=stat.blocks;HEAP32[buf+56>>2]=stat.atime.getTime()/1e3|0;HEAP32[buf+60>>2]=0;HEAP32[buf+64>>2]=stat.mtime.getTime()/1e3|0;HEAP32[buf+68>>2]=0;HEAP32[buf+72>>2]=stat.ctime.getTime()/1e3|0;HEAP32[buf+76>>2]=0;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+80>>2]=tempI64[0],HEAP32[buf+84>>2]=tempI64[1];return 0},doMsync:function(addr,stream,len,flags,offset){var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},doMkdir:function(path,mode){path=PATH.normalize(path);if(path[path.length-1]==="/")path=path.substr(0,path.length-1);FS.mkdir(path,mode,0);return 0},doMknod:function(path,mode,dev){switch(mode&61440){case 32768:case 8192:case 24576:case 4096:case 49152:break;default:return-28}FS.mknod(path,mode,dev);return 0},doReadlink:function(path,buf,bufsize){if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len]=endChar;return len},doAccess:function(path,amode){if(amode&~7){return-28}var node;var lookup=FS.lookupPath(path,{follow:true});node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0},doDup:function(path,flags,suggestFD){var suggest=FS.getStream(suggestFD);if(suggest)FS.close(suggest);return FS.open(path,flags,0,suggestFD,suggestFD).fd},doReadv:function(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAP32[iov+(i*8+4)>>2];var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2];var len=HEAP32[iov+(i*8+4)>>2];var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr}return ret},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},getStreamFromFD:function(fd){var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);return stream},get64:function(low,high){return low}};function ___sys__newselect(nfds,readfds,writefds,exceptfds,timeout){try{var total=0;var srcReadLow=readfds?HEAP32[readfds>>2]:0,srcReadHigh=readfds?HEAP32[readfds+4>>2]:0;var srcWriteLow=writefds?HEAP32[writefds>>2]:0,srcWriteHigh=writefds?HEAP32[writefds+4>>2]:0;var srcExceptLow=exceptfds?HEAP32[exceptfds>>2]:0,srcExceptHigh=exceptfds?HEAP32[exceptfds+4>>2]:0;var dstReadLow=0,dstReadHigh=0;var dstWriteLow=0,dstWriteHigh=0;var dstExceptLow=0,dstExceptHigh=0;var allLow=(readfds?HEAP32[readfds>>2]:0)|(writefds?HEAP32[writefds>>2]:0)|(exceptfds?HEAP32[exceptfds>>2]:0);var allHigh=(readfds?HEAP32[readfds+4>>2]:0)|(writefds?HEAP32[writefds+4>>2]:0)|(exceptfds?HEAP32[exceptfds+4>>2]:0);var check=function(fd,low,high,val){return fd<32?low&val:high&val};for(var fd=0;fd>2]=dstReadLow;HEAP32[readfds+4>>2]=dstReadHigh}if(writefds){HEAP32[writefds>>2]=dstWriteLow;HEAP32[writefds+4>>2]=dstWriteHigh}if(exceptfds){HEAP32[exceptfds>>2]=dstExceptLow;HEAP32[exceptfds+4>>2]=dstExceptHigh}return total}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_access(path,amode){try{path=SYSCALLS.getStr(path);return SYSCALLS.doAccess(path,amode)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_chmod(path,mode){try{path=SYSCALLS.getStr(path);FS.chmod(path,mode);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}var ERRNO_CODES={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};var SOCKFS={mount:function(mount){Module["websocket"]=Module["websocket"]&&"object"===typeof Module["websocket"]?Module["websocket"]:{};Module["websocket"]._callbacks={};Module["websocket"]["on"]=function(event,callback){if("function"===typeof callback){this._callbacks[event]=callback}return this};Module["websocket"].emit=function(event,param){if("function"===typeof this._callbacks[event]){this._callbacks[event].call(this,param)}};return FS.createNode(null,"/",16384|511,0)},createSocket:function(family,type,protocol){type&=~526336;var streaming=type==1;if(protocol){assert(streaming==(protocol==6))}var sock={family:family,type:type,protocol:protocol,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops};var name=SOCKFS.nextname();var node=FS.createNode(SOCKFS.root,name,49152,0);node.sock=sock;var stream=FS.createStream({path:name,node:node,flags:2,seekable:false,stream_ops:SOCKFS.stream_ops});sock.stream=stream;return sock},getSocket:function(fd){var stream=FS.getStream(fd);if(!stream||!FS.isSocket(stream.node.mode)){return null}return stream.node.sock},stream_ops:{poll:function(stream){var sock=stream.node.sock;return sock.sock_ops.poll(sock)},ioctl:function(stream,request,varargs){var sock=stream.node.sock;return sock.sock_ops.ioctl(sock,request,varargs)},read:function(stream,buffer,offset,length,position){var sock=stream.node.sock;var msg=sock.sock_ops.recvmsg(sock,length);if(!msg){return 0}buffer.set(msg.buffer,offset);return msg.buffer.length},write:function(stream,buffer,offset,length,position){var sock=stream.node.sock;return sock.sock_ops.sendmsg(sock,buffer,offset,length)},close:function(stream){var sock=stream.node.sock;sock.sock_ops.close(sock)}},nextname:function(){if(!SOCKFS.nextname.current){SOCKFS.nextname.current=0}return"socket["+SOCKFS.nextname.current+++"]"},websocket_sock_ops:{createPeer:function(sock,addr,port){var ws;if(typeof addr==="object"){ws=addr;addr=null;port=null}if(ws){if(ws._socket){addr=ws._socket.remoteAddress;port=ws._socket.remotePort}else{var result=/ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);if(!result){throw new Error("WebSocket URL must be in the format ws(s)://address:port")}addr=result[1];port=parseInt(result[2],10)}}else{try{var runtimeConfig=Module["websocket"]&&"object"===typeof Module["websocket"];var url="ws:#".replace("#","//");if(runtimeConfig){if("string"===typeof Module["websocket"]["url"]){url=Module["websocket"]["url"]}}if(url==="ws://"||url==="wss://"){var parts=addr.split("/");url=url+parts[0]+":"+port+"/"+parts.slice(1).join("/")}var subProtocols="binary";if(runtimeConfig){if("string"===typeof Module["websocket"]["subprotocol"]){subProtocols=Module["websocket"]["subprotocol"]}}var opts=undefined;if(subProtocols!=="null"){subProtocols=subProtocols.replace(/^ +| +$/g,"").split(/ *, */);opts=ENVIRONMENT_IS_NODE?{"protocol":subProtocols.toString()}:subProtocols}if(runtimeConfig&&null===Module["websocket"]["subprotocol"]){subProtocols="null";opts=undefined}var WebSocketConstructor;if(ENVIRONMENT_IS_NODE){WebSocketConstructor=require("ws")}else{WebSocketConstructor=WebSocket}ws=new WebSocketConstructor(url,opts);ws.binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(ERRNO_CODES.EHOSTUNREACH)}}var peer={addr:addr,port:port,socket:ws,dgram_send_queue:[]};SOCKFS.websocket_sock_ops.addPeer(sock,peer);SOCKFS.websocket_sock_ops.handlePeerEvents(sock,peer);if(sock.type===2&&typeof sock.sport!=="undefined"){peer.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(sock.sport&65280)>>8,sock.sport&255]))}return peer},getPeer:function(sock,addr,port){return sock.peers[addr+":"+port]},addPeer:function(sock,peer){sock.peers[peer.addr+":"+peer.port]=peer},removePeer:function(sock,peer){delete sock.peers[peer.addr+":"+peer.port]},handlePeerEvents:function(sock,peer){var first=true;var handleOpen=function(){Module["websocket"].emit("open",sock.stream.fd);try{var queued=peer.dgram_send_queue.shift();while(queued){peer.socket.send(queued);queued=peer.dgram_send_queue.shift()}}catch(e){peer.socket.close()}};function handleMessage(data){if(typeof data==="string"){var encoder=new TextEncoder;data=encoder.encode(data)}else{assert(data.byteLength!==undefined);if(data.byteLength==0){return}else{data=new Uint8Array(data)}}var wasfirst=first;first=false;if(wasfirst&&data.length===10&&data[0]===255&&data[1]===255&&data[2]===255&&data[3]===255&&data[4]==="p".charCodeAt(0)&&data[5]==="o".charCodeAt(0)&&data[6]==="r".charCodeAt(0)&&data[7]==="t".charCodeAt(0)){var newport=data[8]<<8|data[9];SOCKFS.websocket_sock_ops.removePeer(sock,peer);peer.port=newport;SOCKFS.websocket_sock_ops.addPeer(sock,peer);return}sock.recv_queue.push({addr:peer.addr,port:peer.port,data:data});Module["websocket"].emit("message",sock.stream.fd)}if(ENVIRONMENT_IS_NODE){peer.socket.on("open",handleOpen);peer.socket.on("message",function(data,flags){if(!flags.binary){return}handleMessage(new Uint8Array(data).buffer)});peer.socket.on("close",function(){Module["websocket"].emit("close",sock.stream.fd)});peer.socket.on("error",function(error){sock.error=ERRNO_CODES.ECONNREFUSED;Module["websocket"].emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])})}else{peer.socket.onopen=handleOpen;peer.socket.onclose=function(){Module["websocket"].emit("close",sock.stream.fd)};peer.socket.onmessage=function peer_socket_onmessage(event){handleMessage(event.data)};peer.socket.onerror=function(error){sock.error=ERRNO_CODES.ECONNREFUSED;Module["websocket"].emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])}}},poll:function(sock){if(sock.type===1&&sock.server){return sock.pending.length?64|1:0}var mask=0;var dest=sock.type===1?SOCKFS.websocket_sock_ops.getPeer(sock,sock.daddr,sock.dport):null;if(sock.recv_queue.length||!dest||dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=64|1}if(!dest||dest&&dest.socket.readyState===dest.socket.OPEN){mask|=4}if(dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=16}return mask},ioctl:function(sock,request,arg){switch(request){case 21531:var bytes=0;if(sock.recv_queue.length){bytes=sock.recv_queue[0].data.length}HEAP32[arg>>2]=bytes;return 0;default:return ERRNO_CODES.EINVAL}},close:function(sock){if(sock.server){try{sock.server.close()}catch(e){}sock.server=null}var peers=Object.keys(sock.peers);for(var i=0;i>2]=value;return value}function inetNtop4(addr){return(addr&255)+"."+(addr>>8&255)+"."+(addr>>16&255)+"."+(addr>>24&255)}function inetNtop6(ints){var str="";var word=0;var longest=0;var lastzero=0;var zstart=0;var len=0;var i=0;var parts=[ints[0]&65535,ints[0]>>16,ints[1]&65535,ints[1]>>16,ints[2]&65535,ints[2]>>16,ints[3]&65535,ints[3]>>16];var hasipv4=true;var v4part="";for(i=0;i<5;i++){if(parts[i]!==0){hasipv4=false;break}}if(hasipv4){v4part=inetNtop4(parts[6]|parts[7]<<16);if(parts[5]===-1){str="::ffff:";str+=v4part;return str}if(parts[5]===0){str="::";if(v4part==="0.0.0.0")v4part="";if(v4part==="0.0.0.1")v4part="1";str+=v4part;return str}}for(word=0;word<8;word++){if(parts[word]===0){if(word-lastzero>1){len=0}lastzero=word;len++}if(len>longest){longest=len;zstart=word-longest+1}}for(word=0;word<8;word++){if(longest>1){if(parts[word]===0&&word>=zstart&&word>1];var port=_ntohs(HEAPU16[sa+2>>1]);var addr;switch(family){case 2:if(salen!==16){return{errno:28}}addr=HEAP32[sa+4>>2];addr=inetNtop4(addr);break;case 10:if(salen!==28){return{errno:28}}addr=[HEAP32[sa+8>>2],HEAP32[sa+12>>2],HEAP32[sa+16>>2],HEAP32[sa+20>>2]];addr=inetNtop6(addr);break;default:return{errno:5}}return{family:family,addr:addr,port:port}}function getSocketAddress(addrp,addrlen,allowNull){if(allowNull&&addrp===0)return null;var info=readSockaddr(addrp,addrlen);if(info.errno)throw new FS.ErrnoError(info.errno);info.addr=DNS.lookup_addr(info.addr)||info.addr;return info}function ___sys_connect(fd,addr,addrlen){try{var sock=getSocketFromFD(fd);var info=getSocketAddress(addr,addrlen);sock.sock_ops.connect(sock,info.addr,info.port);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=SYSCALLS.get();if(arg<0){return-28}var newStream;newStream=FS.open(stream.path,stream.flags,0,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=SYSCALLS.get();stream.flags|=arg;return 0}case 12:{var arg=SYSCALLS.get();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0;case 16:case 8:return-28;case 9:setErrNo(28);return-1;default:{return-28}}}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_fstat64(fd,buf){try{var stream=SYSCALLS.getStreamFromFD(fd);return SYSCALLS.doStat(FS.stat,stream.path,buf)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_getcwd(buf,size){try{if(size===0)return-28;var cwd=FS.cwd();var cwdLengthInBytes=lengthBytesUTF8(cwd);if(size>>0,(tempDouble=id,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[dirp+pos>>2]=tempI64[0],HEAP32[dirp+pos+4>>2]=tempI64[1];tempI64=[(idx+1)*struct_size>>>0,(tempDouble=(idx+1)*struct_size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[dirp+pos+8>>2]=tempI64[0],HEAP32[dirp+pos+12>>2]=tempI64[1];HEAP16[dirp+pos+16>>1]=280;HEAP8[dirp+pos+18>>0]=type;stringToUTF8(name,dirp+pos+19,256);pos+=struct_size;idx+=1}FS.llseek(stream,idx*struct_size,0);return pos}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_getrusage(who,usage){try{_memset(usage,0,136);HEAP32[usage>>2]=1;HEAP32[usage+4>>2]=2;HEAP32[usage+8>>2]=3;HEAP32[usage+12>>2]=4;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_getegid32(){return 0}function ___sys_getuid32(){return ___sys_getegid32()}function ___sys_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:case 21505:{if(!stream.tty)return-59;return 0}case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:{if(!stream.tty)return-59;return 0}case 21519:{if(!stream.tty)return-59;var argp=SYSCALLS.get();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=SYSCALLS.get();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;return 0}case 21524:{if(!stream.tty)return-59;return 0}default:abort("bad ioctl syscall "+op)}}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.lstat,path,buf)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_mkdir(path,mode){try{path=SYSCALLS.getStr(path);return SYSCALLS.doMkdir(path,mode)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function syscallMmap2(addr,len,prot,flags,fd,off){off<<=12;var ptr;var allocated=false;if((flags&16)!==0&&addr%65536!==0){return-28}if((flags&32)!==0){ptr=_memalign(65536,len);if(!ptr)return-48;_memset(ptr,0,len);allocated=true}else{var info=FS.getStream(fd);if(!info)return-8;var res=FS.mmap(info,addr,len,off,prot,flags);ptr=res.ptr;allocated=res.allocated}SYSCALLS.mappings[ptr]={malloc:ptr,len:len,allocated:allocated,fd:fd,prot:prot,flags:flags,offset:off};return ptr}function ___sys_mmap2(addr,len,prot,flags,fd,off){try{return syscallMmap2(addr,len,prot,flags,fd,off)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function syscallMunmap(addr,len){if((addr|0)===-1||len===0){return-28}var info=SYSCALLS.mappings[addr];if(!info)return 0;if(len===info.len){var stream=FS.getStream(info.fd);if(stream){if(info.prot&2){SYSCALLS.doMsync(addr,stream,len,info.flags,info.offset)}FS.munmap(stream)}SYSCALLS.mappings[addr]=null;if(info.allocated){_free(info.malloc)}}return 0}function ___sys_munmap(addr,len){try{return syscallMunmap(addr,len)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_open(path,flags,varargs){SYSCALLS.varargs=varargs;try{var pathname=SYSCALLS.getStr(path);var mode=varargs?SYSCALLS.get():0;var stream=FS.open(pathname,flags,mode);return stream.fd}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_readlink(path,buf,bufsize){try{path=SYSCALLS.getStr(path);return SYSCALLS.doReadlink(path,buf,bufsize)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function inetPton4(str){var b=str.split(".");for(var i=0;i<4;i++){var tmp=Number(b[i]);if(isNaN(tmp))return null;b[i]=tmp}return(b[0]|b[1]<<8|b[2]<<16|b[3]<<24)>>>0}function jstoi_q(str){return parseInt(str)}function inetPton6(str){var words;var w,offset,z;var valid6regx=/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i;var parts=[];if(!valid6regx.test(str)){return null}if(str==="::"){return[0,0,0,0,0,0,0,0]}if(str.startsWith("::")){str=str.replace("::","Z:")}else{str=str.replace("::",":Z:")}if(str.indexOf(".")>0){str=str.replace(new RegExp("[.]","g"),":");words=str.split(":");words[words.length-4]=jstoi_q(words[words.length-4])+jstoi_q(words[words.length-3])*256;words[words.length-3]=jstoi_q(words[words.length-2])+jstoi_q(words[words.length-1])*256;words=words.slice(0,words.length-2)}else{words=str.split(":")}offset=0;z=0;for(w=0;w>2]=16}HEAP16[sa>>1]=family;HEAP32[sa+4>>2]=addr;HEAP16[sa+2>>1]=_htons(port);tempI64=[0>>>0,(tempDouble=0,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[sa+8>>2]=tempI64[0],HEAP32[sa+12>>2]=tempI64[1];break;case 10:addr=inetPton6(addr);if(addrlen){HEAP32[addrlen>>2]=28}HEAP32[sa>>2]=family;HEAP32[sa+8>>2]=addr[0];HEAP32[sa+12>>2]=addr[1];HEAP32[sa+16>>2]=addr[2];HEAP32[sa+20>>2]=addr[3];HEAP16[sa+2>>1]=_htons(port);HEAP32[sa+4>>2]=0;HEAP32[sa+24>>2]=0;break;default:return 5}return 0}var DNS={address_map:{id:1,addrs:{},names:{}},lookup_name:function(name){var res=inetPton4(name);if(res!==null){return name}res=inetPton6(name);if(res!==null){return name}var addr;if(DNS.address_map.addrs[name]){addr=DNS.address_map.addrs[name]}else{var id=DNS.address_map.id++;assert(id<65535,"exceeded max address mappings of 65535");addr="172.29."+(id&255)+"."+(id&65280);DNS.address_map.names[addr]=name;DNS.address_map.addrs[name]=addr}return addr},lookup_addr:function(addr){if(DNS.address_map.names[addr]){return DNS.address_map.names[addr]}return null}};function ___sys_recvfrom(fd,buf,len,flags,addr,addrlen){try{var sock=getSocketFromFD(fd);var msg=sock.sock_ops.recvmsg(sock,len);if(!msg)return 0;if(addr){var errno=writeSockaddr(addr,sock.family,DNS.lookup_name(msg.addr),msg.port,addrlen)}HEAPU8.set(msg.buffer,buf);return msg.buffer.byteLength}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_rename(old_path,new_path){try{old_path=SYSCALLS.getStr(old_path);new_path=SYSCALLS.getStr(new_path);FS.rename(old_path,new_path);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_rmdir(path){try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_sendto(fd,message,length,flags,addr,addr_len){try{var sock=getSocketFromFD(fd);var dest=getSocketAddress(addr,addr_len,true);if(!dest){return FS.write(sock.stream,HEAP8,message,length)}else{return sock.sock_ops.sendmsg(sock,HEAP8,message,length,dest.addr,dest.port)}}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_shutdown(fd,how){try{getSocketFromFD(fd);return-52}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_socket(domain,type,protocol){try{var sock=SOCKFS.createSocket(domain,type,protocol);return sock.stream.fd}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.stat,path,buf)}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_statfs64(path,size,buf){try{path=SYSCALLS.getStr(path);HEAP32[buf+4>>2]=4096;HEAP32[buf+40>>2]=4096;HEAP32[buf+8>>2]=1e6;HEAP32[buf+12>>2]=5e5;HEAP32[buf+16>>2]=5e5;HEAP32[buf+20>>2]=FS.nextInode;HEAP32[buf+24>>2]=1e6;HEAP32[buf+28>>2]=42;HEAP32[buf+44>>2]=2;HEAP32[buf+36>>2]=255;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_truncate64(path,zero,low,high){try{path=SYSCALLS.getStr(path);var length=SYSCALLS.get64(low,high);FS.truncate(path,length);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function ___sys_unlink(path){try{path=SYSCALLS.getStr(path);FS.unlink(path);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return-e.errno}}function _abort(){abort()}function _clock(){if(_clock.start===undefined)_clock.start=Date.now();return(Date.now()-_clock.start)*(1e6/1e3)|0}function _emscripten_get_now_res(){if(ENVIRONMENT_IS_NODE){return 1}else if(typeof dateNow!=="undefined"){return 1e3}else return 1e3}var _emscripten_get_now_is_monotonic=true;function _clock_getres(clk_id,res){var nsec;if(clk_id===0){nsec=1e3*1e3}else if(clk_id===1&&_emscripten_get_now_is_monotonic){nsec=_emscripten_get_now_res()}else{setErrNo(28);return-1}HEAP32[res>>2]=nsec/1e9|0;HEAP32[res+4>>2]=nsec;return 0}var _emscripten_get_now;if(ENVIRONMENT_IS_NODE){_emscripten_get_now=function(){var t=process["hrtime"]();return t[0]*1e3+t[1]/1e6}}else if(typeof dateNow!=="undefined"){_emscripten_get_now=dateNow}else _emscripten_get_now=function(){return performance.now()};function _clock_gettime(clk_id,tp){var now;if(clk_id===0){now=Date.now()}else if((clk_id===1||clk_id===4)&&_emscripten_get_now_is_monotonic){now=_emscripten_get_now()}else{setErrNo(28);return-1}HEAP32[tp>>2]=now/1e3|0;HEAP32[tp+4>>2]=now%1e3*1e3*1e3|0;return 0}function _difftime(time1,time0){return time1-time0}function _dlclose(handle){}function _dlerror(){return 0}function _dlopen(filename,flag){}function _dlsym(handle,symbol){return 0}var readAsmConstArgsArray=[];function readAsmConstArgs(sigPtr,buf){readAsmConstArgsArray.length=0;var ch;buf>>=2;while(ch=HEAPU8[sigPtr++]){var double=ch<105;if(double&&buf&1)buf++;readAsmConstArgsArray.push(double?HEAPF64[buf++>>1]:HEAP32[buf]);++buf}return readAsmConstArgsArray}function mainThreadEM_ASM(code,sigPtr,argbuf,sync){var args=readAsmConstArgs(sigPtr,argbuf);return ASM_CONSTS[code].apply(null,args)}function _emscripten_asm_const_int_sync_on_main_thread(code,sigPtr,argbuf){return mainThreadEM_ASM(code,sigPtr,argbuf,1)}function _emscripten_set_main_loop_timing(mode,value){Browser.mainLoop.timingMode=mode;Browser.mainLoop.timingValue=value;if(!Browser.mainLoop.func){return 1}if(!Browser.mainLoop.running){Browser.mainLoop.running=true}if(mode==0){Browser.mainLoop.scheduler=function Browser_mainLoop_scheduler_setTimeout(){var timeUntilNextTick=Math.max(0,Browser.mainLoop.tickStartTime+value-_emscripten_get_now())|0;setTimeout(Browser.mainLoop.runner,timeUntilNextTick)};Browser.mainLoop.method="timeout"}else if(mode==1){Browser.mainLoop.scheduler=function Browser_mainLoop_scheduler_rAF(){Browser.requestAnimationFrame(Browser.mainLoop.runner)};Browser.mainLoop.method="rAF"}else if(mode==2){if(typeof setImmediate==="undefined"){var setImmediates=[];var emscriptenMainLoopMessageId="setimmediate";var Browser_setImmediate_messageHandler=function(event){if(event.data===emscriptenMainLoopMessageId||event.data.target===emscriptenMainLoopMessageId){event.stopPropagation();setImmediates.shift()()}};addEventListener("message",Browser_setImmediate_messageHandler,true);setImmediate=function Browser_emulated_setImmediate(func){setImmediates.push(func);if(ENVIRONMENT_IS_WORKER){if(Module["setImmediates"]===undefined)Module["setImmediates"]=[];Module["setImmediates"].push(func);postMessage({target:emscriptenMainLoopMessageId})}else postMessage(emscriptenMainLoopMessageId,"*")}}Browser.mainLoop.scheduler=function Browser_mainLoop_scheduler_setImmediate(){setImmediate(Browser.mainLoop.runner)};Browser.mainLoop.method="immediate"}return 0}function _exit(status){exit(status)}function maybeExit(){if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){if(e instanceof ExitStatus){return}throw e}}}function setMainLoop(browserIterationFunc,fps,simulateInfiniteLoop,arg,noSetTiming){assert(!Browser.mainLoop.func,"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters.");Browser.mainLoop.func=browserIterationFunc;Browser.mainLoop.arg=arg;var thisMainLoopId=Browser.mainLoop.currentlyRunningMainloop;function checkIsRunning(){if(thisMainLoopId0){var start=Date.now();var blocker=Browser.mainLoop.queue.shift();blocker.func(blocker.arg);if(Browser.mainLoop.remainingBlockers){var remaining=Browser.mainLoop.remainingBlockers;var next=remaining%1==0?remaining-1:Math.floor(remaining);if(blocker.counted){Browser.mainLoop.remainingBlockers=next}else{next=next+.5;Browser.mainLoop.remainingBlockers=(8*remaining+next)/9}}console.log('main loop blocker "'+blocker.name+'" took '+(Date.now()-start)+" ms");Browser.mainLoop.updateStatus();if(!checkIsRunning())return;setTimeout(Browser.mainLoop.runner,0);return}if(!checkIsRunning())return;Browser.mainLoop.currentFrameNumber=Browser.mainLoop.currentFrameNumber+1|0;if(Browser.mainLoop.timingMode==1&&Browser.mainLoop.timingValue>1&&Browser.mainLoop.currentFrameNumber%Browser.mainLoop.timingValue!=0){Browser.mainLoop.scheduler();return}else if(Browser.mainLoop.timingMode==0){Browser.mainLoop.tickStartTime=_emscripten_get_now()}GL.newRenderingFrameStarted();Browser.mainLoop.runIter(browserIterationFunc);if(!checkIsRunning())return;if(typeof SDL==="object"&&SDL.audio&&SDL.audio.queueNewAudioData)SDL.audio.queueNewAudioData();Browser.mainLoop.scheduler()};if(!noSetTiming){if(fps&&fps>0)_emscripten_set_main_loop_timing(0,1e3/fps);else _emscripten_set_main_loop_timing(1,1);Browser.mainLoop.scheduler()}if(simulateInfiniteLoop){throw"unwind"}}function callUserCallback(func,synchronous){if(ABORT){return}if(synchronous){func();return}try{func()}catch(e){if(e instanceof ExitStatus){return}else if(e!=="unwind"){if(e&&typeof e==="object"&&e.stack)err("exception thrown: "+[e,e.stack]);throw e}}}var Browser={mainLoop:{running:false,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){Browser.mainLoop.scheduler=null;Browser.mainLoop.currentlyRunningMainloop++},resume:function(){Browser.mainLoop.currentlyRunningMainloop++;var timingMode=Browser.mainLoop.timingMode;var timingValue=Browser.mainLoop.timingValue;var func=Browser.mainLoop.func;Browser.mainLoop.func=null;setMainLoop(func,0,false,Browser.mainLoop.arg,true);_emscripten_set_main_loop_timing(timingMode,timingValue);Browser.mainLoop.scheduler()},updateStatus:function(){if(Module["setStatus"]){var message=Module["statusMessage"]||"Please wait...";var remaining=Browser.mainLoop.remainingBlockers;var expected=Browser.mainLoop.expectedBlockers;if(remaining){if(remaining=6){var curr=leftchar>>leftbits-6&63;leftbits-=6;ret+=BASE[curr]}}if(leftbits==2){ret+=BASE[(leftchar&3)<<4];ret+=PAD+PAD}else if(leftbits==4){ret+=BASE[(leftchar&15)<<2];ret+=PAD}return ret}audio.src="data:audio/x-"+name.substr(-3)+";base64,"+encode64(byteArray);finish(audio)};audio.src=url;Browser.safeSetTimeout(function(){finish(audio)},1e4)}else{return fail()}};Module["preloadPlugins"].push(audioPlugin);function pointerLockChange(){Browser.pointerLock=document["pointerLockElement"]===Module["canvas"]||document["mozPointerLockElement"]===Module["canvas"]||document["webkitPointerLockElement"]===Module["canvas"]||document["msPointerLockElement"]===Module["canvas"]}var canvas=Module["canvas"];if(canvas){canvas.requestPointerLock=canvas["requestPointerLock"]||canvas["mozRequestPointerLock"]||canvas["webkitRequestPointerLock"]||canvas["msRequestPointerLock"]||function(){};canvas.exitPointerLock=document["exitPointerLock"]||document["mozExitPointerLock"]||document["webkitExitPointerLock"]||document["msExitPointerLock"]||function(){};canvas.exitPointerLock=canvas.exitPointerLock.bind(document);document.addEventListener("pointerlockchange",pointerLockChange,false);document.addEventListener("mozpointerlockchange",pointerLockChange,false);document.addEventListener("webkitpointerlockchange",pointerLockChange,false);document.addEventListener("mspointerlockchange",pointerLockChange,false);if(Module["elementPointerLock"]){canvas.addEventListener("click",function(ev){if(!Browser.pointerLock&&Module["canvas"].requestPointerLock){Module["canvas"].requestPointerLock();ev.preventDefault()}},false)}}},createContext:function(canvas,useWebGL,setInModule,webGLContextAttributes){if(useWebGL&&Module.ctx&&canvas==Module.canvas)return Module.ctx;var ctx;var contextHandle;if(useWebGL){var contextAttributes={antialias:false,alpha:false,majorVersion:typeof WebGL2RenderingContext!=="undefined"?2:1};if(webGLContextAttributes){for(var attribute in webGLContextAttributes){contextAttributes[attribute]=webGLContextAttributes[attribute]}}if(typeof GL!=="undefined"){contextHandle=GL.createContext(canvas,contextAttributes);if(contextHandle){ctx=GL.getContext(contextHandle).GLctx}}}else{ctx=canvas.getContext("2d")}if(!ctx)return null;if(setInModule){if(!useWebGL)assert(typeof GLctx==="undefined","cannot set in module if GLctx is used, but we are a non-GL context that would replace it");Module.ctx=ctx;if(useWebGL)GL.makeContextCurrent(contextHandle);Module.useWebGL=useWebGL;Browser.moduleContextCreatedCallbacks.forEach(function(callback){callback()});Browser.init()}return ctx},destroyContext:function(canvas,useWebGL,setInModule){},fullscreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullscreen:function(lockPointer,resizeCanvas){Browser.lockPointer=lockPointer;Browser.resizeCanvas=resizeCanvas;if(typeof Browser.lockPointer==="undefined")Browser.lockPointer=true;if(typeof Browser.resizeCanvas==="undefined")Browser.resizeCanvas=false;var canvas=Module["canvas"];function fullscreenChange(){Browser.isFullscreen=false;var canvasContainer=canvas.parentNode;if((document["fullscreenElement"]||document["mozFullScreenElement"]||document["msFullscreenElement"]||document["webkitFullscreenElement"]||document["webkitCurrentFullScreenElement"])===canvasContainer){canvas.exitFullscreen=Browser.exitFullscreen;if(Browser.lockPointer)canvas.requestPointerLock();Browser.isFullscreen=true;if(Browser.resizeCanvas){Browser.setFullscreenCanvasSize()}else{Browser.updateCanvasDimensions(canvas)}}else{canvasContainer.parentNode.insertBefore(canvas,canvasContainer);canvasContainer.parentNode.removeChild(canvasContainer);if(Browser.resizeCanvas){Browser.setWindowedCanvasSize()}else{Browser.updateCanvasDimensions(canvas)}}if(Module["onFullScreen"])Module["onFullScreen"](Browser.isFullscreen);if(Module["onFullscreen"])Module["onFullscreen"](Browser.isFullscreen)}if(!Browser.fullscreenHandlersInstalled){Browser.fullscreenHandlersInstalled=true;document.addEventListener("fullscreenchange",fullscreenChange,false);document.addEventListener("mozfullscreenchange",fullscreenChange,false);document.addEventListener("webkitfullscreenchange",fullscreenChange,false);document.addEventListener("MSFullscreenChange",fullscreenChange,false)}var canvasContainer=document.createElement("div");canvas.parentNode.insertBefore(canvasContainer,canvas);canvasContainer.appendChild(canvas);canvasContainer.requestFullscreen=canvasContainer["requestFullscreen"]||canvasContainer["mozRequestFullScreen"]||canvasContainer["msRequestFullscreen"]||(canvasContainer["webkitRequestFullscreen"]?function(){canvasContainer["webkitRequestFullscreen"](Element["ALLOW_KEYBOARD_INPUT"])}:null)||(canvasContainer["webkitRequestFullScreen"]?function(){canvasContainer["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"])}:null);canvasContainer.requestFullscreen()},exitFullscreen:function(){if(!Browser.isFullscreen){return false}var CFS=document["exitFullscreen"]||document["cancelFullScreen"]||document["mozCancelFullScreen"]||document["msExitFullscreen"]||document["webkitCancelFullScreen"]||function(){};CFS.apply(document,[]);return true},nextRAF:0,fakeRequestAnimationFrame:function(func){var now=Date.now();if(Browser.nextRAF===0){Browser.nextRAF=now+1e3/60}else{while(now+2>=Browser.nextRAF){Browser.nextRAF+=1e3/60}}var delay=Math.max(Browser.nextRAF-now,0);setTimeout(func,delay)},requestAnimationFrame:function(func){if(typeof requestAnimationFrame==="function"){requestAnimationFrame(func);return}var RAF=Browser.fakeRequestAnimationFrame;RAF(func)},safeRequestAnimationFrame:function(func){return Browser.requestAnimationFrame(function(){callUserCallback(func)})},safeSetTimeout:function(func,timeout){return setTimeout(function(){callUserCallback(func)},timeout)},getMimetype:function(name){return{"jpg":"image/jpeg","jpeg":"image/jpeg","png":"image/png","bmp":"image/bmp","ogg":"audio/ogg","wav":"audio/wav","mp3":"audio/mpeg"}[name.substr(name.lastIndexOf(".")+1)]},getUserMedia:function(func){if(!window.getUserMedia){window.getUserMedia=navigator["getUserMedia"]||navigator["mozGetUserMedia"]}window.getUserMedia(func)},getMovementX:function(event){return event["movementX"]||event["mozMovementX"]||event["webkitMovementX"]||0},getMovementY:function(event){return event["movementY"]||event["mozMovementY"]||event["webkitMovementY"]||0},getMouseWheelDelta:function(event){var delta=0;switch(event.type){case"DOMMouseScroll":delta=event.detail/3;break;case"mousewheel":delta=event.wheelDelta/120;break;case"wheel":delta=event.deltaY;switch(event.deltaMode){case 0:delta/=100;break;case 1:delta/=3;break;case 2:delta*=80;break;default:throw"unrecognized mouse wheel delta mode: "+event.deltaMode}break;default:throw"unrecognized mouse wheel event: "+event.type}return delta},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(event){if(Browser.pointerLock){if(event.type!="mousemove"&&"mozMovementX"in event){Browser.mouseMovementX=Browser.mouseMovementY=0}else{Browser.mouseMovementX=Browser.getMovementX(event);Browser.mouseMovementY=Browser.getMovementY(event)}if(typeof SDL!="undefined"){Browser.mouseX=SDL.mouseX+Browser.mouseMovementX;Browser.mouseY=SDL.mouseY+Browser.mouseMovementY}else{Browser.mouseX+=Browser.mouseMovementX;Browser.mouseY+=Browser.mouseMovementY}}else{var rect=Module["canvas"].getBoundingClientRect();var cw=Module["canvas"].width;var ch=Module["canvas"].height;var scrollX=typeof window.scrollX!=="undefined"?window.scrollX:window.pageXOffset;var scrollY=typeof window.scrollY!=="undefined"?window.scrollY:window.pageYOffset;if(event.type==="touchstart"||event.type==="touchend"||event.type==="touchmove"){var touch=event.touch;if(touch===undefined){return}var adjustedX=touch.pageX-(scrollX+rect.left);var adjustedY=touch.pageY-(scrollY+rect.top);adjustedX=adjustedX*(cw/rect.width);adjustedY=adjustedY*(ch/rect.height);var coords={x:adjustedX,y:adjustedY};if(event.type==="touchstart"){Browser.lastTouches[touch.identifier]=coords;Browser.touches[touch.identifier]=coords}else if(event.type==="touchend"||event.type==="touchmove"){var last=Browser.touches[touch.identifier];if(!last)last=coords;Browser.lastTouches[touch.identifier]=last;Browser.touches[touch.identifier]=coords}return}var x=event.pageX-(scrollX+rect.left);var y=event.pageY-(scrollY+rect.top);x=x*(cw/rect.width);y=y*(ch/rect.height);Browser.mouseMovementX=x-Browser.mouseX;Browser.mouseMovementY=y-Browser.mouseY;Browser.mouseX=x;Browser.mouseY=y}},asyncLoad:function(url,onload,onerror,noRunDep){var dep=!noRunDep?getUniqueRunDependency("al "+url):"";readAsync(url,function(arrayBuffer){assert(arrayBuffer,'Loading data file "'+url+'" failed (no arrayBuffer).');onload(new Uint8Array(arrayBuffer));if(dep)removeRunDependency(dep)},function(event){if(onerror){onerror()}else{throw'Loading data file "'+url+'" failed.'}});if(dep)addRunDependency(dep)},resizeListeners:[],updateResizeListeners:function(){var canvas=Module["canvas"];Browser.resizeListeners.forEach(function(listener){listener(canvas.width,canvas.height)})},setCanvasSize:function(width,height,noUpdates){var canvas=Module["canvas"];Browser.updateCanvasDimensions(canvas,width,height);if(!noUpdates)Browser.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if(typeof SDL!="undefined"){var flags=HEAPU32[SDL.screen>>2];flags=flags|8388608;HEAP32[SDL.screen>>2]=flags}Browser.updateCanvasDimensions(Module["canvas"]);Browser.updateResizeListeners()},setWindowedCanvasSize:function(){if(typeof SDL!="undefined"){var flags=HEAPU32[SDL.screen>>2];flags=flags&~8388608;HEAP32[SDL.screen>>2]=flags}Browser.updateCanvasDimensions(Module["canvas"]);Browser.updateResizeListeners()},updateCanvasDimensions:function(canvas,wNative,hNative){if(wNative&&hNative){canvas.widthNative=wNative;canvas.heightNative=hNative}else{wNative=canvas.widthNative;hNative=canvas.heightNative}var w=wNative;var h=hNative;if(Module["forcedAspectRatio"]&&Module["forcedAspectRatio"]>0){if(w/h=0;--i){JSEvents._removeHandler(i)}JSEvents.eventHandlers=[];JSEvents.deferredCalls=[]},registerRemoveEventListeners:function(){if(!JSEvents.removeEventListenersRegistered){__ATEXIT__.push(JSEvents.removeAllEventListeners);JSEvents.removeEventListenersRegistered=true}},deferredCalls:[],deferCall:function(targetFunction,precedence,argsList){function arraysHaveEqualContent(arrA,arrB){if(arrA.length!=arrB.length)return false;for(var i in arrA){if(arrA[i]!=arrB[i])return false}return true}for(var i in JSEvents.deferredCalls){var call=JSEvents.deferredCalls[i];if(call.targetFunction==targetFunction&&arraysHaveEqualContent(call.argsList,argsList)){return}}JSEvents.deferredCalls.push({targetFunction:targetFunction,precedence:precedence,argsList:argsList});JSEvents.deferredCalls.sort(function(x,y){return x.precedence2?UTF8ToString(cString):cString}var specialHTMLTargets=[0,typeof document!=="undefined"?document:0,typeof window!=="undefined"?window:0];function findEventTarget(target){target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||(typeof document!=="undefined"?document.querySelector(target):undefined);return domElement}function findCanvasEventTarget(target){return findEventTarget(target)}function _emscripten_get_canvas_element_size(target,width,height){var canvas=findCanvasEventTarget(target);if(!canvas)return-4;HEAP32[width>>2]=canvas.width;HEAP32[height>>2]=canvas.height}function getCanvasElementSize(target){var stackTop=stackSave();var w=stackAlloc(8);var h=w+4;var targetInt=stackAlloc(target.id.length+1);stringToUTF8(target.id,targetInt,target.id.length+1);var ret=_emscripten_get_canvas_element_size(targetInt,w,h);var size=[HEAP32[w>>2],HEAP32[h>>2]];stackRestore(stackTop);return size}function _emscripten_set_canvas_element_size(target,width,height){var canvas=findCanvasEventTarget(target);if(!canvas)return-4;canvas.width=width;canvas.height=height;return 0}function setCanvasElementSize(target,width,height){if(!target.controlTransferredOffscreen){target.width=width;target.height=height}else{var stackTop=stackSave();var targetInt=stackAlloc(target.id.length+1);stringToUTF8(target.id,targetInt,target.id.length+1);_emscripten_set_canvas_element_size(targetInt,width,height);stackRestore(stackTop)}}function registerRestoreOldStyle(canvas){var canvasSize=getCanvasElementSize(canvas);var oldWidth=canvasSize[0];var oldHeight=canvasSize[1];var oldCssWidth=canvas.style.width;var oldCssHeight=canvas.style.height;var oldBackgroundColor=canvas.style.backgroundColor;var oldDocumentBackgroundColor=document.body.style.backgroundColor;var oldPaddingLeft=canvas.style.paddingLeft;var oldPaddingRight=canvas.style.paddingRight;var oldPaddingTop=canvas.style.paddingTop;var oldPaddingBottom=canvas.style.paddingBottom;var oldMarginLeft=canvas.style.marginLeft;var oldMarginRight=canvas.style.marginRight;var oldMarginTop=canvas.style.marginTop;var oldMarginBottom=canvas.style.marginBottom;var oldDocumentBodyMargin=document.body.style.margin;var oldDocumentOverflow=document.documentElement.style.overflow;var oldDocumentScroll=document.body.scroll;var oldImageRendering=canvas.style.imageRendering;function restoreOldStyle(){var fullscreenElement=document.fullscreenElement||document.webkitFullscreenElement||document.msFullscreenElement;if(!fullscreenElement){document.removeEventListener("fullscreenchange",restoreOldStyle);document.removeEventListener("webkitfullscreenchange",restoreOldStyle);setCanvasElementSize(canvas,oldWidth,oldHeight);canvas.style.width=oldCssWidth;canvas.style.height=oldCssHeight;canvas.style.backgroundColor=oldBackgroundColor;if(!oldDocumentBackgroundColor)document.body.style.backgroundColor="white";document.body.style.backgroundColor=oldDocumentBackgroundColor;canvas.style.paddingLeft=oldPaddingLeft;canvas.style.paddingRight=oldPaddingRight;canvas.style.paddingTop=oldPaddingTop;canvas.style.paddingBottom=oldPaddingBottom;canvas.style.marginLeft=oldMarginLeft;canvas.style.marginRight=oldMarginRight;canvas.style.marginTop=oldMarginTop;canvas.style.marginBottom=oldMarginBottom;document.body.style.margin=oldDocumentBodyMargin;document.documentElement.style.overflow=oldDocumentOverflow;document.body.scroll=oldDocumentScroll;canvas.style.imageRendering=oldImageRendering;if(canvas.GLctxObject)canvas.GLctxObject.GLctx.viewport(0,0,oldWidth,oldHeight);if(currentFullscreenStrategy.canvasResizedCallback){(function(a1,a2,a3){return dynCall_iiii.apply(null,[currentFullscreenStrategy.canvasResizedCallback,a1,a2,a3])})(37,0,currentFullscreenStrategy.canvasResizedCallbackUserData)}}}document.addEventListener("fullscreenchange",restoreOldStyle);document.addEventListener("webkitfullscreenchange",restoreOldStyle);return restoreOldStyle}function setLetterbox(element,topBottom,leftRight){element.style.paddingLeft=element.style.paddingRight=leftRight+"px";element.style.paddingTop=element.style.paddingBottom=topBottom+"px"}function getBoundingClientRect(e){return specialHTMLTargets.indexOf(e)<0?e.getBoundingClientRect():{"left":0,"top":0}}function _JSEvents_resizeCanvasForFullscreen(target,strategy){var restoreOldStyle=registerRestoreOldStyle(target);var cssWidth=strategy.softFullscreen?innerWidth:screen.width;var cssHeight=strategy.softFullscreen?innerHeight:screen.height;var rect=getBoundingClientRect(target);var windowedCssWidth=rect.width;var windowedCssHeight=rect.height;var canvasSize=getCanvasElementSize(target);var windowedRttWidth=canvasSize[0];var windowedRttHeight=canvasSize[1];if(strategy.scaleMode==3){setLetterbox(target,(cssHeight-windowedCssHeight)/2,(cssWidth-windowedCssWidth)/2);cssWidth=windowedCssWidth;cssHeight=windowedCssHeight}else if(strategy.scaleMode==2){if(cssWidth*windowedRttHeight>2]=isFullscreen;HEAP32[eventStruct+4>>2]=JSEvents.fullscreenEnabled();var reportedElement=isFullscreen?fullscreenElement:JSEvents.previousFullscreenElement;var nodeName=JSEvents.getNodeNameForTarget(reportedElement);var id=reportedElement&&reportedElement.id?reportedElement.id:"";stringToUTF8(nodeName,eventStruct+8,128);stringToUTF8(id,eventStruct+136,128);HEAP32[eventStruct+264>>2]=reportedElement?reportedElement.clientWidth:0;HEAP32[eventStruct+268>>2]=reportedElement?reportedElement.clientHeight:0;HEAP32[eventStruct+272>>2]=screen.width;HEAP32[eventStruct+276>>2]=screen.height;if(isFullscreen){JSEvents.previousFullscreenElement=fullscreenElement}}function _emscripten_get_fullscreen_status(fullscreenStatus){if(!JSEvents.fullscreenEnabled())return-1;fillFullscreenChangeEventData(fullscreenStatus);return 0}function fillGamepadEventData(eventStruct,e){HEAPF64[eventStruct>>3]=e.timestamp;for(var i=0;i>3]=e.axes[i]}for(var i=0;i>3]=e.buttons[i].value}else{HEAPF64[eventStruct+i*8+528>>3]=e.buttons[i]}}for(var i=0;i>2]=e.buttons[i].pressed}else{HEAP32[eventStruct+i*4+1040>>2]=e.buttons[i]==1}}HEAP32[eventStruct+1296>>2]=e.connected;HEAP32[eventStruct+1300>>2]=e.index;HEAP32[eventStruct+8>>2]=e.axes.length;HEAP32[eventStruct+12>>2]=e.buttons.length;stringToUTF8(e.id,eventStruct+1304,64);stringToUTF8(e.mapping,eventStruct+1368,64)}function _emscripten_get_gamepad_status(index,gamepadState){if(index<0||index>=JSEvents.lastGamepadState.length)return-5;if(!JSEvents.lastGamepadState[index])return-7;fillGamepadEventData(gamepadState,JSEvents.lastGamepadState[index]);return 0}function _emscripten_get_heap_max(){return 2147483648}function _emscripten_get_num_gamepads(){return JSEvents.lastGamepadState.length}function _emscripten_html5_remove_all_event_listeners(){JSEvents.removeAllEventListeners()}function _emscripten_is_webgl_context_lost(contextHandle){return!GL.contexts[contextHandle]||GL.contexts[contextHandle].GLctx.isContextLost()}function reallyNegative(x){return x<0||x===0&&1/x===-Infinity}function convertI32PairToI53(lo,hi){return(lo>>>0)+hi*4294967296}function convertU32PairToI53(lo,hi){return(lo>>>0)+(hi>>>0)*4294967296}function reSign(value,bits){if(value<=0){return value}var half=bits<=32?Math.abs(1<=half&&(bits<=32||value>half)){value=-2*half+value}return value}function unSign(value,bits){if(value>=0){return value}return bits<=32?2*Math.abs(1<>3];argIndex+=8}else if(type=="i64"){ret=[HEAP32[argIndex>>2],HEAP32[argIndex+4>>2]];argIndex+=8}else{type="i32";ret=HEAP32[argIndex>>2];argIndex+=4}return ret}var ret=[];var curr,next,currArg;while(1){var startTextIndex=textIndex;curr=HEAP8[textIndex>>0];if(curr===0)break;next=HEAP8[textIndex+1>>0];if(curr==37){var flagAlwaysSigned=false;var flagLeftAlign=false;var flagAlternative=false;var flagZeroPad=false;var flagPadSign=false;flagsLoop:while(1){switch(next){case 43:flagAlwaysSigned=true;break;case 45:flagLeftAlign=true;break;case 35:flagAlternative=true;break;case 48:if(flagZeroPad){break flagsLoop}else{flagZeroPad=true;break}case 32:flagPadSign=true;break;default:break flagsLoop}textIndex++;next=HEAP8[textIndex+1>>0]}var width=0;if(next==42){width=getNextArg("i32");textIndex++;next=HEAP8[textIndex+1>>0]}else{while(next>=48&&next<=57){width=width*10+(next-48);textIndex++;next=HEAP8[textIndex+1>>0]}}var precisionSet=false,precision=-1;if(next==46){precision=0;precisionSet=true;textIndex++;next=HEAP8[textIndex+1>>0];if(next==42){precision=getNextArg("i32");textIndex++}else{while(1){var precisionChr=HEAP8[textIndex+1>>0];if(precisionChr<48||precisionChr>57)break;precision=precision*10+(precisionChr-48);textIndex++}}next=HEAP8[textIndex+1>>0]}if(precision<0){precision=6;precisionSet=false}var argSize;switch(String.fromCharCode(next)){case"h":var nextNext=HEAP8[textIndex+2>>0];if(nextNext==104){textIndex++;argSize=1}else{argSize=2}break;case"l":var nextNext=HEAP8[textIndex+2>>0];if(nextNext==108){textIndex++;argSize=8}else{argSize=4}break;case"L":case"q":case"j":argSize=8;break;case"z":case"t":case"I":argSize=4;break;default:argSize=null}if(argSize)textIndex++;next=HEAP8[textIndex+1>>0];switch(String.fromCharCode(next)){case"d":case"i":case"u":case"o":case"x":case"X":case"p":{var signed=next==100||next==105;argSize=argSize||4;currArg=getNextArg("i"+argSize*8);var argText;if(argSize==8){currArg=next==117?convertU32PairToI53(currArg[0],currArg[1]):convertI32PairToI53(currArg[0],currArg[1])}if(argSize<=4){var limit=Math.pow(256,argSize)-1;currArg=(signed?reSign:unSign)(currArg&limit,argSize*8)}var currAbsArg=Math.abs(currArg);var prefix="";if(next==100||next==105){argText=reSign(currArg,8*argSize,1).toString(10)}else if(next==117){argText=unSign(currArg,8*argSize,1).toString(10);currArg=Math.abs(currArg)}else if(next==111){argText=(flagAlternative?"0":"")+currAbsArg.toString(8)}else if(next==120||next==88){prefix=flagAlternative&&currArg!=0?"0x":"";if(currArg<0){currArg=-currArg;argText=(currAbsArg-1).toString(16);var buffer=[];for(var i=0;i=0){if(flagAlwaysSigned){prefix="+"+prefix}else if(flagPadSign){prefix=" "+prefix}}if(argText.charAt(0)=="-"){prefix="-"+prefix;argText=argText.substr(1)}while(prefix.length+argText.lengthexponent&&exponent>=-4){next=(next==103?"f":"F").charCodeAt(0);precision-=exponent+1}else{next=(next==103?"e":"E").charCodeAt(0);precision--}effectivePrecision=Math.min(precision,20)}if(next==101||next==69){argText=currArg.toExponential(effectivePrecision);if(/[eE][-+]\d$/.test(argText)){argText=argText.slice(0,-1)+"0"+argText.slice(-1)}}else if(next==102||next==70){argText=currArg.toFixed(effectivePrecision);if(currArg===0&&reallyNegative(currArg)){argText="-"+argText}}var parts=argText.split("e");if(isGeneral&&!flagAlternative){while(parts[0].length>1&&parts[0].includes(".")&&(parts[0].slice(-1)=="0"||parts[0].slice(-1)==".")){parts[0]=parts[0].slice(0,-1)}}else{if(flagAlternative&&argText.indexOf(".")==-1)parts[0]+=".";while(precision>effectivePrecision++)parts[0]+="0"}argText=parts[0]+(parts.length>1?"e"+parts[1]:"");if(next==69)argText=argText.toUpperCase();if(currArg>=0){if(flagAlwaysSigned){argText="+"+argText}else if(flagPadSign){argText=" "+argText}}}while(argText.length>0])}}else{ret=ret.concat(intArrayFromString("(null)".substr(0,argLength),true))}if(flagLeftAlign){while(argLength0){ret.push(32)}if(!flagLeftAlign)ret.push(getNextArg("i8"));break}case"n":{var ptr=getNextArg("i32*");HEAP32[ptr>>2]=ret.length;break}case"%":{ret.push(curr);break}default:{for(var i=startTextIndex;i>0])}}}textIndex+=2}else{ret.push(curr);textIndex+=1}}return ret}function traverseStack(args){if(!args||!args.callee||!args.callee.name){return[null,"",""]}var funstr=args.callee.toString();var funcname=args.callee.name;var str="(";var first=true;for(var i in args){var a=args[i];if(!first){str+=", "}first=false;if(typeof a==="number"||typeof a==="string"){str+=a}else{str+="("+typeof a+")"}}str+=")";var caller=args.callee.caller;args=caller?caller.arguments:[];if(first)str="";return[args,funcname,str]}function _emscripten_get_callstack_js(flags){var callstack=jsStackTrace();var iThisFunc=callstack.lastIndexOf("_emscripten_log");var iThisFunc2=callstack.lastIndexOf("_emscripten_get_callstack");var iNextLine=callstack.indexOf("\n",Math.max(iThisFunc,iThisFunc2))+1;callstack=callstack.slice(iNextLine);if(flags&32){warnOnce("EM_LOG_DEMANGLE is deprecated; ignoring")}if(flags&8&&typeof emscripten_source_map==="undefined"){warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.');flags^=8;flags|=16}var stack_args=null;if(flags&128){stack_args=traverseStack(arguments);while(stack_args[1].includes("_emscripten_"))stack_args=traverseStack(stack_args[0])}var lines=callstack.split("\n");callstack="";var newFirefoxRe=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)");var firefoxRe=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?");var chromeRe=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var l in lines){var line=lines[l];var symbolName="";var file="";var lineno=0;var column=0;var parts=chromeRe.exec(line);if(parts&&parts.length==5){symbolName=parts[1];file=parts[2];lineno=parts[3];column=parts[4]}else{parts=newFirefoxRe.exec(line);if(!parts)parts=firefoxRe.exec(line);if(parts&&parts.length>=4){symbolName=parts[1];file=parts[2];lineno=parts[3];column=parts[4]|0}else{callstack+=line+"\n";continue}}var haveSourceMap=false;if(flags&8){var orig=emscripten_source_map.originalPositionFor({line:lineno,column:column});haveSourceMap=orig&&orig.source;if(haveSourceMap){if(flags&64){orig.source=orig.source.substring(orig.source.replace(/\\/g,"/").lastIndexOf("/")+1)}callstack+=" at "+symbolName+" ("+orig.source+":"+orig.line+":"+orig.column+")\n"}}if(flags&16||!haveSourceMap){if(flags&64){file=file.substring(file.replace(/\\/g,"/").lastIndexOf("/")+1)}callstack+=(haveSourceMap?" = "+symbolName:" at "+symbolName)+" ("+file+":"+lineno+":"+column+")\n"}if(flags&128&&stack_args[0]){if(stack_args[1]==symbolName&&stack_args[2].length>0){callstack=callstack.replace(/\s+$/,"");callstack+=" with values: "+stack_args[1]+stack_args[2]+"\n"}stack_args=traverseStack(stack_args[0])}}callstack=callstack.replace(/\s+$/,"");return callstack}function _emscripten_log_js(flags,str){if(flags&24){str=str.replace(/\s+$/,"");str+=(str.length>0?"\n":"")+_emscripten_get_callstack_js(flags)}if(flags&1){if(flags&4){console.error(str)}else if(flags&2){console.warn(str)}else if(flags&512){console.info(str)}else if(flags&256){console.debug(str)}else{console.log(str)}}else if(flags&6){err(str)}else{out(str)}}function _emscripten_log(flags,format,varargs){var result=formatString(format,varargs);var str=UTF8ArrayToString(result,0);_emscripten_log_js(flags,str)}function _longjmp(env,value){_setThrew(env,value||1);throw"longjmp"}function _emscripten_longjmp(a0,a1){return _longjmp(a0,a1)}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function doRequestFullscreen(target,strategy){if(!JSEvents.fullscreenEnabled())return-1;target=findEventTarget(target);if(!target)return-4;if(!target.requestFullscreen&&!target.webkitRequestFullscreen){return-3}var canPerformRequests=JSEvents.canPerformEventHandlerRequests();if(!canPerformRequests){if(strategy.deferUntilInEventHandler){JSEvents.deferCall(_JSEvents_requestFullscreen,1,[target,strategy]);return 1}else{return-2}}return _JSEvents_requestFullscreen(target,strategy)}function _emscripten_request_fullscreen(target,deferUntilInEventHandler){var strategy={scaleMode:0,canvasResolutionScaleMode:0,filteringMode:0,deferUntilInEventHandler:deferUntilInEventHandler,canvasResizedCallbackTargetThread:2};return doRequestFullscreen(target,strategy)}function _emscripten_request_pointerlock(target,deferUntilInEventHandler){target=findEventTarget(target);if(!target)return-4;if(!target.requestPointerLock&&!target.msRequestPointerLock){return-1}var canPerformRequests=JSEvents.canPerformEventHandlerRequests();if(!canPerformRequests){if(deferUntilInEventHandler){JSEvents.deferCall(requestPointerLock,2,[target]);return 1}else{return-2}}return requestPointerLock(target)}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}function _emscripten_sample_gamepad_data(){return(JSEvents.lastGamepadState=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():null)?0:-1}function registerFocusEventCallback(target,userData,useCapture,callbackfunc,eventTypeId,eventTypeString,targetThread){if(!JSEvents.focusEvent)JSEvents.focusEvent=_malloc(256);var focusEventHandlerFunc=function(ev){var e=ev||event;var nodeName=JSEvents.getNodeNameForTarget(e.target);var id=e.target.id?e.target.id:"";var focusEvent=JSEvents.focusEvent;stringToUTF8(nodeName,focusEvent+0,128);stringToUTF8(id,focusEvent+128,128);if(function(a1,a2,a3){return dynCall_iiii.apply(null,[callbackfunc,a1,a2,a3])}(eventTypeId,focusEvent,userData))e.preventDefault()};var eventHandler={target:findEventTarget(target),eventTypeString:eventTypeString,callbackfunc:callbackfunc,handlerFunc:focusEventHandlerFunc,useCapture:useCapture};JSEvents.registerOrRemoveHandler(eventHandler)}function _emscripten_set_blur_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerFocusEventCallback(target,userData,useCapture,callbackfunc,12,"blur",targetThread);return 0}function _emscripten_set_focus_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerFocusEventCallback(target,userData,useCapture,callbackfunc,13,"focus",targetThread);return 0}function registerFullscreenChangeEventCallback(target,userData,useCapture,callbackfunc,eventTypeId,eventTypeString,targetThread){if(!JSEvents.fullscreenChangeEvent)JSEvents.fullscreenChangeEvent=_malloc(280);var fullscreenChangeEventhandlerFunc=function(ev){var e=ev||event;var fullscreenChangeEvent=JSEvents.fullscreenChangeEvent;fillFullscreenChangeEventData(fullscreenChangeEvent);if(function(a1,a2,a3){return dynCall_iiii.apply(null,[callbackfunc,a1,a2,a3])}(eventTypeId,fullscreenChangeEvent,userData))e.preventDefault()};var eventHandler={target:target,eventTypeString:eventTypeString,callbackfunc:callbackfunc,handlerFunc:fullscreenChangeEventhandlerFunc,useCapture:useCapture};JSEvents.registerOrRemoveHandler(eventHandler)}function _emscripten_set_fullscreenchange_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){if(!JSEvents.fullscreenEnabled())return-1;target=findEventTarget(target);if(!target)return-4;registerFullscreenChangeEventCallback(target,userData,useCapture,callbackfunc,19,"fullscreenchange",targetThread);registerFullscreenChangeEventCallback(target,userData,useCapture,callbackfunc,19,"webkitfullscreenchange",targetThread);return 0}function registerGamepadEventCallback(target,userData,useCapture,callbackfunc,eventTypeId,eventTypeString,targetThread){if(!JSEvents.gamepadEvent)JSEvents.gamepadEvent=_malloc(1432);var gamepadEventHandlerFunc=function(ev){var e=ev||event;var gamepadEvent=JSEvents.gamepadEvent;fillGamepadEventData(gamepadEvent,e["gamepad"]);if(function(a1,a2,a3){return dynCall_iiii.apply(null,[callbackfunc,a1,a2,a3])}(eventTypeId,gamepadEvent,userData))e.preventDefault()};var eventHandler={target:findEventTarget(target),allowsDeferredCalls:true,eventTypeString:eventTypeString,callbackfunc:callbackfunc,handlerFunc:gamepadEventHandlerFunc,useCapture:useCapture};JSEvents.registerOrRemoveHandler(eventHandler)}function _emscripten_set_gamepadconnected_callback_on_thread(userData,useCapture,callbackfunc,targetThread){if(!navigator.getGamepads&&!navigator.webkitGetGamepads)return-1;registerGamepadEventCallback(2,userData,useCapture,callbackfunc,26,"gamepadconnected",targetThread);return 0}function _emscripten_set_gamepaddisconnected_callback_on_thread(userData,useCapture,callbackfunc,targetThread){if(!navigator.getGamepads&&!navigator.webkitGetGamepads)return-1;registerGamepadEventCallback(2,userData,useCapture,callbackfunc,27,"gamepaddisconnected",targetThread);return 0}function _emscripten_set_interval(cb,msecs,userData){return setInterval(function(){(function(a1){dynCall_vi.apply(null,[cb,a1])})(userData)},msecs)}function registerKeyEventCallback(target,userData,useCapture,callbackfunc,eventTypeId,eventTypeString,targetThread){if(!JSEvents.keyEvent)JSEvents.keyEvent=_malloc(164);var keyEventHandlerFunc=function(e){var keyEventData=JSEvents.keyEvent;var idx=keyEventData>>2;HEAP32[idx+0]=e.location;HEAP32[idx+1]=e.ctrlKey;HEAP32[idx+2]=e.shiftKey;HEAP32[idx+3]=e.altKey;HEAP32[idx+4]=e.metaKey;HEAP32[idx+5]=e.repeat;HEAP32[idx+6]=e.charCode;HEAP32[idx+7]=e.keyCode;HEAP32[idx+8]=e.which;stringToUTF8(e.key||"",keyEventData+36,32);stringToUTF8(e.code||"",keyEventData+68,32);stringToUTF8(e.char||"",keyEventData+100,32);stringToUTF8(e.locale||"",keyEventData+132,32);if(function(a1,a2,a3){return dynCall_iiii.apply(null,[callbackfunc,a1,a2,a3])}(eventTypeId,keyEventData,userData))e.preventDefault()};var eventHandler={target:findEventTarget(target),allowsDeferredCalls:true,eventTypeString:eventTypeString,callbackfunc:callbackfunc,handlerFunc:keyEventHandlerFunc,useCapture:useCapture};JSEvents.registerOrRemoveHandler(eventHandler)}function _emscripten_set_keydown_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerKeyEventCallback(target,userData,useCapture,callbackfunc,2,"keydown",targetThread);return 0}function _emscripten_set_keypress_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerKeyEventCallback(target,userData,useCapture,callbackfunc,1,"keypress",targetThread);return 0}function _emscripten_set_keyup_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerKeyEventCallback(target,userData,useCapture,callbackfunc,3,"keyup",targetThread);return 0}function _emscripten_set_main_loop(func,fps,simulateInfiniteLoop){var browserIterationFunc=function(){dynCall_v.call(null,func)};setMainLoop(browserIterationFunc,fps,simulateInfiniteLoop)}function fillMouseEventData(eventStruct,e,target){var idx=eventStruct>>2;HEAP32[idx+0]=e.screenX;HEAP32[idx+1]=e.screenY;HEAP32[idx+2]=e.clientX;HEAP32[idx+3]=e.clientY;HEAP32[idx+4]=e.ctrlKey;HEAP32[idx+5]=e.shiftKey;HEAP32[idx+6]=e.altKey;HEAP32[idx+7]=e.metaKey;HEAP16[idx*2+16]=e.button;HEAP16[idx*2+17]=e.buttons;HEAP32[idx+9]=e["movementX"];HEAP32[idx+10]=e["movementY"];var rect=getBoundingClientRect(target);HEAP32[idx+11]=e.clientX-rect.left;HEAP32[idx+12]=e.clientY-rect.top}function registerMouseEventCallback(target,userData,useCapture,callbackfunc,eventTypeId,eventTypeString,targetThread){if(!JSEvents.mouseEvent)JSEvents.mouseEvent=_malloc(64);target=findEventTarget(target);var mouseEventHandlerFunc=function(ev){var e=ev||event;fillMouseEventData(JSEvents.mouseEvent,e,target);if(function(a1,a2,a3){return dynCall_iiii.apply(null,[callbackfunc,a1,a2,a3])}(eventTypeId,JSEvents.mouseEvent,userData))e.preventDefault()};var eventHandler={target:target,allowsDeferredCalls:eventTypeString!="mousemove"&&eventTypeString!="mouseenter"&&eventTypeString!="mouseleave",eventTypeString:eventTypeString,callbackfunc:callbackfunc,handlerFunc:mouseEventHandlerFunc,useCapture:useCapture};JSEvents.registerOrRemoveHandler(eventHandler)}function _emscripten_set_mousedown_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerMouseEventCallback(target,userData,useCapture,callbackfunc,5,"mousedown",targetThread);return 0}function _emscripten_set_mousemove_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerMouseEventCallback(target,userData,useCapture,callbackfunc,8,"mousemove",targetThread);return 0}function _emscripten_set_mouseup_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerMouseEventCallback(target,userData,useCapture,callbackfunc,6,"mouseup",targetThread);return 0}function registerTouchEventCallback(target,userData,useCapture,callbackfunc,eventTypeId,eventTypeString,targetThread){if(!JSEvents.touchEvent)JSEvents.touchEvent=_malloc(1684);target=findEventTarget(target);var touchEventHandlerFunc=function(e){var t,touches={},et=e.touches;for(var i=0;i>2;HEAP32[idx+1]=e.ctrlKey;HEAP32[idx+2]=e.shiftKey;HEAP32[idx+3]=e.altKey;HEAP32[idx+4]=e.metaKey;idx+=5;var targetRect=getBoundingClientRect(target);var numTouches=0;for(var i in touches){var t=touches[i];HEAP32[idx+0]=t.identifier;HEAP32[idx+1]=t.screenX;HEAP32[idx+2]=t.screenY;HEAP32[idx+3]=t.clientX;HEAP32[idx+4]=t.clientY;HEAP32[idx+5]=t.pageX;HEAP32[idx+6]=t.pageY;HEAP32[idx+7]=t.isChanged;HEAP32[idx+8]=t.onTarget;HEAP32[idx+9]=t.clientX-targetRect.left;HEAP32[idx+10]=t.clientY-targetRect.top;idx+=13;if(++numTouches>31){break}}HEAP32[touchEvent>>2]=numTouches;if(function(a1,a2,a3){return dynCall_iiii.apply(null,[callbackfunc,a1,a2,a3])}(eventTypeId,touchEvent,userData))e.preventDefault()};var eventHandler={target:target,allowsDeferredCalls:eventTypeString=="touchstart"||eventTypeString=="touchend",eventTypeString:eventTypeString,callbackfunc:callbackfunc,handlerFunc:touchEventHandlerFunc,useCapture:useCapture};JSEvents.registerOrRemoveHandler(eventHandler)}function _emscripten_set_touchcancel_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerTouchEventCallback(target,userData,useCapture,callbackfunc,25,"touchcancel",targetThread);return 0}function _emscripten_set_touchend_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerTouchEventCallback(target,userData,useCapture,callbackfunc,23,"touchend",targetThread);return 0}function _emscripten_set_touchmove_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerTouchEventCallback(target,userData,useCapture,callbackfunc,24,"touchmove",targetThread);return 0}function _emscripten_set_touchstart_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){registerTouchEventCallback(target,userData,useCapture,callbackfunc,22,"touchstart",targetThread);return 0}function registerWheelEventCallback(target,userData,useCapture,callbackfunc,eventTypeId,eventTypeString,targetThread){if(!JSEvents.wheelEvent)JSEvents.wheelEvent=_malloc(96);var wheelHandlerFunc=function(ev){var e=ev||event;var wheelEvent=JSEvents.wheelEvent;fillMouseEventData(wheelEvent,e,target);HEAPF64[wheelEvent+64>>3]=e["deltaX"];HEAPF64[wheelEvent+72>>3]=e["deltaY"];HEAPF64[wheelEvent+80>>3]=e["deltaZ"];HEAP32[wheelEvent+88>>2]=e["deltaMode"];if(function(a1,a2,a3){return dynCall_iiii.apply(null,[callbackfunc,a1,a2,a3])}(eventTypeId,wheelEvent,userData))e.preventDefault()};var eventHandler={target:target,allowsDeferredCalls:true,eventTypeString:eventTypeString,callbackfunc:callbackfunc,handlerFunc:wheelHandlerFunc,useCapture:useCapture};JSEvents.registerOrRemoveHandler(eventHandler)}function _emscripten_set_wheel_callback_on_thread(target,userData,useCapture,callbackfunc,targetThread){target=findEventTarget(target);if(typeof target.onwheel!=="undefined"){registerWheelEventCallback(target,userData,useCapture,callbackfunc,9,"wheel",targetThread);return 0}else{return-1}}function _emscripten_thread_sleep(msecs){var start=_emscripten_get_now();while(_emscripten_get_now()-start>1;var quadIndexes=new Uint16Array(numIndexes);var i=0,v=0;while(1){quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+1;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v+3;if(i>=numIndexes)break;v+=4}context.GLctx.bufferData(34963,quadIndexes,35044);context.GLctx.bindBuffer(34963,null)}},getTempVertexBuffer:function getTempVertexBuffer(sizeBytes){var idx=GL.log2ceilLookup(sizeBytes);var ringbuffer=GL.currentContext.tempVertexBuffers1[idx];var nextFreeBufferIndex=GL.currentContext.tempVertexBufferCounters1[idx];GL.currentContext.tempVertexBufferCounters1[idx]=GL.currentContext.tempVertexBufferCounters1[idx]+1&GL.numTempVertexBuffersPerSize-1;var vbo=ringbuffer[nextFreeBufferIndex];if(vbo){return vbo}var prevVBO=GLctx.getParameter(34964);ringbuffer[nextFreeBufferIndex]=GLctx.createBuffer();GLctx.bindBuffer(34962,ringbuffer[nextFreeBufferIndex]);GLctx.bufferData(34962,1<>2]:-1;source+=UTF8ToString(HEAP32[string+i*4>>2],len<0?undefined:len)}return source},calcBufLength:function calcBufLength(size,type,stride,count){if(stride>0){return count*stride}var typeSize=GL.byteSizeByType[type-GL.byteSizeByTypeRoot];return size*typeSize*count},usedTempBuffers:[],preDrawHandleClientVertexAttribBindings:function preDrawHandleClientVertexAttribBindings(count){GL.resetBufferBinding=false;for(var i=0;i1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:function(ctx,webGLContextAttributes){var handle=GL.getNewId(GL.contexts);var context={handle:handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault==="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}context.maxVertexAttribs=context.GLctx.getParameter(34921);context.clientBuffers=[];for(var i=0;i=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}__webgl_enable_WEBGL_multi_draw(GLctx);var exts=GLctx.getSupportedExtensions()||[];exts.forEach(function(ext){if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}})}};var __emscripten_webgl_power_preferences=["default","low-power","high-performance"];function _emscripten_webgl_do_create_context(target,attributes){var a=attributes>>2;var powerPreference=HEAP32[a+(24>>2)];var contextAttributes={"alpha":!!HEAP32[a+(0>>2)],"depth":!!HEAP32[a+(4>>2)],"stencil":!!HEAP32[a+(8>>2)],"antialias":!!HEAP32[a+(12>>2)],"premultipliedAlpha":!!HEAP32[a+(16>>2)],"preserveDrawingBuffer":!!HEAP32[a+(20>>2)],"powerPreference":__emscripten_webgl_power_preferences[powerPreference],"failIfMajorPerformanceCaveat":!!HEAP32[a+(28>>2)],majorVersion:HEAP32[a+(32>>2)],minorVersion:HEAP32[a+(36>>2)],enableExtensionsByDefault:HEAP32[a+(40>>2)],explicitSwapControl:HEAP32[a+(44>>2)],proxyContextToMainThread:HEAP32[a+(48>>2)],renderViaOffscreenBackBuffer:HEAP32[a+(52>>2)]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle}function _emscripten_webgl_create_context(a0,a1){return _emscripten_webgl_do_create_context(a0,a1)}function _emscripten_webgl_do_get_current_context(){return GL.currentContext?GL.currentContext.handle:0}function _emscripten_webgl_get_current_context(){return _emscripten_webgl_do_get_current_context()}Module["_emscripten_webgl_get_current_context"]=_emscripten_webgl_get_current_context;function _emscripten_webgl_make_context_current(contextHandle){var success=GL.makeContextCurrent(contextHandle);return success?0:-5}Module["_emscripten_webgl_make_context_current"]=_emscripten_webgl_make_context_current;function _emscripten_webgl_destroy_context(contextHandle){if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)}function _emscripten_webgl_enable_extension(contextHandle,extension){var context=GL.getContext(contextHandle);var extString=UTF8ToString(extension);if(extString.startsWith("GL_"))extString=extString.substr(3);if(extString=="ANGLE_instanced_arrays")__webgl_enable_ANGLE_instanced_arrays(GLctx);if(extString=="OES_vertex_array_object")__webgl_enable_OES_vertex_array_object(GLctx);if(extString=="WEBGL_draw_buffers")__webgl_enable_WEBGL_draw_buffers(GLctx);if(extString=="WEBGL_draw_instanced_base_vertex_base_instance")__webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);if(extString=="WEBGL_multi_draw_instanced_base_vertex_base_instance")__webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);if(extString=="WEBGL_multi_draw")__webgl_enable_WEBGL_multi_draw(GLctx);var ext=context.GLctx.getExtension(extString);return!!ext}function _emscripten_webgl_init_context_attributes(attributes){var a=attributes>>2;for(var i=0;i<56>>2;++i){HEAP32[a+i]=0}HEAP32[a+(0>>2)]=HEAP32[a+(4>>2)]=HEAP32[a+(12>>2)]=HEAP32[a+(16>>2)]=HEAP32[a+(32>>2)]=HEAP32[a+(40>>2)]=1}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator==="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={"USER":"web_user","LOGNAME":"web_user","PATH":"/","PWD":"/","HOME":"/home/web_user","LANG":lang,"_":getExecutableName()};for(var x in ENV){env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(x+"="+env[x])}getEnvStrings.strings=strings}return getEnvStrings.strings}function _environ_get(__environ,environ_buf){try{var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAP32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _environ_sizes_get(penviron_count,penviron_buf_size){try{var strings=getEnvStrings();HEAP32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAP32[penviron_buf_size>>2]=bufSize;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_fdstat_get(fd,pbuf){try{var stream=SYSCALLS.getStreamFromFD(fd);var type=stream.tty?2:FS.isDir(stream.mode)?3:FS.isLink(stream.mode)?7:4;HEAP8[pbuf>>0]=type;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=SYSCALLS.doReadv(stream,iov,iovcnt);HEAP32[pnum>>2]=num;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){try{var stream=SYSCALLS.getStreamFromFD(fd);var HIGH_OFFSET=4294967296;var offset=offset_high*HIGH_OFFSET+(offset_low>>>0);var DOUBLE_LIMIT=9007199254740992;if(offset<=-DOUBLE_LIMIT||offset>=DOUBLE_LIMIT){return-61}FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=SYSCALLS.doWritev(stream,iov,iovcnt);HEAP32[pnum>>2]=num;return 0}catch(e){if(typeof FS==="undefined"||!(e instanceof FS.ErrnoError))abort(e);return e.errno}}function _flock(fd,operation){return 0}function _getTempRet0(){return getTempRet0()}function getHostByName(name){var ret=_malloc(20);var nameBuf=_malloc(name.length+1);stringToUTF8(name,nameBuf,name.length+1);HEAP32[ret>>2]=nameBuf;var aliasesBuf=_malloc(4);HEAP32[aliasesBuf>>2]=0;HEAP32[ret+4>>2]=aliasesBuf;var afinet=2;HEAP32[ret+8>>2]=afinet;HEAP32[ret+12>>2]=4;var addrListBuf=_malloc(12);HEAP32[addrListBuf>>2]=addrListBuf+8;HEAP32[addrListBuf+4>>2]=0;HEAP32[addrListBuf+8>>2]=inetPton4(DNS.lookup_name(name));HEAP32[ret+16>>2]=addrListBuf;return ret}function _gethostbyaddr(addr,addrlen,type){if(type!==2){setErrNo(5);return null}addr=HEAP32[addr>>2];var host=inetNtop4(addr);var lookup=DNS.lookup_addr(host);if(lookup){host=lookup}return getHostByName(host)}function _gethostbyname(name){return getHostByName(UTF8ToString(name))}function _getpwuid(){throw"getpwuid: TODO"}function _gettimeofday(ptr){var now=Date.now();HEAP32[ptr>>2]=now/1e3|0;HEAP32[ptr+4>>2]=now%1e3*1e3|0;return 0}function _glActiveTexture(x0){GLctx["activeTexture"](x0)}function _glAttachShader(program,shader){program=GL.programs[program];shader=GL.shaders[shader];program[shader.shaderType]=shader;GLctx.attachShader(program,shader)}function _glBeginQuery(target,id){GLctx["beginQuery"](target,GL.queries[id])}function _glBeginTransformFeedback(x0){GLctx["beginTransformFeedback"](x0)}function _glBindAttribLocation(program,index,name){GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))}function _glBindBuffer(target,buffer){if(target==34962){GLctx.currentArrayBufferBinding=buffer}else if(target==34963){GLctx.currentElementArrayBufferBinding=buffer}if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])}function _glBindBufferBase(target,index,buffer){GLctx["bindBufferBase"](target,index,GL.buffers[buffer])}function _glBindBufferRange(target,index,buffer,offset,ptrsize){GLctx["bindBufferRange"](target,index,GL.buffers[buffer],offset,ptrsize)}function _glBindFramebuffer(target,framebuffer){GLctx.bindFramebuffer(target,GL.framebuffers[framebuffer])}function _glBindRenderbuffer(target,renderbuffer){GLctx.bindRenderbuffer(target,GL.renderbuffers[renderbuffer])}function _glBindSampler(unit,sampler){GLctx["bindSampler"](unit,GL.samplers[sampler])}function _glBindTexture(target,texture){GLctx.bindTexture(target,GL.textures[texture])}function _glBindTransformFeedback(target,id){GLctx["bindTransformFeedback"](target,GL.transformFeedbacks[id])}function _glBindVertexArray(vao){GLctx["bindVertexArray"](GL.vaos[vao]);var ibo=GLctx.getParameter(34965);GLctx.currentElementArrayBufferBinding=ibo?ibo.name|0:0}function _glBlendEquation(x0){GLctx["blendEquation"](x0)}function _glBlendEquationSeparate(x0,x1){GLctx["blendEquationSeparate"](x0,x1)}function _glBlendFuncSeparate(x0,x1,x2,x3){GLctx["blendFuncSeparate"](x0,x1,x2,x3)}function _glBlitFramebuffer(x0,x1,x2,x3,x4,x5,x6,x7,x8,x9){GLctx["blitFramebuffer"](x0,x1,x2,x3,x4,x5,x6,x7,x8,x9)}function _glBufferData(target,size,data,usage){if(GL.currentContext.version>=2){if(data){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}}else{GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)}}function _glBufferSubData(target,offset,size,data){if(GL.currentContext.version>=2){GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))}function _glCheckFramebufferStatus(x0){return GLctx["checkFramebufferStatus"](x0)}function _glClear(x0){GLctx["clear"](x0)}function _glClearBufferfi(x0,x1,x2,x3){GLctx["clearBufferfi"](x0,x1,x2,x3)}function _glClearBufferfv(buffer,drawbuffer,value){GLctx["clearBufferfv"](buffer,drawbuffer,HEAPF32,value>>2)}function _glClearBufferuiv(buffer,drawbuffer,value){GLctx["clearBufferuiv"](buffer,drawbuffer,HEAPU32,value>>2)}function _glClearColor(x0,x1,x2,x3){GLctx["clearColor"](x0,x1,x2,x3)}function _glClearDepthf(x0){GLctx["clearDepth"](x0)}function _glClearStencil(x0){GLctx["clearStencil"](x0)}function _glClientWaitSync(sync,flags,timeoutLo,timeoutHi){return GLctx.clientWaitSync(GL.syncs[sync],flags,convertI32PairToI53(timeoutLo,timeoutHi))}function _glColorMask(red,green,blue,alpha){GLctx.colorMask(!!red,!!green,!!blue,!!alpha)}function _glCompileShader(shader){GLctx.compileShader(GL.shaders[shader])}function _glCompressedTexImage2D(target,level,internalFormat,width,height,border,imageSize,data){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,imageSize,data)}else{GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,HEAPU8,data,imageSize)}return}GLctx["compressedTexImage2D"](target,level,internalFormat,width,height,border,data?HEAPU8.subarray(data,data+imageSize):null)}function _glCompressedTexImage3D(target,level,internalFormat,width,height,depth,border,imageSize,data){if(GLctx.currentPixelUnpackBufferBinding){GLctx["compressedTexImage3D"](target,level,internalFormat,width,height,depth,border,imageSize,data)}else{GLctx["compressedTexImage3D"](target,level,internalFormat,width,height,depth,border,HEAPU8,data,imageSize)}}function _glCompressedTexSubImage2D(target,level,xoffset,yoffset,width,height,format,imageSize,data){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,imageSize,data)}else{GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,HEAPU8,data,imageSize)}return}GLctx["compressedTexSubImage2D"](target,level,xoffset,yoffset,width,height,format,data?HEAPU8.subarray(data,data+imageSize):null)}function _glCompressedTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data){if(GLctx.currentPixelUnpackBufferBinding){GLctx["compressedTexSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data)}else{GLctx["compressedTexSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,HEAPU8,data,imageSize)}}function _glCopyBufferSubData(x0,x1,x2,x3,x4){GLctx["copyBufferSubData"](x0,x1,x2,x3,x4)}function _glCopyTexImage2D(x0,x1,x2,x3,x4,x5,x6,x7){GLctx["copyTexImage2D"](x0,x1,x2,x3,x4,x5,x6,x7)}function _glCopyTexSubImage2D(x0,x1,x2,x3,x4,x5,x6,x7){GLctx["copyTexSubImage2D"](x0,x1,x2,x3,x4,x5,x6,x7)}function _glCreateProgram(){var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id}function _glCreateShader(shaderType){var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);GL.shaders[id].shaderType=shaderType&1?"vs":"fs";return id}function _glCullFace(x0){GLctx["cullFace"](x0)}function _glDeleteBuffers(n,buffers){for(var i=0;i>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentArrayBufferBinding)GLctx.currentArrayBufferBinding=0;if(id==GLctx.currentElementArrayBufferBinding)GLctx.currentElementArrayBufferBinding=0;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}}function _glDeleteFramebuffers(n,framebuffers){for(var i=0;i>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}}function _glDeleteProgram(id){if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null}function _glDeleteQueries(n,ids){for(var i=0;i>2];var query=GL.queries[id];if(!query)continue;GLctx["deleteQuery"](query);GL.queries[id]=null}}function _glDeleteRenderbuffers(n,renderbuffers){for(var i=0;i>2];var renderbuffer=GL.renderbuffers[id];if(!renderbuffer)continue;GLctx.deleteRenderbuffer(renderbuffer);renderbuffer.name=0;GL.renderbuffers[id]=null}}function _glDeleteSamplers(n,samplers){for(var i=0;i>2];var sampler=GL.samplers[id];if(!sampler)continue;GLctx["deleteSampler"](sampler);sampler.name=0;GL.samplers[id]=null}}function _glDeleteShader(id){if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null}function _glDeleteSync(id){if(!id)return;var sync=GL.syncs[id];if(!sync){GL.recordError(1281);return}GLctx.deleteSync(sync);sync.name=0;GL.syncs[id]=null}function _glDeleteTextures(n,textures){for(var i=0;i>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}}function _glDeleteTransformFeedbacks(n,ids){for(var i=0;i>2];var transformFeedback=GL.transformFeedbacks[id];if(!transformFeedback)continue;GLctx["deleteTransformFeedback"](transformFeedback);transformFeedback.name=0;GL.transformFeedbacks[id]=null}}function _glDeleteVertexArrays(n,vaos){for(var i=0;i>2];GLctx["deleteVertexArray"](GL.vaos[id]);GL.vaos[id]=null}}function _glDepthFunc(x0){GLctx["depthFunc"](x0)}function _glDepthMask(flag){GLctx.depthMask(!!flag)}function _glDetachShader(program,shader){GLctx.detachShader(GL.programs[program],GL.shaders[shader])}function _glDisable(x0){GLctx["disable"](x0)}function _glDisableVertexAttribArray(index){var cb=GL.currentContext.clientBuffers[index];cb.enabled=false;GLctx.disableVertexAttribArray(index)}function _glDrawArrays(mode,first,count){GL.preDrawHandleClientVertexAttribBindings(first+count);GLctx.drawArrays(mode,first,count);GL.postDrawHandleClientVertexAttribBindings()}function _glDrawArraysInstanced(mode,first,count,primcount){GLctx["drawArraysInstanced"](mode,first,count,primcount)}var tempFixedLengthArray=[];function _glDrawBuffers(n,bufs){var bufArray=tempFixedLengthArray[n];for(var i=0;i>2]}GLctx["drawBuffers"](bufArray)}function _glDrawElements(mode,count,type,indices){var buf;if(!GLctx.currentElementArrayBufferBinding){var size=GL.calcBufLength(1,type,0,count);buf=GL.getTempIndexBuffer(size);GLctx.bindBuffer(34963,buf);GLctx.bufferSubData(34963,0,HEAPU8.subarray(indices,indices+size));indices=0}GL.preDrawHandleClientVertexAttribBindings(count);GLctx.drawElements(mode,count,type,indices);GL.postDrawHandleClientVertexAttribBindings(count);if(!GLctx.currentElementArrayBufferBinding){GLctx.bindBuffer(34963,null)}}function _glDrawElementsInstanced(mode,count,type,indices,primcount){GLctx["drawElementsInstanced"](mode,count,type,indices,primcount)}function _glEnable(x0){GLctx["enable"](x0)}function _glEnableVertexAttribArray(index){var cb=GL.currentContext.clientBuffers[index];cb.enabled=true;GLctx.enableVertexAttribArray(index)}function _glEndQuery(x0){GLctx["endQuery"](x0)}function _glEndTransformFeedback(){GLctx["endTransformFeedback"]()}function _glFenceSync(condition,flags){var sync=GLctx.fenceSync(condition,flags);if(sync){var id=GL.getNewId(GL.syncs);sync.name=id;GL.syncs[id]=sync;return id}else{return 0}}function _glFinish(){GLctx["finish"]()}function _glFlush(){GLctx["flush"]()}function emscriptenWebGLGetBufferBinding(target){switch(target){case 34962:target=34964;break;case 34963:target=34965;break;case 35051:target=35053;break;case 35052:target=35055;break;case 35982:target=35983;break;case 36662:target=36662;break;case 36663:target=36663;break;case 35345:target=35368;break}var buffer=GLctx.getParameter(target);if(buffer)return buffer.name|0;else return 0}function emscriptenWebGLValidateMapBufferTarget(target){switch(target){case 34962:case 34963:case 36662:case 36663:case 35051:case 35052:case 35882:case 35982:case 35345:return true;default:return false}}function _glFlushMappedBufferRange(target,offset,length){if(!emscriptenWebGLValidateMapBufferTarget(target)){GL.recordError(1280);err("GL_INVALID_ENUM in glFlushMappedBufferRange");return}var mapping=GL.mappedBuffers[emscriptenWebGLGetBufferBinding(target)];if(!mapping){GL.recordError(1282);err("buffer was never mapped in glFlushMappedBufferRange");return}if(!(mapping.access&16)){GL.recordError(1282);err("buffer was not mapped with GL_MAP_FLUSH_EXPLICIT_BIT in glFlushMappedBufferRange");return}if(offset<0||length<0||offset+length>mapping.length){GL.recordError(1281);err("invalid range in glFlushMappedBufferRange");return}GLctx.bufferSubData(target,mapping.offset,HEAPU8.subarray(mapping.mem+offset,mapping.mem+offset+length))}function _glFramebufferRenderbuffer(target,attachment,renderbuffertarget,renderbuffer){GLctx.framebufferRenderbuffer(target,attachment,renderbuffertarget,GL.renderbuffers[renderbuffer])}function _glFramebufferTexture2D(target,attachment,textarget,texture,level){GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)}function _glFramebufferTextureLayer(target,attachment,texture,level,layer){GLctx.framebufferTextureLayer(target,attachment,GL.textures[texture],level,layer)}function _glFrontFace(x0){GLctx["frontFace"](x0)}function __glGenObject(n,buffers,createFunction,objectTable){for(var i=0;i>2]=id}}function _glGenBuffers(n,buffers){__glGenObject(n,buffers,"createBuffer",GL.buffers)}function _glGenFramebuffers(n,ids){__glGenObject(n,ids,"createFramebuffer",GL.framebuffers)}function _glGenQueries(n,ids){__glGenObject(n,ids,"createQuery",GL.queries)}function _glGenRenderbuffers(n,renderbuffers){__glGenObject(n,renderbuffers,"createRenderbuffer",GL.renderbuffers)}function _glGenSamplers(n,samplers){__glGenObject(n,samplers,"createSampler",GL.samplers)}function _glGenTextures(n,textures){__glGenObject(n,textures,"createTexture",GL.textures)}function _glGenTransformFeedbacks(n,ids){__glGenObject(n,ids,"createTransformFeedback",GL.transformFeedbacks)}function _glGenVertexArrays(n,arrays){__glGenObject(n,arrays,"createVertexArray",GL.vaos)}function _glGenerateMipmap(x0){GLctx["generateMipmap"](x0)}function __glGetActiveAttribOrUniform(funcName,program,index,bufSize,length,size,type,name){program=GL.programs[program];var info=GLctx[funcName](program,index);if(info){var numBytesWrittenExclNull=name&&stringToUTF8(info.name,name,bufSize);if(length)HEAP32[length>>2]=numBytesWrittenExclNull;if(size)HEAP32[size>>2]=info.size;if(type)HEAP32[type>>2]=info.type}}function _glGetActiveAttrib(program,index,bufSize,length,size,type,name){__glGetActiveAttribOrUniform("getActiveAttrib",program,index,bufSize,length,size,type,name)}function _glGetActiveUniform(program,index,bufSize,length,size,type,name){__glGetActiveAttribOrUniform("getActiveUniform",program,index,bufSize,length,size,type,name)}function _glGetActiveUniformBlockName(program,uniformBlockIndex,bufSize,length,uniformBlockName){program=GL.programs[program];var result=GLctx["getActiveUniformBlockName"](program,uniformBlockIndex);if(!result)return;if(uniformBlockName&&bufSize>0){var numBytesWrittenExclNull=stringToUTF8(result,uniformBlockName,bufSize);if(length)HEAP32[length>>2]=numBytesWrittenExclNull}else{if(length)HEAP32[length>>2]=0}}function _glGetActiveUniformBlockiv(program,uniformBlockIndex,pname,params){if(!params){GL.recordError(1281);return}program=GL.programs[program];if(pname==35393){var name=GLctx["getActiveUniformBlockName"](program,uniformBlockIndex);HEAP32[params>>2]=name.length+1;return}var result=GLctx["getActiveUniformBlockParameter"](program,uniformBlockIndex,pname);if(result===null)return;if(pname==35395){for(var i=0;i>2]=result[i]}}else{HEAP32[params>>2]=result}}function _glGetActiveUniformsiv(program,uniformCount,uniformIndices,pname,params){if(!params){GL.recordError(1281);return}if(uniformCount>0&&uniformIndices==0){GL.recordError(1281);return}program=GL.programs[program];var ids=[];for(var i=0;i>2])}var result=GLctx["getActiveUniforms"](program,ids,pname);if(!result)return;var len=result.length;for(var i=0;i>2]=result[i]}}function _glGetAttribLocation(program,name){return GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name))}function _glGetError(){var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error}function _glGetFramebufferAttachmentParameteriv(target,attachment,pname,params){var result=GLctx.getFramebufferAttachmentParameter(target,attachment,pname);if(result instanceof WebGLRenderbuffer||result instanceof WebGLTexture){result=result.name|0}HEAP32[params>>2]=result}function writeI53ToI64(ptr,num){HEAPU32[ptr>>2]=num;HEAPU32[ptr+4>>2]=(num-HEAPU32[ptr>>2])/4294967296}function emscriptenWebGLGetIndexed(target,index,data,type){if(!data){GL.recordError(1281);return}var result=GLctx["getIndexedParameter"](target,index);var ret;switch(typeof result){case"boolean":ret=result?1:0;break;case"number":ret=result;break;case"object":if(result===null){switch(target){case 35983:case 35368:ret=0;break;default:{GL.recordError(1280);return}}}else if(result instanceof WebGLBuffer){ret=result.name|0}else{GL.recordError(1280);return}break;default:GL.recordError(1280);return}switch(type){case 1:writeI53ToI64(data,ret);break;case 0:HEAP32[data>>2]=ret;break;case 2:HEAPF32[data>>2]=ret;break;case 4:HEAP8[data>>0]=ret?1:0;break;default:throw"internal emscriptenWebGLGetIndexed() error, bad type: "+type}}function _glGetIntegeri_v(target,index,data){emscriptenWebGLGetIndexed(target,index,data,0)}function emscriptenWebGLGet(name_,p,type){if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33390:ret=1048576;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}var exts=GLctx.getSupportedExtensions()||[];ret=2*exts.length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i>>0]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err("GL_INVALID_ENUM in glGet"+type+"v: Unknown object returned from WebGL getParameter("+name_+")! (error: "+e+")");return}}break;default:GL.recordError(1280);err("GL_INVALID_ENUM in glGet"+type+"v: Native code calling glGet"+type+"v("+name_+") and it returns "+result+" of type "+typeof result+"!");return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p>>0]=ret?1:0;break}}function _glGetIntegerv(name_,p){emscriptenWebGLGet(name_,p,0)}function _glGetInternalformativ(target,internalformat,pname,bufSize,params){if(bufSize<0){GL.recordError(1281);return}if(!params){GL.recordError(1281);return}var ret=GLctx["getInternalformatParameter"](target,internalformat,pname);if(ret===null)return;for(var i=0;i>2]=ret[i]}}function _glGetProgramBinary(program,bufSize,length,binaryFormat,binary){GL.recordError(1282)}function _glGetProgramInfoLog(program,maxLength,length,infoLog){var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _glGetProgramiv(program,pname,p){if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){for(var i=0;i>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){for(var i=0;i>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){for(var i=0;i>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}}function _glGetQueryObjectuiv(id,pname,params){if(!params){GL.recordError(1281);return}var query=GL.queries[id];var param=GLctx["getQueryParameter"](query,pname);var ret;if(typeof param=="boolean"){ret=param?1:0}else{ret=param}HEAP32[params>>2]=ret}function _glGetQueryiv(target,pname,params){if(!params){GL.recordError(1281);return}HEAP32[params>>2]=GLctx["getQuery"](target,pname)}function _glGetRenderbufferParameteriv(target,pname,params){if(!params){GL.recordError(1281);return}HEAP32[params>>2]=GLctx.getRenderbufferParameter(target,pname)}function _glGetShaderInfoLog(shader,maxLength,length,infoLog){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _glGetShaderPrecisionFormat(shaderType,precisionType,range,precision){var result=GLctx.getShaderPrecisionFormat(shaderType,precisionType);HEAP32[range>>2]=result.rangeMin;HEAP32[range+4>>2]=result.rangeMax;HEAP32[precision>>2]=result.precision}function _glGetShaderSource(shader,bufSize,length,source){var result=GLctx.getShaderSource(GL.shaders[shader]);if(!result)return;var numBytesWrittenExclNull=bufSize>0&&source?stringToUTF8(result,source,bufSize):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull}function _glGetShaderiv(shader,pname,p){if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}}function _glGetString(name_){var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:var exts=GLctx.getSupportedExtensions()||[];exts=exts.concat(exts.map(function(e){return"GL_"+e}));ret=stringToNewUTF8(exts.join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s&&stringToNewUTF8(s);break;case 7938:var glVersion=GLctx.getParameter(7938);if(GL.currentContext.version>=2)glVersion="OpenGL ES 3.0 ("+glVersion+")";else{glVersion="OpenGL ES 2.0 ("+glVersion+")"}ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion="OpenGL ES GLSL ES "+ver_num[1]+" ("+glslVersion+")"}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret}function _glGetStringi(name,index){if(GL.currentContext.version<2){GL.recordError(1282);return 0}var stringiCache=GL.stringiCache[name];if(stringiCache){if(index<0||index>=stringiCache.length){GL.recordError(1281);return 0}return stringiCache[index]}switch(name){case 7939:var exts=GLctx.getSupportedExtensions()||[];exts=exts.concat(exts.map(function(e){return"GL_"+e}));exts=exts.map(function(e){return stringToNewUTF8(e)});stringiCache=GL.stringiCache[name]=exts;if(index<0||index>=stringiCache.length){GL.recordError(1281);return 0}return stringiCache[index];default:GL.recordError(1280);return 0}}function _glGetTexParameteriv(target,pname,params){if(!params){GL.recordError(1281);return}HEAP32[params>>2]=GLctx.getTexParameter(target,pname)}function _glGetUniformBlockIndex(program,uniformBlockName){return GLctx["getUniformBlockIndex"](GL.programs[program],UTF8ToString(uniformBlockName))}function _glGetUniformIndices(program,uniformCount,uniformNames,uniformIndices){if(!uniformIndices){GL.recordError(1281);return}if(uniformCount>0&&(uniformNames==0||uniformIndices==0)){GL.recordError(1281);return}program=GL.programs[program];var names=[];for(var i=0;i>2]));var result=GLctx["getUniformIndices"](program,names);if(!result)return;var len=result.length;for(var i=0;i>2]=result[i]}}function _glGetUniformLocation(program,name){function getLeftBracePos(name){return name.slice(-1)=="]"&&name.lastIndexOf("[")}name=UTF8ToString(name);if(program=GL.programs[program]){var uniformLocsById=program.uniformLocsById;var uniformSizeAndIdsByName=program.uniformSizeAndIdsByName;var i,j;var arrayIndex=0;var uniformBaseName=name;var leftBrace=getLeftBracePos(name);if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};for(i=0;i0?nm.slice(0,lb):nm;var id=uniformSizeAndIdsByName[arrayName]?uniformSizeAndIdsByName[arrayName][1]:program.uniformIdCounter;program.uniformIdCounter=Math.max(id+sz,program.uniformIdCounter);uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex0?"["+webglLoc+"]":""))}return webglLoc}else{GL.recordError(1282)}}function emscriptenWebGLGetUniform(program,location,params,type){if(!params){GL.recordError(1281);return}program=GL.programs[program];var data=GLctx.getUniform(program,webglGetUniformLocation(location));if(typeof data=="number"||typeof data=="boolean"){switch(type){case 0:HEAP32[params>>2]=data;break;case 2:HEAPF32[params>>2]=data;break}}else{for(var i=0;i>2]=data[i];break;case 2:HEAPF32[params+i*4>>2]=data[i];break}}}}function _glGetUniformiv(program,location,params){emscriptenWebGLGetUniform(program,location,params,0)}function emscriptenWebGLGetVertexAttrib(index,pname,params,type){if(!params){GL.recordError(1281);return}if(GL.currentContext.clientBuffers[index].enabled){err("glGetVertexAttrib*v on client-side array: not supported, bad data returned")}var data=GLctx.getVertexAttrib(index,pname);if(pname==34975){HEAP32[params>>2]=data&&data["name"]}else if(typeof data=="number"||typeof data=="boolean"){switch(type){case 0:HEAP32[params>>2]=data;break;case 2:HEAPF32[params>>2]=data;break;case 5:HEAP32[params>>2]=Math.fround(data);break}}else{for(var i=0;i>2]=data[i];break;case 2:HEAPF32[params+i*4>>2]=data[i];break;case 5:HEAP32[params+i*4>>2]=Math.fround(data[i]);break}}}}function _glGetVertexAttribiv(index,pname,params){emscriptenWebGLGetVertexAttrib(index,pname,params,5)}function _glInvalidateFramebuffer(target,numAttachments,attachments){var list=tempFixedLengthArray[numAttachments];for(var i=0;i>2]}GLctx["invalidateFramebuffer"](target,list)}function _glIsEnabled(x0){return GLctx["isEnabled"](x0)}function _glIsVertexArray(array){var vao=GL.vaos[array];if(!vao)return 0;return GLctx["isVertexArray"](vao)}function _glLinkProgram(program){program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={};[program["vs"],program["fs"]].forEach(function(s){Object.keys(s.explicitUniformLocations).forEach(function(shaderLocation){var loc=s.explicitUniformLocations[shaderLocation];program.uniformSizeAndIdsByName[shaderLocation]=[1,loc];program.uniformIdCounter=Math.max(program.uniformIdCounter,loc+1)})});function copyKeys(dst,src){Object.keys(src).forEach(function(key){dst[key]=src[key]})}program.explicitUniformBindings={};program.explicitSamplerBindings={};[program["vs"],program["fs"]].forEach(function(s){copyKeys(program.explicitUniformBindings,s.explicitUniformBindings);copyKeys(program.explicitSamplerBindings,s.explicitSamplerBindings)});program.explicitProgramBindingsApplied=0}function _glMapBufferRange(target,offset,length,access){if(access!=26&&access!=10){err("glMapBufferRange is only supported when access is MAP_WRITE|INVALIDATE_BUFFER");return 0}if(!emscriptenWebGLValidateMapBufferTarget(target)){GL.recordError(1280);err("GL_INVALID_ENUM in glMapBufferRange");return 0}var mem=_malloc(length);if(!mem)return 0;GL.mappedBuffers[emscriptenWebGLGetBufferBinding(target)]={offset:offset,length:length,mem:mem,access:access};return mem}function _glPixelStorei(pname,param){if(pname==3317){GL.unpackAlignment=param}GLctx.pixelStorei(pname,param)}function _glPolygonOffset(x0,x1){GLctx["polygonOffset"](x0,x1)}function _glProgramBinary(program,binaryFormat,binary,length){GL.recordError(1280)}function _glProgramParameteri(program,pname,value){GL.recordError(1280)}function _glReadBuffer(x0){GLctx["readBuffer"](x0)}function computeUnpackAlignedImageSize(width,height,sizePerPixel,alignment){function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=width*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,alignment);return height*alignedRowSize}function __colorChannelsInGlTextureFormat(format){var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1}function heapObjectForWebGLType(type){type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16}function heapAccessShiftForWebGLHeap(heap){return 31-Math.clz32(heap.BYTES_PER_ELEMENT)}function emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat){var heap=heapObjectForWebGLType(type);var shift=heapAccessShiftForWebGLHeap(heap);var byteSize=1<>shift,pixels+bytes>>shift)}function _glReadPixels(x,y,width,height,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelPackBufferBinding){GLctx.readPixels(x,y,width,height,format,type,pixels)}else{var heap=heapObjectForWebGLType(type);GLctx.readPixels(x,y,width,height,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}return}var pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,format);if(!pixelData){GL.recordError(1280);return}GLctx.readPixels(x,y,width,height,format,type,pixelData)}function _glRenderbufferStorage(x0,x1,x2,x3){GLctx["renderbufferStorage"](x0,x1,x2,x3)}function _glRenderbufferStorageMultisample(x0,x1,x2,x3,x4){GLctx["renderbufferStorageMultisample"](x0,x1,x2,x3,x4)}function _glSamplerParameteri(sampler,pname,param){GLctx["samplerParameteri"](GL.samplers[sampler],pname,param)}function _glScissor(x0,x1,x2,x3){GLctx["scissor"](x0,x1,x2,x3)}function find_closing_parens_index(arr,i,opening="(",closing=")"){for(var nesting=0;i32)}function nextWhitespace(str,i){while(!isWhitespace(str,i))++i;return i}function classifyChar(str,idx){var cc=str.charCodeAt(idx);if(cc>32){if(cc<48)return 1;if(cc<58)return 2;if(cc<65)return 1;if(cc<91||cc==95)return 3;if(cc<97)return 1;if(cc<123)return 3;return 1}return cc<33?0:4}function tokenize(exprString,keepWhitespace){var out=[],len=exprString.length;for(var i=0;i<=len;++i){var kind=classifyChar(exprString,i);if(kind==2||kind==3){for(var j=i+1;j<=len;++j){var kind2=classifyChar(exprString,j);if(kind2!=kind&&(kind2!=2||kind!=3)){out.push(exprString.substring(i,j));i=j-1;break}}}else if(kind==1){var op2=exprString.substr(i,2);if(["<=",">=","==","!=","&&","||"].includes(op2)){out.push(op2);++i}else{out.push(exprString[i])}}}return out}function expandMacros(str,lineStart,lineEnd){if(lineEnd===undefined)lineEnd=str.length;var len=str.length;var out="";for(var i=lineStart;i1||typeof tokens[0]!="function"){tokens=function(tokens){var i,j,p,operatorAndPriority=-2;for(j=0;j",">=","==","!=","&&","||","("].indexOf(tokens[j]))>operatorAndPriority){i=j;operatorAndPriority=p}}if(operatorAndPriority==13){var j=find_closing_parens_index(tokens,i);if(j){tokens.splice(i,j+1-i,buildExprTree(tokens.slice(i+1,j)));return tokens}}if(operatorAndPriority==4){i=tokens.lastIndexOf("!");var innerExpr=buildExprTree(tokens.slice(i+1,i+2));tokens.splice(i,2,function(){return!innerExpr()});return tokens}if(operatorAndPriority>=0){var left=buildExprTree(tokens.slice(0,i));var right=buildExprTree(tokens.slice(i+1));switch(tokens[i]){case"&&":return[function(){return left()&&right()}];case"||":return[function(){return left()||right()}];case"==":return[function(){return left()==right()}];case"!=":return[function(){return left()!=right()}];case"<":return[function(){return left()":return[function(){return left()>right()}];case">=":return[function(){return left()>=right()}];case"+":return[function(){return left()+right()}];case"-":return[function(){return left()-right()}];case"*":return[function(){return left()*right()}];case"/":return[function(){return Math.floor(left()/right())}]}}var num=jstoi_q(tokens[i]);return[function(){return num}]}(tokens)}return tokens[0]}for(;i0){var macroEnd=expression.indexOf(")",macroStart);let params=expression.substring(macroStart+1,macroEnd).split(",").map(x=>x.trim());let value=tokenize(expression.substring(macroEnd+1).trim());defs[expression.substring(0,macroStart)]=function(args){var ret="";value.forEach(x=>{var argIndex=params.indexOf(x);ret+=argIndex>=0?args[argIndex]:x});return ret}}else{let value=expandMacros(expression.substring(firstWs+1).trim(),0);defs[expression.substring(0,firstWs)]=function(){return value}}}break;case"undef":if(thisLineIsInActivePreprocessingBlock)delete defs[expression];break;default:if(directive!="version"&&directive!="pragma"&&directive!="extension"){}out+=expandMacros(code,lineStart,i)+"\n"}}return out}function remove_cpp_comments_in_shaders(code){var i=0,out="",ch,next,len=code.length;for(;i=0&&explicitUniformLocations[match[5]]<1048576)){console.error('Specified an out of range layout(location=x) directive "'+explicitUniformLocations[match[5]]+'"! ('+match[0]+")");GL.recordError(1281);return}}source=source.replace(regex,"$2");GL.shaders[shader].explicitUniformLocations=explicitUniformLocations;var bindingRegex=/layout\s*\(.*?binding\s*=\s*(-?\d+).*?\)\s*uniform\s+(\w+)\s+(\w+)?/g,samplerBindings={},uniformBindings={},bindingMatch;while(bindingMatch=bindingRegex.exec(source)){var arrayLength=1;for(var i=bindingMatch.index;i=0&&binding+arrayLength<=numBindingPoints)){console.error('Specified an out of range layout(binding=x) directive "'+binding+'"! ('+bindingMatch[0]+"). Valid range is [0, "+numBindingPoints+"-1]");GL.recordError(1281);return}}source=source.replace(/layout\s*\(.*?binding\s*=\s*([-\d]+).*?\)/g,"");source=source.replace(/(layout\s*\((.*?)),\s*binding\s*=\s*([-\d]+)\)/g,"$1)");source=source.replace(/layout\s*\(\s*binding\s*=\s*([-\d]+)\s*,(.*?)\)/g,"layout($2)");GL.shaders[shader].explicitSamplerBindings=samplerBindings;GL.shaders[shader].explicitUniformBindings=uniformBindings;GLctx.shaderSource(GL.shaders[shader],source)}function _glStencilFuncSeparate(x0,x1,x2,x3){GLctx["stencilFuncSeparate"](x0,x1,x2,x3)}function _glStencilMask(x0){GLctx["stencilMask"](x0)}function _glStencilOpSeparate(x0,x1,x2,x3){GLctx["stencilOpSeparate"](x0,x1,x2,x3)}function _glTexImage2D(target,level,internalFormat,width,height,border,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,null)}return}GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null)}function _glTexImage3D(target,level,internalFormat,width,height,depth,border,format,type,pixels){if(GLctx.currentPixelUnpackBufferBinding){GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx["texImage3D"](target,level,internalFormat,width,height,depth,border,format,type,null)}}function _glTexParameterf(x0,x1,x2){GLctx["texParameterf"](x0,x1,x2)}function _glTexParameteri(x0,x1,x2){GLctx["texParameteri"](x0,x1,x2)}function _glTexParameteriv(target,pname,params){var param=HEAP32[params>>2];GLctx.texParameteri(target,pname,param)}function _glTexStorage2D(x0,x1,x2,x3,x4){GLctx["texStorage2D"](x0,x1,x2,x3,x4)}function _glTexStorage3D(x0,x1,x2,x3,x4,x5){GLctx["texStorage3D"](x0,x1,x2,x3,x4,x5)}function _glTexSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels){if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,null)}return}var pixelData=null;if(pixels)pixelData=emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)}function _glTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels){if(GLctx.currentPixelUnpackBufferBinding){GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels)}else if(pixels){var heap=heapObjectForWebGLType(type);GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,heap,pixels>>heapAccessShiftForWebGLHeap(heap))}else{GLctx["texSubImage3D"](target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,null)}}function _glTransformFeedbackVaryings(program,count,varyings,bufferMode){program=GL.programs[program];var vars=[];for(var i=0;i>2]));GLctx["transformFeedbackVaryings"](program,vars,bufferMode)}var miniTempWebGLFloatBuffers=[];function _glUniform1fv(location,count,value){if(GL.currentContext.version>=2){GLctx.uniform1fv(webglGetUniformLocation(location),HEAPF32,value>>2,count);return}if(count<=288){var view=miniTempWebGLFloatBuffers[count-1];for(var i=0;i>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*4>>2)}GLctx.uniform1fv(webglGetUniformLocation(location),view)}function _glUniform1i(location,v0){GLctx.uniform1i(webglGetUniformLocation(location),v0)}var __miniTempWebGLIntBuffers=[];function _glUniform1iv(location,count,value){if(GL.currentContext.version>=2){GLctx.uniform1iv(webglGetUniformLocation(location),HEAP32,value>>2,count);return}if(count<=288){var view=__miniTempWebGLIntBuffers[count-1];for(var i=0;i>2]}}else{var view=HEAP32.subarray(value>>2,value+count*4>>2)}GLctx.uniform1iv(webglGetUniformLocation(location),view)}function _glUniform1uiv(location,count,value){GLctx.uniform1uiv(webglGetUniformLocation(location),HEAPU32,value>>2,count)}function _glUniform2fv(location,count,value){if(GL.currentContext.version>=2){GLctx.uniform2fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*2);return}if(count<=144){var view=miniTempWebGLFloatBuffers[2*count-1];for(var i=0;i<2*count;i+=2){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*8>>2)}GLctx.uniform2fv(webglGetUniformLocation(location),view)}function _glUniform2iv(location,count,value){if(GL.currentContext.version>=2){GLctx.uniform2iv(webglGetUniformLocation(location),HEAP32,value>>2,count*2);return}if(count<=144){var view=__miniTempWebGLIntBuffers[2*count-1];for(var i=0;i<2*count;i+=2){view[i]=HEAP32[value+4*i>>2];view[i+1]=HEAP32[value+(4*i+4)>>2]}}else{var view=HEAP32.subarray(value>>2,value+count*8>>2)}GLctx.uniform2iv(webglGetUniformLocation(location),view)}function _glUniform2uiv(location,count,value){GLctx.uniform2uiv(webglGetUniformLocation(location),HEAPU32,value>>2,count*2)}function _glUniform3fv(location,count,value){if(GL.currentContext.version>=2){GLctx.uniform3fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*3);return}if(count<=96){var view=miniTempWebGLFloatBuffers[3*count-1];for(var i=0;i<3*count;i+=3){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*12>>2)}GLctx.uniform3fv(webglGetUniformLocation(location),view)}function _glUniform3iv(location,count,value){if(GL.currentContext.version>=2){GLctx.uniform3iv(webglGetUniformLocation(location),HEAP32,value>>2,count*3);return}if(count<=96){var view=__miniTempWebGLIntBuffers[3*count-1];for(var i=0;i<3*count;i+=3){view[i]=HEAP32[value+4*i>>2];view[i+1]=HEAP32[value+(4*i+4)>>2];view[i+2]=HEAP32[value+(4*i+8)>>2]}}else{var view=HEAP32.subarray(value>>2,value+count*12>>2)}GLctx.uniform3iv(webglGetUniformLocation(location),view)}function _glUniform3uiv(location,count,value){GLctx.uniform3uiv(webglGetUniformLocation(location),HEAPU32,value>>2,count*3)}function _glUniform4fv(location,count,value){if(GL.currentContext.version>=2){GLctx.uniform4fv(webglGetUniformLocation(location),HEAPF32,value>>2,count*4);return}if(count<=72){var view=miniTempWebGLFloatBuffers[4*count-1];var heap=HEAPF32;value>>=2;for(var i=0;i<4*count;i+=4){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3]}}else{var view=HEAPF32.subarray(value>>2,value+count*16>>2)}GLctx.uniform4fv(webglGetUniformLocation(location),view)}function _glUniform4iv(location,count,value){if(GL.currentContext.version>=2){GLctx.uniform4iv(webglGetUniformLocation(location),HEAP32,value>>2,count*4);return}if(count<=72){var view=__miniTempWebGLIntBuffers[4*count-1];for(var i=0;i<4*count;i+=4){view[i]=HEAP32[value+4*i>>2];view[i+1]=HEAP32[value+(4*i+4)>>2];view[i+2]=HEAP32[value+(4*i+8)>>2];view[i+3]=HEAP32[value+(4*i+12)>>2]}}else{var view=HEAP32.subarray(value>>2,value+count*16>>2)}GLctx.uniform4iv(webglGetUniformLocation(location),view)}function _glUniform4uiv(location,count,value){GLctx.uniform4uiv(webglGetUniformLocation(location),HEAPU32,value>>2,count*4)}function _glUniformBlockBinding(program,uniformBlockIndex,uniformBlockBinding){program=GL.programs[program];GLctx["uniformBlockBinding"](program,uniformBlockIndex,uniformBlockBinding)}function _glUniformMatrix3fv(location,count,transpose,value){if(GL.currentContext.version>=2){GLctx.uniformMatrix3fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*9);return}if(count<=32){var view=miniTempWebGLFloatBuffers[9*count-1];for(var i=0;i<9*count;i+=9){view[i]=HEAPF32[value+4*i>>2];view[i+1]=HEAPF32[value+(4*i+4)>>2];view[i+2]=HEAPF32[value+(4*i+8)>>2];view[i+3]=HEAPF32[value+(4*i+12)>>2];view[i+4]=HEAPF32[value+(4*i+16)>>2];view[i+5]=HEAPF32[value+(4*i+20)>>2];view[i+6]=HEAPF32[value+(4*i+24)>>2];view[i+7]=HEAPF32[value+(4*i+28)>>2];view[i+8]=HEAPF32[value+(4*i+32)>>2]}}else{var view=HEAPF32.subarray(value>>2,value+count*36>>2)}GLctx.uniformMatrix3fv(webglGetUniformLocation(location),!!transpose,view)}function _glUniformMatrix4fv(location,count,transpose,value){if(GL.currentContext.version>=2){GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count-1];var heap=HEAPF32;value>>=2;for(var i=0;i<16*count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)}function _glUnmapBuffer(target){if(!emscriptenWebGLValidateMapBufferTarget(target)){GL.recordError(1280);err("GL_INVALID_ENUM in glUnmapBuffer");return 0}var buffer=emscriptenWebGLGetBufferBinding(target);var mapping=GL.mappedBuffers[buffer];if(!mapping){GL.recordError(1282);err("buffer was never mapped in glUnmapBuffer");return 0}GL.mappedBuffers[buffer]=null;if(!(mapping.access&16))if(GL.currentContext.version>=2){GLctx.bufferSubData(target,mapping.offset,HEAPU8,mapping.mem,mapping.length)}else{GLctx.bufferSubData(target,mapping.offset,HEAPU8.subarray(mapping.mem,mapping.mem+mapping.length))}_free(mapping.mem);return 1}function webglApplyExplicitProgramBindings(){var p=GLctx.currentProgram;if(!p.explicitProgramBindingsApplied){if(GL.currentContext.version>=2){Object.keys(p.explicitUniformBindings).forEach(function(ubo){var bindings=p.explicitUniformBindings[ubo];for(var i=0;i1?"["+i+"]":""));GLctx.uniformBlockBinding(p,blockIndex,bindings[0]+i)}})}Object.keys(p.explicitSamplerBindings).forEach(function(sampler){var bindings=p.explicitSamplerBindings[sampler];for(var i=0;i>2],HEAPF32[v+4>>2],HEAPF32[v+8>>2],HEAPF32[v+12>>2])}function _glVertexAttribIPointer(index,size,type,stride,ptr){var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=false;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribIPointer(index,size,type,stride,ptr)};return}cb.clientside=false;GLctx["vertexAttribIPointer"](index,size,type,stride,ptr)}function _glVertexAttribPointer(index,size,type,normalized,stride,ptr){var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=normalized;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribPointer(index,size,type,normalized,stride,ptr)};return}cb.clientside=false;GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)}function _glViewport(x0,x1,x2,x3){GLctx["viewport"](x0,x1,x2,x3)}function _llvm_eh_typeid_for(type){return type}function _mktime(tmPtr){_tzset();var date=new Date(HEAP32[tmPtr+20>>2]+1900,HEAP32[tmPtr+16>>2],HEAP32[tmPtr+12>>2],HEAP32[tmPtr+8>>2],HEAP32[tmPtr+4>>2],HEAP32[tmPtr>>2],0);var dst=HEAP32[tmPtr+32>>2];var guessedOffset=date.getTimezoneOffset();var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dstOffset=Math.min(winterOffset,summerOffset);if(dst<0){HEAP32[tmPtr+32>>2]=Number(summerOffset!=winterOffset&&dstOffset==guessedOffset)}else if(dst>0!=(dstOffset==guessedOffset)){var nonDstOffset=Math.max(winterOffset,summerOffset);var trueOffset=dst>0?dstOffset:nonDstOffset;date.setTime(date.getTime()+(trueOffset-guessedOffset)*6e4)}HEAP32[tmPtr+24>>2]=date.getDay();var yday=(date.getTime()-start.getTime())/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();return date.getTime()/1e3|0}function _setTempRet0(val){setTempRet0(val)}function __isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function __arraySum(array,index){var sum=0;for(var i=0;i<=index;sum+=array[i++]){}return sum}var __MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31];var __MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31];function __addDays(date,days){var newDate=new Date(date.getTime());while(days>0){var leap=__isLeapYear(newDate.getFullYear());var currentMonth=newDate.getMonth();var daysInCurrentMonth=(leap?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR)[currentMonth];if(days>daysInCurrentMonth-newDate.getDate()){days-=daysInCurrentMonth-newDate.getDate()+1;newDate.setDate(1);if(currentMonth<11){newDate.setMonth(currentMonth+1)}else{newDate.setMonth(0);newDate.setFullYear(newDate.getFullYear()+1)}}else{newDate.setDate(newDate.getDate()+days);return newDate}}return newDate}function _strftime(s,maxsize,format,tm){var tm_zone=HEAP32[tm+40>>2];var date={tm_sec:HEAP32[tm>>2],tm_min:HEAP32[tm+4>>2],tm_hour:HEAP32[tm+8>>2],tm_mday:HEAP32[tm+12>>2],tm_mon:HEAP32[tm+16>>2],tm_year:HEAP32[tm+20>>2],tm_wday:HEAP32[tm+24>>2],tm_yday:HEAP32[tm+28>>2],tm_isdst:HEAP32[tm+32>>2],tm_gmtoff:HEAP32[tm+36>>2],tm_zone:tm_zone?UTF8ToString(tm_zone):""};var pattern=UTF8ToString(format);var EXPANSION_RULES_1={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var rule in EXPANSION_RULES_1){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_1[rule])}var WEEKDAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];function leadingSomething(value,digits,character){var str=typeof value==="number"?value.toString():value||"";while(str.length0?1:0}var compare;if((compare=sgn(date1.getFullYear()-date2.getFullYear()))===0){if((compare=sgn(date1.getMonth()-date2.getMonth()))===0){compare=sgn(date1.getDate()-date2.getDate())}}return compare}function getFirstWeekStartDate(janFourth){switch(janFourth.getDay()){case 0:return new Date(janFourth.getFullYear()-1,11,29);case 1:return janFourth;case 2:return new Date(janFourth.getFullYear(),0,3);case 3:return new Date(janFourth.getFullYear(),0,2);case 4:return new Date(janFourth.getFullYear(),0,1);case 5:return new Date(janFourth.getFullYear()-1,11,31);case 6:return new Date(janFourth.getFullYear()-1,11,30)}}function getWeekBasedYear(date){var thisDate=__addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);var janFourthThisYear=new Date(thisDate.getFullYear(),0,4);var janFourthNextYear=new Date(thisDate.getFullYear()+1,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);if(compareByDay(firstWeekStartThisYear,thisDate)<=0){if(compareByDay(firstWeekStartNextYear,thisDate)<=0){return thisDate.getFullYear()+1}else{return thisDate.getFullYear()}}else{return thisDate.getFullYear()-1}}var EXPANSION_RULES_2={"%a":function(date){return WEEKDAYS[date.tm_wday].substring(0,3)},"%A":function(date){return WEEKDAYS[date.tm_wday]},"%b":function(date){return MONTHS[date.tm_mon].substring(0,3)},"%B":function(date){return MONTHS[date.tm_mon]},"%C":function(date){var year=date.tm_year+1900;return leadingNulls(year/100|0,2)},"%d":function(date){return leadingNulls(date.tm_mday,2)},"%e":function(date){return leadingSomething(date.tm_mday,2," ")},"%g":function(date){return getWeekBasedYear(date).toString().substring(2)},"%G":function(date){return getWeekBasedYear(date)},"%H":function(date){return leadingNulls(date.tm_hour,2)},"%I":function(date){var twelveHour=date.tm_hour;if(twelveHour==0)twelveHour=12;else if(twelveHour>12)twelveHour-=12;return leadingNulls(twelveHour,2)},"%j":function(date){return leadingNulls(date.tm_mday+__arraySum(__isLeapYear(date.tm_year+1900)?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR,date.tm_mon-1),3)},"%m":function(date){return leadingNulls(date.tm_mon+1,2)},"%M":function(date){return leadingNulls(date.tm_min,2)},"%n":function(){return"\n"},"%p":function(date){if(date.tm_hour>=0&&date.tm_hour<12){return"AM"}else{return"PM"}},"%S":function(date){return leadingNulls(date.tm_sec,2)},"%t":function(){return"\t"},"%u":function(date){return date.tm_wday||7},"%U":function(date){var janFirst=new Date(date.tm_year+1900,0,1);var firstSunday=janFirst.getDay()===0?janFirst:__addDays(janFirst,7-janFirst.getDay());var endDate=new Date(date.tm_year+1900,date.tm_mon,date.tm_mday);if(compareByDay(firstSunday,endDate)<0){var februaryFirstUntilEndMonth=__arraySum(__isLeapYear(endDate.getFullYear())?__MONTH_DAYS_LEAP:__MONTH_DAYS_REGULAR,endDate.getMonth()-1)-31;var firstSundayUntilEndJanuary=31-firstSunday.getDate();var days=firstSundayUntilEndJanuary+februaryFirstUntilEndMonth+endDate.getDate();return leadingNulls(Math.ceil(days/7),2)}return compareByDay(firstSunday,janFirst)===0?"01":"00"},"%V":function(date){var janFourthThisYear=new Date(date.tm_year+1900,0,4);var janFourthNextYear=new Date(date.tm_year+1901,0,4);var firstWeekStartThisYear=getFirstWeekStartDate(janFourthThisYear);var firstWeekStartNextYear=getFirstWeekStartDate(janFourthNextYear);var endDate=__addDays(new Date(date.tm_year+1900,0,1),date.tm_yday);if(compareByDay(endDate,firstWeekStartThisYear)<0){return"53"}if(compareByDay(firstWeekStartNextYear,endDate)<=0){return"01"}var daysDifference;if(firstWeekStartThisYear.getFullYear()=0;off=Math.abs(off)/60;off=off/60*100+off%60;return(ahead?"+":"-")+String("0000"+off).slice(-4)},"%Z":function(date){return date.tm_zone},"%%":function(){return"%"}};for(var rule in EXPANSION_RULES_2){if(pattern.includes(rule)){pattern=pattern.replace(new RegExp(rule,"g"),EXPANSION_RULES_2[rule](date))}}var bytes=intArrayFromString(pattern,false);if(bytes.length>maxsize){return 0}writeArrayToMemory(bytes,s);return bytes.length-1}function _time(ptr){var ret=Date.now()/1e3|0;if(ptr){HEAP32[ptr>>2]=ret}return ret}function setFileTime(path,time){path=UTF8ToString(path);try{FS.utime(path,time,time);return 0}catch(e){if(!(e instanceof FS.ErrnoError))throw e+" : "+stackTrace();setErrNo(e.errno);return-1}}function _utime(path,times){var time;if(times){time=HEAP32[times+4>>2]*1e3}else{time=Date.now()}return setFileTime(path,time)}var FSNode=function(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.mounted=null;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.node_ops={};this.stream_ops={};this.rdev=rdev};var readMode=292|73;var writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(val){val?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(val){val?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}});FS.FSNode=FSNode;FS.staticInit();Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["requestFullscreen"]=function Module_requestFullscreen(lockPointer,resizeCanvas){Browser.requestFullscreen(lockPointer,resizeCanvas)};Module["requestAnimationFrame"]=function Module_requestAnimationFrame(func){Browser.requestAnimationFrame(func)};Module["setCanvasSize"]=function Module_setCanvasSize(width,height,noUpdates){Browser.setCanvasSize(width,height,noUpdates)};Module["pauseMainLoop"]=function Module_pauseMainLoop(){Browser.mainLoop.pause()};Module["resumeMainLoop"]=function Module_resumeMainLoop(){Browser.mainLoop.resume()};Module["getUserMedia"]=function Module_getUserMedia(){Browser.getUserMedia()};Module["createContext"]=function Module_createContext(canvas,useWebGL,setInModule,webGLContextAttributes){return Browser.createContext(canvas,useWebGL,setInModule,webGLContextAttributes)};var GLctx;for(var i=0;i<32;++i)tempFixedLengthArray.push(new Array(i));var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i+1)}var __miniTempWebGLIntBuffersStorage=new Int32Array(288);for(var i=0;i<288;++i){__miniTempWebGLIntBuffers[i]=__miniTempWebGLIntBuffersStorage.subarray(0,i+1)}function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}var asmLibraryArg={"we":_JS_Accelerometer_IsRunning,"vb":_JS_Accelerometer_Start,"ub":_JS_Accelerometer_Stop,"Be":_JS_Cursor_SetImage,"$a":_JS_Cursor_SetShow,"Ia":_JS_DOM_MapViewportCoordinateToElementLocalCoordinate,"ce":_JS_DOM_UnityCanvasSelector,"Xd":_JS_FileSystem_Initialize,"ea":_JS_FileSystem_Sync,"ye":_JS_Focus_Window,"ue":_JS_GravitySensor_IsRunning,"qb":_JS_GravitySensor_Start,"pb":_JS_GravitySensor_Stop,"te":_JS_Gyroscope_IsRunning,"ob":_JS_Gyroscope_Start,"nb":_JS_Gyroscope_Stop,"ve":_JS_LinearAccelerationSensor_IsRunning,"sb":_JS_LinearAccelerationSensor_Start,"rb":_JS_LinearAccelerationSensor_Stop,"ch":_JS_Log_Dump,"ge":_JS_Log_StackTrace,"xe":_JS_OrientationSensor_IsRunning,"xb":_JS_OrientationSensor_Start,"wb":_JS_OrientationSensor_Stop,"zb":_JS_RequestDeviceSensorPermissionsOnTouch,"_d":_JS_RunQuitCallbacks,"se":_JS_ScreenOrientation_DeInit,"ze":_JS_ScreenOrientation_Init,"da":_JS_ScreenOrientation_Lock,"Re":_JS_Sound_Create_Channel,"Ob":_JS_Sound_GetLength,"Ne":_JS_Sound_GetLoadState,"Le":_JS_Sound_Init,"Nb":_JS_Sound_Load,"Me":_JS_Sound_Load_PCM,"Ma":_JS_Sound_Play,"Na":_JS_Sound_ReleaseInstance,"Ab":_JS_Sound_ResumeIfNeeded,"Oe":_JS_Sound_Set3D,"Je":_JS_Sound_SetListenerOrientation,"Ke":_JS_Sound_SetListenerPosition,"Qb":_JS_Sound_SetLoop,"Pb":_JS_Sound_SetLoopPoints,"La":_JS_Sound_SetPaused,"fa":_JS_Sound_SetPitch,"Qe":_JS_Sound_SetPosition,"Pe":_JS_Sound_SetVolume,"qa":_JS_Sound_Stop,"ka":_JS_SystemInfo_GetCanvasClientSize,"Mb":_JS_SystemInfo_GetDocumentURL,"gb":_JS_SystemInfo_GetGPUInfo,"mb":_JS_SystemInfo_GetMatchWebGLToCanvasSize,"hb":_JS_SystemInfo_GetMemory,"ib":_JS_SystemInfo_GetOS,"kb":_JS_SystemInfo_GetPreferredDevicePixelRatio,"ie":_JS_SystemInfo_GetScreenSize,"Ce":_JS_SystemInfo_HasAstcHdr,"jb":_JS_SystemInfo_HasCursorLock,"re":_JS_SystemInfo_HasFullscreen,"sa":_JS_SystemInfo_HasWebGL,"de":_JS_SystemInfo_IsMobile,"be":_JS_UnityEngineShouldQuit,"o":___cxa_allocate_exception,"i":___cxa_begin_catch,"l":___cxa_end_catch,"e":___cxa_find_matching_catch_2,"a":___cxa_find_matching_catch_3,"Gc":___cxa_find_matching_catch_4,"Wa":___cxa_free_exception,"Rc":___cxa_rethrow,"V":___cxa_throw,"Wc":___gmtime_r,"Xc":___localtime_r,"f":___resumeException,"bd":___sys__newselect,"gd":___sys_access,"Pc":___sys_chmod,"Vd":___sys_connect,"N":___sys_fcntl64,"Ae":___sys_fstat64,"Mc":___sys_getcwd,"Jc":___sys_getdents64,"_c":___sys_getrusage,"Ve":___sys_getuid32,"ad":___sys_ioctl,"Qc":___sys_lstat64,"Lc":___sys_mkdir,"$c":___sys_mmap2,"Vc":___sys_munmap,"Ka":___sys_open,"eh":___sys_readlink,"rd":___sys_recvfrom,"Nc":___sys_rename,"Kc":___sys_rmdir,"Cd":___sys_sendto,"Sc":___sys_shutdown,"Tc":___sys_socket,"yb":___sys_stat64,"Se":___sys_statfs64,"Te":___sys_truncate64,"Oc":___sys_unlink,"v":_abort,"I":_clock,"Zc":_clock_getres,"fb":_clock_gettime,"Uc":_difftime,"ee":_dlclose,"la":_dlerror,"tb":_dlopen,"le":_dlsym,"Lb":_emscripten_asm_const_int_sync_on_main_thread,"$d":_emscripten_cancel_main_loop,"Zd":_emscripten_clear_interval,"pe":_emscripten_exit_fullscreen,"je":_emscripten_exit_pointerlock,"he":_emscripten_get_canvas_element_size,"oe":_emscripten_get_fullscreen_status,"Fa":_emscripten_get_gamepad_status,"Yc":_emscripten_get_heap_max,"H":_emscripten_get_now,"Ga":_emscripten_get_num_gamepads,"ae":_emscripten_html5_remove_all_event_listeners,"Ee":_emscripten_is_webgl_context_lost,"A":_emscripten_log,"T":_emscripten_longjmp,"vh":_emscripten_memcpy_big,"qe":_emscripten_request_fullscreen,"ke":_emscripten_request_pointerlock,"wh":_emscripten_resize_heap,"Ha":_emscripten_sample_gamepad_data,"lb":_emscripten_set_blur_callback_on_thread,"Ea":_emscripten_set_canvas_element_size,"me":_emscripten_set_focus_callback_on_thread,"ne":_emscripten_set_fullscreenchange_callback_on_thread,"Cb":_emscripten_set_gamepadconnected_callback_on_thread,"Bb":_emscripten_set_gamepaddisconnected_callback_on_thread,"Wd":_emscripten_set_interval,"na":_emscripten_set_keydown_callback_on_thread,"ma":_emscripten_set_keypress_callback_on_thread,"Ja":_emscripten_set_keyup_callback_on_thread,"Ud":_emscripten_set_main_loop,"Yd":_emscripten_set_main_loop_timing,"Jb":_emscripten_set_mousedown_callback_on_thread,"Ib":_emscripten_set_mousemove_callback_on_thread,"Kb":_emscripten_set_mouseup_callback_on_thread,"Db":_emscripten_set_touchcancel_callback_on_thread,"Fb":_emscripten_set_touchend_callback_on_thread,"Eb":_emscripten_set_touchmove_callback_on_thread,"Gb":_emscripten_set_touchstart_callback_on_thread,"Hb":_emscripten_set_wheel_callback_on_thread,"dh":_emscripten_thread_sleep,"Ge":_emscripten_webgl_create_context,"Fe":_emscripten_webgl_destroy_context,"oa":_emscripten_webgl_enable_extension,"De":_emscripten_webgl_get_current_context,"We":_emscripten_webgl_init_context_attributes,"pa":_emscripten_webgl_make_context_current,"wg":_environ_get,"Gg":_environ_sizes_get,"w":_exit,"W":_fd_close,"fe":_fd_fdstat_get,"db":_fd_read,"Td":_fd_seek,"Oa":_fd_write,"ra":_flock,"b":_getTempRet0,"He":_gethostbyaddr,"Ie":_gethostbyname,"Ue":_getpwuid,"ja":_gettimeofday,"Xg":_glActiveTexture,"Ug":_glAttachShader,"Yb":_glBeginQuery,"If":_glBeginTransformFeedback,"za":_glBindAttribLocation,"Tg":_glBindBuffer,"hf":_glBindBufferBase,"gf":_glBindBufferRange,"Qg":_glBindFramebuffer,"Rg":_glBindRenderbuffer,"bf":_glBindSampler,"Sg":_glBindTexture,"Bf":_glBindTransformFeedback,"Ef":_glBindVertexArray,"nc":_glBlendEquation,"oc":_glBlendEquationSeparate,"pc":_glBlendFuncSeparate,"tf":_glBlitFramebuffer,"Og":_glBufferData,"Pg":_glBufferSubData,"Ng":_glCheckFramebufferStatus,"Jg":_glClear,"Ze":_glClearBufferfi,"Ye":_glClearBufferfv,"Xe":_glClearBufferuiv,"Kg":_glClearColor,"Lg":_glClearDepthf,"Mg":_glClearStencil,"cd":_glClientWaitSync,"_a":_glColorMask,"Ig":_glCompileShader,"Fg":_glCompressedTexImage2D,"vf":_glCompressedTexImage3D,"Hg":_glCompressedTexSubImage2D,"zf":_glCompressedTexSubImage3D,"lf":_glCopyBufferSubData,"Eg":_glCopyTexImage2D,"mc":_glCopyTexSubImage2D,"Dg":_glCreateProgram,"Cg":_glCreateShader,"Bg":_glCullFace,"Ag":_glDeleteBuffers,"zg":_glDeleteFramebuffers,"yg":_glDeleteProgram,"Ta":_glDeleteQueries,"xg":_glDeleteRenderbuffers,"af":_glDeleteSamplers,"vg":_glDeleteShader,"Tb":_glDeleteSync,"ug":_glDeleteTextures,"Cf":_glDeleteTransformFeedbacks,"Gf":_glDeleteVertexArrays,"ya":_glDepthFunc,"xa":_glDepthMask,"tg":_glDetachShader,"sg":_glDisable,"rg":_glDisableVertexAttribArray,"og":_glDrawArrays,"nf":_glDrawArraysInstanced,"kf":_glDrawBuffers,"pg":_glDrawElements,"mf":_glDrawElementsInstanced,"qg":_glEnable,"ng":_glEnableVertexAttribArray,"Zb":_glEndQuery,"Jf":_glEndTransformFeedback,"Sb":_glFenceSync,"kg":_glFinish,"lg":_glFlush,"qf":_glFlushMappedBufferRange,"M":_glFramebufferRenderbuffer,"L":_glFramebufferTexture2D,"ta":_glFramebufferTextureLayer,"wa":_glFrontFace,"jg":_glGenBuffers,"fg":_glGenFramebuffers,"Xb":_glGenQueries,"gg":_glGenRenderbuffers,"$e":_glGenSamplers,"ig":_glGenTextures,"Df":_glGenTransformFeedbacks,"Hf":_glGenVertexArrays,"hg":_glGenerateMipmap,"bh":_glGetActiveAttrib,"Za":_glGetActiveUniform,"Qa":_glGetActiveUniformBlockName,"Z":_glGetActiveUniformBlockiv,"Y":_glGetActiveUniformsiv,"ah":_glGetAttribLocation,"eg":_glGetError,"dg":_glGetFramebufferAttachmentParameteriv,"Wg":_glGetIntegeri_v,"Aa":_glGetIntegerv,"df":_glGetInternalformativ,"Vb":_glGetProgramBinary,"Zg":_glGetProgramInfoLog,"P":_glGetProgramiv,"Lf":_glGetQueryObjectuiv,"Kf":_glGetQueryiv,"mg":_glGetRenderbufferParameteriv,"bg":_glGetShaderInfoLog,"lc":_glGetShaderPrecisionFormat,"cg":_glGetShaderSource,"Yg":_glGetShaderiv,"ag":_glGetString,"rf":_glGetStringi,"$f":_glGetTexParameteriv,"ef":_glGetUniformBlockIndex,"Pa":_glGetUniformIndices,"ga":_glGetUniformLocation,"kc":_glGetUniformiv,"$g":_glGetVertexAttribiv,"Sa":_glInvalidateFramebuffer,"Vg":_glIsEnabled,"Ff":_glIsVertexArray,"Zf":_glLinkProgram,"of":_glMapBufferRange,"_f":_glPixelStorei,"jc":_glPolygonOffset,"Wb":_glProgramBinary,"_e":_glProgramParameteri,"jf":_glReadBuffer,"$":_glReadPixels,"Yf":_glRenderbufferStorage,"sf":_glRenderbufferStorageMultisample,"cf":_glSamplerParameteri,"Ya":_glScissor,"Wf":_glShaderSource,"Xf":_glStencilFuncSeparate,"Uf":_glStencilMask,"Vf":_glStencilOpSeparate,"Sf":_glTexImage2D,"xf":_glTexImage3D,"Tf":_glTexParameterf,"Xa":_glTexParameteri,"Rf":_glTexParameteriv,"uf":_glTexStorage2D,"wf":_glTexStorage3D,"Qf":_glTexSubImage2D,"yf":_glTexSubImage3D,"Af":_glTransformFeedbackVaryings,"_b":_glUniform1fv,"ua":_glUniform1i,"$b":_glUniform1iv,"ac":_glUniform1uiv,"bc":_glUniform2fv,"cc":_glUniform2iv,"dc":_glUniform2uiv,"Va":_glUniform3fv,"ec":_glUniform3iv,"fc":_glUniform3uiv,"_":_glUniform4fv,"gc":_glUniform4iv,"hc":_glUniform4uiv,"Ra":_glUniformBlockBinding,"ic":_glUniformMatrix3fv,"va":_glUniformMatrix4fv,"pf":_glUnmapBuffer,"Mf":_glUseProgram,"_g":_glValidateProgram,"Nf":_glVertexAttrib4f,"Of":_glVertexAttrib4fv,"ff":_glVertexAttribIPointer,"Pf":_glVertexAttribPointer,"Ua":_glViewport,"ca":invoke_dddi,"sc":invoke_di,"U":invoke_dii,"Ub":invoke_diii,"uc":invoke_diiid,"Bd":invoke_dji,"X":invoke_fffi,"Ca":invoke_ffi,"R":invoke_fi,"Q":invoke_fifi,"z":invoke_fii,"B":invoke_fiii,"tc":invoke_fiiif,"Ba":invoke_fiiii,"hh":invoke_fiiiii,"x":invoke_i,"d":invoke_ii,"fh":invoke_iifi,"ph":invoke_iifii,"c":invoke_iii,"zc":invoke_iiifi,"rc":invoke_iiifii,"k":invoke_iiii,"r":invoke_iiiii,"sh":invoke_iiiiifiiiii,"u":invoke_iiiiii,"s":invoke_iiiiiii,"jh":invoke_iiiiiiidii,"K":invoke_iiiiiiii,"uh":invoke_iiiiiiiifiii,"S":invoke_iiiiiiiii,"qc":invoke_iiiiiiiiii,"ab":invoke_iiiiiiiiiii,"Ic":invoke_iiiiiiiiiiiii,"Gd":invoke_iiiiiiiiiji,"dd":invoke_iiiijii,"Rd":invoke_iiij,"Od":invoke_iiijiii,"Pd":invoke_iij,"Jd":invoke_iiji,"md":invoke_iijii,"sd":invoke_iijji,"hd":invoke_iji,"Dd":invoke_ijji,"Qd":invoke_j,"Ed":invoke_jdi,"Md":invoke_ji,"Nd":invoke_jii,"Kd":invoke_jiii,"Sd":invoke_jiiii,"ed":invoke_jiiiii,"Hd":invoke_jiiiiiiiiii,"ud":invoke_jiiij,"pd":invoke_jiiji,"td":invoke_jiji,"qd":invoke_jijiii,"nd":invoke_jijj,"fd":invoke_jjji,"g":invoke_v,"oh":invoke_vfi,"m":invoke_vi,"wc":invoke_vidi,"Bc":invoke_vidiii,"Ec":invoke_viffffi,"ba":invoke_viffi,"D":invoke_vifi,"p":invoke_vii,"Fc":invoke_viiddi,"rh":invoke_viidii,"Rb":invoke_viif,"O":invoke_viiff,"vc":invoke_viifffffi,"Ac":invoke_viifffi,"Dc":invoke_viiffi,"E":invoke_viifi,"qh":invoke_viifiiiii,"h":invoke_viii,"gh":invoke_viiif,"ia":invoke_viiifi,"n":invoke_viiii,"kh":invoke_viiiidi,"vd":invoke_viiiidij,"yc":invoke_viiiifi,"q":invoke_viiiii,"ha":invoke_viiiiifffiii,"th":invoke_viiiiiffi,"Cc":invoke_viiiiifi,"t":invoke_viiiiii,"y":invoke_viiiiiii,"mh":invoke_viiiiiiifddfiii,"lh":invoke_viiiiiiiffffiii,"G":invoke_viiiiiiifiifiii,"zd":invoke_viiiiiiifjjfiii,"F":invoke_viiiiiiii,"J":invoke_viiiiiiiii,"xc":invoke_viiiiiiiiifi,"Hc":invoke_viiiiiiiiii,"aa":invoke_viiiiiiiiiii,"nh":invoke_viiiiiiiiiiii,"ih":invoke_viiiiiiiiiiiii,"wd":invoke_viiij,"xd":invoke_viiiji,"od":invoke_viij,"Id":invoke_viiji,"Ld":invoke_viijii,"id":invoke_viijiiiiii,"Ad":invoke_viji,"Fd":invoke_vijii,"ld":invoke_vijiii,"yd":invoke_vji,"jd":invoke_vjiiiii,"kd":invoke_vjjjiiii,"j":_llvm_eh_typeid_for,"cb":_mktime,"C":_setTempRet0,"Da":_strftime,"eb":_time,"bb":_utime};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["yh"]).apply(null,arguments)};var _SendMessageFloat=Module["_SendMessageFloat"]=function(){return(_SendMessageFloat=Module["_SendMessageFloat"]=Module["asm"]["zh"]).apply(null,arguments)};var _SendMessageString=Module["_SendMessageString"]=function(){return(_SendMessageString=Module["_SendMessageString"]=Module["asm"]["Ah"]).apply(null,arguments)};var _SendMessage=Module["_SendMessage"]=function(){return(_SendMessage=Module["_SendMessage"]=Module["asm"]["Bh"]).apply(null,arguments)};var _SetFullscreen=Module["_SetFullscreen"]=function(){return(_SetFullscreen=Module["_SetFullscreen"]=Module["asm"]["Ch"]).apply(null,arguments)};var _main=Module["_main"]=function(){return(_main=Module["_main"]=Module["asm"]["Dh"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["Eh"]).apply(null,arguments)};var _htons=Module["_htons"]=function(){return(_htons=Module["_htons"]=Module["asm"]["Fh"]).apply(null,arguments)};var _ntohs=Module["_ntohs"]=function(){return(_ntohs=Module["_ntohs"]=Module["asm"]["Gh"]).apply(null,arguments)};var __get_tzname=Module["__get_tzname"]=function(){return(__get_tzname=Module["__get_tzname"]=Module["asm"]["Hh"]).apply(null,arguments)};var __get_daylight=Module["__get_daylight"]=function(){return(__get_daylight=Module["__get_daylight"]=Module["asm"]["Ih"]).apply(null,arguments)};var __get_timezone=Module["__get_timezone"]=function(){return(__get_timezone=Module["__get_timezone"]=Module["asm"]["Jh"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["Kh"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["Lh"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["Mh"]).apply(null,arguments)};var _setThrew=Module["_setThrew"]=function(){return(_setThrew=Module["_setThrew"]=Module["asm"]["Nh"]).apply(null,arguments)};var ___cxa_can_catch=Module["___cxa_can_catch"]=function(){return(___cxa_can_catch=Module["___cxa_can_catch"]=Module["asm"]["Oh"]).apply(null,arguments)};var ___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=function(){return(___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=Module["asm"]["Ph"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["Qh"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["Rh"]).apply(null,arguments)};var _memalign=Module["_memalign"]=function(){return(_memalign=Module["_memalign"]=Module["asm"]["Sh"]).apply(null,arguments)};var _memset=Module["_memset"]=function(){return(_memset=Module["_memset"]=Module["asm"]["Th"]).apply(null,arguments)};var _strlen=Module["_strlen"]=function(){return(_strlen=Module["_strlen"]=Module["asm"]["Uh"]).apply(null,arguments)};var dynCall_iidiiii=Module["dynCall_iidiiii"]=function(){return(dynCall_iidiiii=Module["dynCall_iidiiii"]=Module["asm"]["Wh"]).apply(null,arguments)};var dynCall_vii=Module["dynCall_vii"]=function(){return(dynCall_vii=Module["dynCall_vii"]=Module["asm"]["Xh"]).apply(null,arguments)};var dynCall_iii=Module["dynCall_iii"]=function(){return(dynCall_iii=Module["dynCall_iii"]=Module["asm"]["Yh"]).apply(null,arguments)};var dynCall_ii=Module["dynCall_ii"]=function(){return(dynCall_ii=Module["dynCall_ii"]=Module["asm"]["Zh"]).apply(null,arguments)};var dynCall_iiii=Module["dynCall_iiii"]=function(){return(dynCall_iiii=Module["dynCall_iiii"]=Module["asm"]["_h"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["$h"]).apply(null,arguments)};var dynCall_vi=Module["dynCall_vi"]=function(){return(dynCall_vi=Module["dynCall_vi"]=Module["asm"]["ai"]).apply(null,arguments)};var dynCall_iiiii=Module["dynCall_iiiii"]=function(){return(dynCall_iiiii=Module["dynCall_iiiii"]=Module["asm"]["bi"]).apply(null,arguments)};var dynCall_viii=Module["dynCall_viii"]=function(){return(dynCall_viii=Module["dynCall_viii"]=Module["asm"]["ci"]).apply(null,arguments)};var dynCall_i=Module["dynCall_i"]=function(){return(dynCall_i=Module["dynCall_i"]=Module["asm"]["di"]).apply(null,arguments)};var dynCall_v=Module["dynCall_v"]=function(){return(dynCall_v=Module["dynCall_v"]=Module["asm"]["ei"]).apply(null,arguments)};var dynCall_viiiiii=Module["dynCall_viiiiii"]=function(){return(dynCall_viiiiii=Module["dynCall_viiiiii"]=Module["asm"]["fi"]).apply(null,arguments)};var dynCall_viiiii=Module["dynCall_viiiii"]=function(){return(dynCall_viiiii=Module["dynCall_viiiii"]=Module["asm"]["gi"]).apply(null,arguments)};var dynCall_viiii=Module["dynCall_viiii"]=function(){return(dynCall_viiii=Module["dynCall_viiii"]=Module["asm"]["hi"]).apply(null,arguments)};var dynCall_iiiiii=Module["dynCall_iiiiii"]=function(){return(dynCall_iiiiii=Module["dynCall_iiiiii"]=Module["asm"]["ii"]).apply(null,arguments)};var dynCall_iiij=Module["dynCall_iiij"]=function(){return(dynCall_iiij=Module["dynCall_iiij"]=Module["asm"]["ji"]).apply(null,arguments)};var dynCall_iiiiiiii=Module["dynCall_iiiiiiii"]=function(){return(dynCall_iiiiiiii=Module["dynCall_iiiiiiii"]=Module["asm"]["ki"]).apply(null,arguments)};var dynCall_iiijiii=Module["dynCall_iiijiii"]=function(){return(dynCall_iiijiii=Module["dynCall_iiijiii"]=Module["asm"]["li"]).apply(null,arguments)};var dynCall_iij=Module["dynCall_iij"]=function(){return(dynCall_iij=Module["dynCall_iij"]=Module["asm"]["mi"]).apply(null,arguments)};var dynCall_iiiiiii=Module["dynCall_iiiiiii"]=function(){return(dynCall_iiiiiii=Module["dynCall_iiiiiii"]=Module["asm"]["ni"]).apply(null,arguments)};var dynCall_jii=Module["dynCall_jii"]=function(){return(dynCall_jii=Module["dynCall_jii"]=Module["asm"]["oi"]).apply(null,arguments)};var dynCall_jiiii=Module["dynCall_jiiii"]=function(){return(dynCall_jiiii=Module["dynCall_jiiii"]=Module["asm"]["pi"]).apply(null,arguments)};var dynCall_viifi=Module["dynCall_viifi"]=function(){return(dynCall_viifi=Module["dynCall_viifi"]=Module["asm"]["qi"]).apply(null,arguments)};var dynCall_viiji=Module["dynCall_viiji"]=function(){return(dynCall_viiji=Module["dynCall_viiji"]=Module["asm"]["ri"]).apply(null,arguments)};var dynCall_jiiiiiiiiii=Module["dynCall_jiiiiiiiiii"]=function(){return(dynCall_jiiiiiiiiii=Module["dynCall_jiiiiiiiiii"]=Module["asm"]["si"]).apply(null,arguments)};var dynCall_vijii=Module["dynCall_vijii"]=function(){return(dynCall_vijii=Module["dynCall_vijii"]=Module["asm"]["ti"]).apply(null,arguments)};var dynCall_fii=Module["dynCall_fii"]=function(){return(dynCall_fii=Module["dynCall_fii"]=Module["asm"]["ui"]).apply(null,arguments)};var dynCall_vifi=Module["dynCall_vifi"]=function(){return(dynCall_vifi=Module["dynCall_vifi"]=Module["asm"]["vi"]).apply(null,arguments)};var dynCall_viffffi=Module["dynCall_viffffi"]=function(){return(dynCall_viffffi=Module["dynCall_viffffi"]=Module["asm"]["wi"]).apply(null,arguments)};var dynCall_viiffi=Module["dynCall_viiffi"]=function(){return(dynCall_viiffi=Module["dynCall_viiffi"]=Module["asm"]["xi"]).apply(null,arguments)};var dynCall_iiiifii=Module["dynCall_iiiifii"]=function(){return(dynCall_iiiifii=Module["dynCall_iiiifii"]=Module["asm"]["yi"]).apply(null,arguments)};var dynCall_iiifii=Module["dynCall_iiifii"]=function(){return(dynCall_iiifii=Module["dynCall_iiifii"]=Module["asm"]["zi"]).apply(null,arguments)};var dynCall_viiiifii=Module["dynCall_viiiifii"]=function(){return(dynCall_viiiifii=Module["dynCall_viiiifii"]=Module["asm"]["Ai"]).apply(null,arguments)};var dynCall_viiiiiii=Module["dynCall_viiiiiii"]=function(){return(dynCall_viiiiiii=Module["dynCall_viiiiiii"]=Module["asm"]["Bi"]).apply(null,arguments)};var dynCall_viffi=Module["dynCall_viffi"]=function(){return(dynCall_viffi=Module["dynCall_viffi"]=Module["asm"]["Ci"]).apply(null,arguments)};var dynCall_viiifi=Module["dynCall_viiifi"]=function(){return(dynCall_viiifi=Module["dynCall_viiifi"]=Module["asm"]["Di"]).apply(null,arguments)};var dynCall_ffi=Module["dynCall_ffi"]=function(){return(dynCall_ffi=Module["dynCall_ffi"]=Module["asm"]["Ei"]).apply(null,arguments)};var dynCall_viiiiiiiiiii=Module["dynCall_viiiiiiiiiii"]=function(){return(dynCall_viiiiiiiiiii=Module["dynCall_viiiiiiiiiii"]=Module["asm"]["Fi"]).apply(null,arguments)};var dynCall_viiiiiiiii=Module["dynCall_viiiiiiiii"]=function(){return(dynCall_viiiiiiiii=Module["dynCall_viiiiiiiii"]=Module["asm"]["Gi"]).apply(null,arguments)};var dynCall_iiiiiiiifiii=Module["dynCall_iiiiiiiifiii"]=function(){return(dynCall_iiiiiiiifiii=Module["dynCall_iiiiiiiifiii"]=Module["asm"]["Hi"]).apply(null,arguments)};var dynCall_viiiiifi=Module["dynCall_viiiiifi"]=function(){return(dynCall_viiiiifi=Module["dynCall_viiiiifi"]=Module["asm"]["Ii"]).apply(null,arguments)};var dynCall_viiiiiffi=Module["dynCall_viiiiiffi"]=function(){return(dynCall_viiiiiffi=Module["dynCall_viiiiiffi"]=Module["asm"]["Ji"]).apply(null,arguments)};var dynCall_dddi=Module["dynCall_dddi"]=function(){return(dynCall_dddi=Module["dynCall_dddi"]=Module["asm"]["Ki"]).apply(null,arguments)};var dynCall_viiiiiiii=Module["dynCall_viiiiiiii"]=function(){return(dynCall_viiiiiiii=Module["dynCall_viiiiiiii"]=Module["asm"]["Li"]).apply(null,arguments)};var dynCall_jiii=Module["dynCall_jiii"]=function(){return(dynCall_jiii=Module["dynCall_jiii"]=Module["asm"]["Mi"]).apply(null,arguments)};var dynCall_iiiiiiiii=Module["dynCall_iiiiiiiii"]=function(){return(dynCall_iiiiiiiii=Module["dynCall_iiiiiiiii"]=Module["asm"]["Ni"]).apply(null,arguments)};var dynCall_fiii=Module["dynCall_fiii"]=function(){return(dynCall_fiii=Module["dynCall_fiii"]=Module["asm"]["Oi"]).apply(null,arguments)};var dynCall_iiiiifiiiii=Module["dynCall_iiiiifiiiii"]=function(){return(dynCall_iiiiifiiiii=Module["dynCall_iiiiifiiiii"]=Module["asm"]["Pi"]).apply(null,arguments)};var dynCall_viiddi=Module["dynCall_viiddi"]=function(){return(dynCall_viiddi=Module["dynCall_viiddi"]=Module["asm"]["Qi"]).apply(null,arguments)};var dynCall_viidii=Module["dynCall_viidii"]=function(){return(dynCall_viidii=Module["dynCall_viidii"]=Module["asm"]["Ri"]).apply(null,arguments)};var dynCall_diii=Module["dynCall_diii"]=function(){return(dynCall_diii=Module["dynCall_diii"]=Module["asm"]["Si"]).apply(null,arguments)};var dynCall_jdi=Module["dynCall_jdi"]=function(){return(dynCall_jdi=Module["dynCall_jdi"]=Module["asm"]["Ti"]).apply(null,arguments)};var dynCall_ijji=Module["dynCall_ijji"]=function(){return(dynCall_ijji=Module["dynCall_ijji"]=Module["asm"]["Ui"]).apply(null,arguments)};var dynCall_dji=Module["dynCall_dji"]=function(){return(dynCall_dji=Module["dynCall_dji"]=Module["asm"]["Vi"]).apply(null,arguments)};var dynCall_vidiii=Module["dynCall_vidiii"]=function(){return(dynCall_vidiii=Module["dynCall_vidiii"]=Module["asm"]["Wi"]).apply(null,arguments)};var dynCall_dii=Module["dynCall_dii"]=function(){return(dynCall_dii=Module["dynCall_dii"]=Module["asm"]["Xi"]).apply(null,arguments)};var dynCall_fiiii=Module["dynCall_fiiii"]=function(){return(dynCall_fiiii=Module["dynCall_fiiii"]=Module["asm"]["Yi"]).apply(null,arguments)};var dynCall_fi=Module["dynCall_fi"]=function(){return(dynCall_fi=Module["dynCall_fi"]=Module["asm"]["Zi"]).apply(null,arguments)};var dynCall_viifiiiii=Module["dynCall_viifiiiii"]=function(){return(dynCall_viifiiiii=Module["dynCall_viifiiiii"]=Module["asm"]["_i"]).apply(null,arguments)};var dynCall_iifii=Module["dynCall_iifii"]=function(){return(dynCall_iifii=Module["dynCall_iifii"]=Module["asm"]["$i"]).apply(null,arguments)};var dynCall_vfi=Module["dynCall_vfi"]=function(){return(dynCall_vfi=Module["dynCall_vfi"]=Module["asm"]["aj"]).apply(null,arguments)};var dynCall_viji=Module["dynCall_viji"]=function(){return(dynCall_viji=Module["dynCall_viji"]=Module["asm"]["bj"]).apply(null,arguments)};var dynCall_iiji=Module["dynCall_iiji"]=function(){return(dynCall_iiji=Module["dynCall_iiji"]=Module["asm"]["cj"]).apply(null,arguments)};var dynCall_viiiiiiiiiiii=Module["dynCall_viiiiiiiiiiii"]=function(){return(dynCall_viiiiiiiiiiii=Module["dynCall_viiiiiiiiiiii"]=Module["asm"]["dj"]).apply(null,arguments)};var dynCall_viifii=Module["dynCall_viifii"]=function(){return(dynCall_viifii=Module["dynCall_viifii"]=Module["asm"]["ej"]).apply(null,arguments)};var dynCall_fffi=Module["dynCall_fffi"]=function(){return(dynCall_fffi=Module["dynCall_fffi"]=Module["asm"]["fj"]).apply(null,arguments)};var dynCall_viifffi=Module["dynCall_viifffi"]=function(){return(dynCall_viifffi=Module["dynCall_viifffi"]=Module["asm"]["gj"]).apply(null,arguments)};var dynCall_viiiiiiifiifiii=Module["dynCall_viiiiiiifiifiii"]=function(){return(dynCall_viiiiiiifiifiii=Module["dynCall_viiiiiiifiifiii"]=Module["asm"]["hj"]).apply(null,arguments)};var dynCall_viiiiiiifddfiii=Module["dynCall_viiiiiiifddfiii"]=function(){return(dynCall_viiiiiiifddfiii=Module["dynCall_viiiiiiifddfiii"]=Module["asm"]["ij"]).apply(null,arguments)};var dynCall_viiiiiiifjjfiii=Module["dynCall_viiiiiiifjjfiii"]=function(){return(dynCall_viiiiiiifjjfiii=Module["dynCall_viiiiiiifjjfiii"]=Module["asm"]["jj"]).apply(null,arguments)};var dynCall_viiiiiiiffffiii=Module["dynCall_viiiiiiiffffiii"]=function(){return(dynCall_viiiiiiiffffiii=Module["dynCall_viiiiiiiffffiii"]=Module["asm"]["kj"]).apply(null,arguments)};var dynCall_viif=Module["dynCall_viif"]=function(){return(dynCall_viif=Module["dynCall_viif"]=Module["asm"]["lj"]).apply(null,arguments)};var dynCall_viiiiiiiiii=Module["dynCall_viiiiiiiiii"]=function(){return(dynCall_viiiiiiiiii=Module["dynCall_viiiiiiiiii"]=Module["asm"]["mj"]).apply(null,arguments)};var dynCall_iiiiiiiiiji=Module["dynCall_iiiiiiiiiji"]=function(){return(dynCall_iiiiiiiiiji=Module["dynCall_iiiiiiiiiji"]=Module["asm"]["nj"]).apply(null,arguments)};var dynCall_vji=Module["dynCall_vji"]=function(){return(dynCall_vji=Module["dynCall_vji"]=Module["asm"]["oj"]).apply(null,arguments)};var dynCall_viiff=Module["dynCall_viiff"]=function(){return(dynCall_viiff=Module["dynCall_viiff"]=Module["asm"]["pj"]).apply(null,arguments)};var dynCall_iiifi=Module["dynCall_iiifi"]=function(){return(dynCall_iiifi=Module["dynCall_iiifi"]=Module["asm"]["qj"]).apply(null,arguments)};var dynCall_viiij=Module["dynCall_viiij"]=function(){return(dynCall_viiij=Module["dynCall_viiij"]=Module["asm"]["rj"]).apply(null,arguments)};var dynCall_viiiifi=Module["dynCall_viiiifi"]=function(){return(dynCall_viiiifi=Module["dynCall_viiiifi"]=Module["asm"]["sj"]).apply(null,arguments)};var dynCall_ji=Module["dynCall_ji"]=function(){return(dynCall_ji=Module["dynCall_ji"]=Module["asm"]["tj"]).apply(null,arguments)};var dynCall_viiiiiiiiifi=Module["dynCall_viiiiiiiiifi"]=function(){return(dynCall_viiiiiiiiifi=Module["dynCall_viiiiiiiiifi"]=Module["asm"]["uj"]).apply(null,arguments)};var dynCall_iiiiiiiiiiiii=Module["dynCall_iiiiiiiiiiiii"]=function(){return(dynCall_iiiiiiiiiiiii=Module["dynCall_iiiiiiiiiiiii"]=Module["asm"]["vj"]).apply(null,arguments)};var dynCall_iiiifi=Module["dynCall_iiiifi"]=function(){return(dynCall_iiiifi=Module["dynCall_iiiifi"]=Module["asm"]["wj"]).apply(null,arguments)};var dynCall_fiiffi=Module["dynCall_fiiffi"]=function(){return(dynCall_fiiffi=Module["dynCall_fiiffi"]=Module["asm"]["xj"]).apply(null,arguments)};var dynCall_viiififii=Module["dynCall_viiififii"]=function(){return(dynCall_viiififii=Module["dynCall_viiififii"]=Module["asm"]["yj"]).apply(null,arguments)};var dynCall_fifi=Module["dynCall_fifi"]=function(){return(dynCall_fifi=Module["dynCall_fifi"]=Module["asm"]["zj"]).apply(null,arguments)};var dynCall_jiiji=Module["dynCall_jiiji"]=function(){return(dynCall_jiiji=Module["dynCall_jiiji"]=Module["asm"]["Aj"]).apply(null,arguments)};var dynCall_fiifi=Module["dynCall_fiifi"]=function(){return(dynCall_fiifi=Module["dynCall_fiifi"]=Module["asm"]["Bj"]).apply(null,arguments)};var dynCall_iiffi=Module["dynCall_iiffi"]=function(){return(dynCall_iiffi=Module["dynCall_iiffi"]=Module["asm"]["Cj"]).apply(null,arguments)};var dynCall_iiidii=Module["dynCall_iiidii"]=function(){return(dynCall_iiidii=Module["dynCall_iiidii"]=Module["asm"]["Dj"]).apply(null,arguments)};var dynCall_fiiiii=Module["dynCall_fiiiii"]=function(){return(dynCall_fiiiii=Module["dynCall_fiiiii"]=Module["asm"]["Ej"]).apply(null,arguments)};var dynCall_iifi=Module["dynCall_iifi"]=function(){return(dynCall_iifi=Module["dynCall_iifi"]=Module["asm"]["Fj"]).apply(null,arguments)};var dynCall_viidiji=Module["dynCall_viidiji"]=function(){return(dynCall_viidiji=Module["dynCall_viidiji"]=Module["asm"]["Gj"]).apply(null,arguments)};var dynCall_viidjii=Module["dynCall_viidjii"]=function(){return(dynCall_viidjii=Module["dynCall_viidjii"]=Module["asm"]["Hj"]).apply(null,arguments)};var dynCall_viiiidi=Module["dynCall_viiiidi"]=function(){return(dynCall_viiiidi=Module["dynCall_viiiidi"]=Module["asm"]["Ij"]).apply(null,arguments)};var dynCall_vidi=Module["dynCall_vidi"]=function(){return(dynCall_vidi=Module["dynCall_vidi"]=Module["asm"]["Jj"]).apply(null,arguments)};var dynCall_iiiiiiidii=Module["dynCall_iiiiiiidii"]=function(){return(dynCall_iiiiiiidii=Module["dynCall_iiiiiiidii"]=Module["asm"]["Kj"]).apply(null,arguments)};var dynCall_viiiidij=Module["dynCall_viiiidij"]=function(){return(dynCall_viiiidij=Module["dynCall_viiiidij"]=Module["asm"]["Lj"]).apply(null,arguments)};var dynCall_viiiiiiiiiiiii=Module["dynCall_viiiiiiiiiiiii"]=function(){return(dynCall_viiiiiiiiiiiii=Module["dynCall_viiiiiiiiiiiii"]=Module["asm"]["Mj"]).apply(null,arguments)};var dynCall_viifffffi=Module["dynCall_viifffffi"]=function(){return(dynCall_viifffffi=Module["dynCall_viifffffi"]=Module["asm"]["Nj"]).apply(null,arguments)};var dynCall_viiiiifffiii=Module["dynCall_viiiiifffiii"]=function(){return(dynCall_viiiiifffiii=Module["dynCall_viiiiifffiii"]=Module["asm"]["Oj"]).apply(null,arguments)};var dynCall_viiif=Module["dynCall_viiif"]=function(){return(dynCall_viiif=Module["dynCall_viiif"]=Module["asm"]["Pj"]).apply(null,arguments)};var dynCall_iijji=Module["dynCall_iijji"]=function(){return(dynCall_iijji=Module["dynCall_iijji"]=Module["asm"]["Qj"]).apply(null,arguments)};var dynCall_diiid=Module["dynCall_diiid"]=function(){return(dynCall_diiid=Module["dynCall_diiid"]=Module["asm"]["Rj"]).apply(null,arguments)};var dynCall_jiiij=Module["dynCall_jiiij"]=function(){return(dynCall_jiiij=Module["dynCall_jiiij"]=Module["asm"]["Sj"]).apply(null,arguments)};var dynCall_fiiif=Module["dynCall_fiiif"]=function(){return(dynCall_fiiif=Module["dynCall_fiiif"]=Module["asm"]["Tj"]).apply(null,arguments)};var dynCall_fiffffi=Module["dynCall_fiffffi"]=function(){return(dynCall_fiffffi=Module["dynCall_fiffffi"]=Module["asm"]["Uj"]).apply(null,arguments)};var dynCall_viijii=Module["dynCall_viijii"]=function(){return(dynCall_viijii=Module["dynCall_viijii"]=Module["asm"]["Vj"]).apply(null,arguments)};var dynCall_di=Module["dynCall_di"]=function(){return(dynCall_di=Module["dynCall_di"]=Module["asm"]["Wj"]).apply(null,arguments)};var dynCall_fiifii=Module["dynCall_fiifii"]=function(){return(dynCall_fiifii=Module["dynCall_fiifii"]=Module["asm"]["Xj"]).apply(null,arguments)};var dynCall_iiiiiiiiiii=Module["dynCall_iiiiiiiiiii"]=function(){return(dynCall_iiiiiiiiiii=Module["dynCall_iiiiiiiiiii"]=Module["asm"]["Yj"]).apply(null,arguments)};var dynCall_jijiii=Module["dynCall_jijiii"]=function(){return(dynCall_jijiii=Module["dynCall_jijiii"]=Module["asm"]["Zj"]).apply(null,arguments)};var dynCall_viij=Module["dynCall_viij"]=function(){return(dynCall_viij=Module["dynCall_viij"]=Module["asm"]["_j"]).apply(null,arguments)};var dynCall_j=Module["dynCall_j"]=function(){return(dynCall_j=Module["dynCall_j"]=Module["asm"]["$j"]).apply(null,arguments)};var dynCall_jijj=Module["dynCall_jijj"]=function(){return(dynCall_jijj=Module["dynCall_jijj"]=Module["asm"]["ak"]).apply(null,arguments)};var dynCall_iijii=Module["dynCall_iijii"]=function(){return(dynCall_iijii=Module["dynCall_iijii"]=Module["asm"]["bk"]).apply(null,arguments)};var dynCall_viijiiiiii=Module["dynCall_viijiiiiii"]=function(){return(dynCall_viijiiiiii=Module["dynCall_viijiiiiii"]=Module["asm"]["ck"]).apply(null,arguments)};var dynCall_vijiii=Module["dynCall_vijiii"]=function(){return(dynCall_vijiii=Module["dynCall_vijiii"]=Module["asm"]["dk"]).apply(null,arguments)};var dynCall_vjjjiiii=Module["dynCall_vjjjiiii"]=function(){return(dynCall_vjjjiiii=Module["dynCall_vjjjiiii"]=Module["asm"]["ek"]).apply(null,arguments)};var dynCall_vjiiiii=Module["dynCall_vjiiiii"]=function(){return(dynCall_vjiiiii=Module["dynCall_vjiiiii"]=Module["asm"]["fk"]).apply(null,arguments)};var dynCall_iji=Module["dynCall_iji"]=function(){return(dynCall_iji=Module["dynCall_iji"]=Module["asm"]["gk"]).apply(null,arguments)};var dynCall_jjji=Module["dynCall_jjji"]=function(){return(dynCall_jjji=Module["dynCall_jjji"]=Module["asm"]["hk"]).apply(null,arguments)};var dynCall_jiiiii=Module["dynCall_jiiiii"]=function(){return(dynCall_jiiiii=Module["dynCall_jiiiii"]=Module["asm"]["ik"]).apply(null,arguments)};var dynCall_viiiji=Module["dynCall_viiiji"]=function(){return(dynCall_viiiji=Module["dynCall_viiiji"]=Module["asm"]["jk"]).apply(null,arguments)};var dynCall_iiiiiiiiii=Module["dynCall_iiiiiiiiii"]=function(){return(dynCall_iiiiiiiiii=Module["dynCall_iiiiiiiiii"]=Module["asm"]["kk"]).apply(null,arguments)};var dynCall_iiiffi=Module["dynCall_iiiffi"]=function(){return(dynCall_iiiffi=Module["dynCall_iiiffi"]=Module["asm"]["lk"]).apply(null,arguments)};var dynCall_iiffii=Module["dynCall_iiffii"]=function(){return(dynCall_iiffii=Module["dynCall_iiffii"]=Module["asm"]["mk"]).apply(null,arguments)};var dynCall_iiifiii=Module["dynCall_iiifiii"]=function(){return(dynCall_iiifiii=Module["dynCall_iiifiii"]=Module["asm"]["nk"]).apply(null,arguments)};var dynCall_iiififii=Module["dynCall_iiififii"]=function(){return(dynCall_iiififii=Module["dynCall_iiififii"]=Module["asm"]["ok"]).apply(null,arguments)};var dynCall_iiifiiiii=Module["dynCall_iiifiiiii"]=function(){return(dynCall_iiifiiiii=Module["dynCall_iiifiiiii"]=Module["asm"]["pk"]).apply(null,arguments)};var dynCall_iiffifiiii=Module["dynCall_iiffifiiii"]=function(){return(dynCall_iiffifiiii=Module["dynCall_iiffifiiii"]=Module["asm"]["qk"]).apply(null,arguments)};var dynCall_iifiifiiii=Module["dynCall_iifiifiiii"]=function(){return(dynCall_iifiifiiii=Module["dynCall_iifiifiiii"]=Module["asm"]["rk"]).apply(null,arguments)};var dynCall_iiiifiii=Module["dynCall_iiiifiii"]=function(){return(dynCall_iiiifiii=Module["dynCall_iiiifiii"]=Module["asm"]["sk"]).apply(null,arguments)};var dynCall_iiifiiii=Module["dynCall_iiifiiii"]=function(){return(dynCall_iiifiiii=Module["dynCall_iiifiiii"]=Module["asm"]["tk"]).apply(null,arguments)};var dynCall_iiiffiii=Module["dynCall_iiiffiii"]=function(){return(dynCall_iiiffiii=Module["dynCall_iiiffiii"]=Module["asm"]["uk"]).apply(null,arguments)};var dynCall_iiiiifii=Module["dynCall_iiiiifii"]=function(){return(dynCall_iiiiifii=Module["dynCall_iiiiifii"]=Module["asm"]["vk"]).apply(null,arguments)};var dynCall_fiffi=Module["dynCall_fiffi"]=function(){return(dynCall_fiffi=Module["dynCall_fiffi"]=Module["asm"]["wk"]).apply(null,arguments)};var dynCall_iiiiiffi=Module["dynCall_iiiiiffi"]=function(){return(dynCall_iiiiiffi=Module["dynCall_iiiiiffi"]=Module["asm"]["xk"]).apply(null,arguments)};var dynCall_viiiiiiifiii=Module["dynCall_viiiiiiifiii"]=function(){return(dynCall_viiiiiiifiii=Module["dynCall_viiiiiiifiii"]=Module["asm"]["yk"]).apply(null,arguments)};var dynCall_fiiifii=Module["dynCall_fiiifii"]=function(){return(dynCall_fiiifii=Module["dynCall_fiiifii"]=Module["asm"]["zk"]).apply(null,arguments)};var dynCall_fifii=Module["dynCall_fifii"]=function(){return(dynCall_fifii=Module["dynCall_fifii"]=Module["asm"]["Ak"]).apply(null,arguments)};var dynCall_iiiffii=Module["dynCall_iiiffii"]=function(){return(dynCall_iiiffii=Module["dynCall_iiiffii"]=Module["asm"]["Bk"]).apply(null,arguments)};var dynCall_fifiii=Module["dynCall_fifiii"]=function(){return(dynCall_fifiii=Module["dynCall_fifiii"]=Module["asm"]["Ck"]).apply(null,arguments)};var dynCall_viiiiffii=Module["dynCall_viiiiffii"]=function(){return(dynCall_viiiiffii=Module["dynCall_viiiiffii"]=Module["asm"]["Dk"]).apply(null,arguments)};var dynCall_viiiiifffi=Module["dynCall_viiiiifffi"]=function(){return(dynCall_viiiiifffi=Module["dynCall_viiiiifffi"]=Module["asm"]["Ek"]).apply(null,arguments)};var dynCall_iiiiifi=Module["dynCall_iiiiifi"]=function(){return(dynCall_iiiiifi=Module["dynCall_iiiiifi"]=Module["asm"]["Fk"]).apply(null,arguments)};var dynCall_viiifffi=Module["dynCall_viiifffi"]=function(){return(dynCall_viiifffi=Module["dynCall_viiifffi"]=Module["asm"]["Gk"]).apply(null,arguments)};var dynCall_viiiffi=Module["dynCall_viiiffi"]=function(){return(dynCall_viiiffi=Module["dynCall_viiiffi"]=Module["asm"]["Hk"]).apply(null,arguments)};var dynCall_fifiiiii=Module["dynCall_fifiiiii"]=function(){return(dynCall_fifiiiii=Module["dynCall_fifiiiii"]=Module["asm"]["Ik"]).apply(null,arguments)};var dynCall_viifiii=Module["dynCall_viifiii"]=function(){return(dynCall_viifiii=Module["dynCall_viifiii"]=Module["asm"]["Jk"]).apply(null,arguments)};var dynCall_vifiiiii=Module["dynCall_vifiiiii"]=function(){return(dynCall_vifiiiii=Module["dynCall_vifiiiii"]=Module["asm"]["Kk"]).apply(null,arguments)};var dynCall_viffiifffiii=Module["dynCall_viffiifffiii"]=function(){return(dynCall_viffiifffiii=Module["dynCall_viffiifffiii"]=Module["asm"]["Lk"]).apply(null,arguments)};var dynCall_ffffffi=Module["dynCall_ffffffi"]=function(){return(dynCall_ffffffi=Module["dynCall_ffffffi"]=Module["asm"]["Mk"]).apply(null,arguments)};var dynCall_viiiiiifi=Module["dynCall_viiiiiifi"]=function(){return(dynCall_viiiiiifi=Module["dynCall_viiiiiifi"]=Module["asm"]["Nk"]).apply(null,arguments)};var dynCall_viiiiffi=Module["dynCall_viiiiffi"]=function(){return(dynCall_viiiiffi=Module["dynCall_viiiiffi"]=Module["asm"]["Ok"]).apply(null,arguments)};var dynCall_fiiiiii=Module["dynCall_fiiiiii"]=function(){return(dynCall_fiiiiii=Module["dynCall_fiiiiii"]=Module["asm"]["Pk"]).apply(null,arguments)};var dynCall_fifffi=Module["dynCall_fifffi"]=function(){return(dynCall_fifffi=Module["dynCall_fifffi"]=Module["asm"]["Qk"]).apply(null,arguments)};var dynCall_viffiiiii=Module["dynCall_viffiiiii"]=function(){return(dynCall_viffiiiii=Module["dynCall_viffiiiii"]=Module["asm"]["Rk"]).apply(null,arguments)};var dynCall_vifffffi=Module["dynCall_vifffffi"]=function(){return(dynCall_vifffffi=Module["dynCall_vifffffi"]=Module["asm"]["Sk"]).apply(null,arguments)};var dynCall_vifiii=Module["dynCall_vifiii"]=function(){return(dynCall_vifiii=Module["dynCall_vifiii"]=Module["asm"]["Tk"]).apply(null,arguments)};var dynCall_iifiifiii=Module["dynCall_iifiifiii"]=function(){return(dynCall_iifiifiii=Module["dynCall_iifiifiii"]=Module["asm"]["Uk"]).apply(null,arguments)};var dynCall_vifffi=Module["dynCall_vifffi"]=function(){return(dynCall_vifffi=Module["dynCall_vifffi"]=Module["asm"]["Vk"]).apply(null,arguments)};var dynCall_iifiiii=Module["dynCall_iifiiii"]=function(){return(dynCall_iifiiii=Module["dynCall_iifiiii"]=Module["asm"]["Wk"]).apply(null,arguments)};var dynCall_vifii=Module["dynCall_vifii"]=function(){return(dynCall_vifii=Module["dynCall_vifii"]=Module["asm"]["Xk"]).apply(null,arguments)};var dynCall_viddi=Module["dynCall_viddi"]=function(){return(dynCall_viddi=Module["dynCall_viddi"]=Module["asm"]["Yk"]).apply(null,arguments)};var dynCall_vijji=Module["dynCall_vijji"]=function(){return(dynCall_vijji=Module["dynCall_vijji"]=Module["asm"]["Zk"]).apply(null,arguments)};var dynCall_vijjjji=Module["dynCall_vijjjji"]=function(){return(dynCall_vijjjji=Module["dynCall_vijjjji"]=Module["asm"]["_k"]).apply(null,arguments)};var dynCall_idi=Module["dynCall_idi"]=function(){return(dynCall_idi=Module["dynCall_idi"]=Module["asm"]["$k"]).apply(null,arguments)};var dynCall_iijjjji=Module["dynCall_iijjjji"]=function(){return(dynCall_iijjjji=Module["dynCall_iijjjji"]=Module["asm"]["al"]).apply(null,arguments)};var dynCall_diiii=Module["dynCall_diiii"]=function(){return(dynCall_diiii=Module["dynCall_diiii"]=Module["asm"]["bl"]).apply(null,arguments)};var dynCall_iiidi=Module["dynCall_iiidi"]=function(){return(dynCall_iiidi=Module["dynCall_iiidi"]=Module["asm"]["cl"]).apply(null,arguments)};var dynCall_iijjjjiii=Module["dynCall_iijjjjiii"]=function(){return(dynCall_iijjjjiii=Module["dynCall_iijjjjiii"]=Module["asm"]["dl"]).apply(null,arguments)};var dynCall_iiiidi=Module["dynCall_iiiidi"]=function(){return(dynCall_iiiidi=Module["dynCall_iiiidi"]=Module["asm"]["el"]).apply(null,arguments)};var dynCall_iidi=Module["dynCall_iidi"]=function(){return(dynCall_iidi=Module["dynCall_iidi"]=Module["asm"]["fl"]).apply(null,arguments)};var dynCall_viidi=Module["dynCall_viidi"]=function(){return(dynCall_viidi=Module["dynCall_viidi"]=Module["asm"]["gl"]).apply(null,arguments)};var dynCall_viiidi=Module["dynCall_viiidi"]=function(){return(dynCall_viiidi=Module["dynCall_viiidi"]=Module["asm"]["hl"]).apply(null,arguments)};var dynCall_ffffi=Module["dynCall_ffffi"]=function(){return(dynCall_ffffi=Module["dynCall_ffffi"]=Module["asm"]["il"]).apply(null,arguments)};var dynCall_viiifii=Module["dynCall_viiifii"]=function(){return(dynCall_viiifii=Module["dynCall_viiifii"]=Module["asm"]["jl"]).apply(null,arguments)};var dynCall_iiffffiii=Module["dynCall_iiffffiii"]=function(){return(dynCall_iiffffiii=Module["dynCall_iiffffiii"]=Module["asm"]["kl"]).apply(null,arguments)};var dynCall_vffi=Module["dynCall_vffi"]=function(){return(dynCall_vffi=Module["dynCall_vffi"]=Module["asm"]["ll"]).apply(null,arguments)};var dynCall_iiidfi=Module["dynCall_iiidfi"]=function(){return(dynCall_iiidfi=Module["dynCall_iiidfi"]=Module["asm"]["ml"]).apply(null,arguments)};var dynCall_iiijfi=Module["dynCall_iiijfi"]=function(){return(dynCall_iiijfi=Module["dynCall_iiijfi"]=Module["asm"]["nl"]).apply(null,arguments)};var dynCall_iifffi=Module["dynCall_iifffi"]=function(){return(dynCall_iifffi=Module["dynCall_iifffi"]=Module["asm"]["ol"]).apply(null,arguments)};var dynCall_iiiififi=Module["dynCall_iiiififi"]=function(){return(dynCall_iiiififi=Module["dynCall_iiiififi"]=Module["asm"]["pl"]).apply(null,arguments)};var dynCall_iiiffifiiii=Module["dynCall_iiiffifiiii"]=function(){return(dynCall_iiiffifiiii=Module["dynCall_iiiffifiiii"]=Module["asm"]["ql"]).apply(null,arguments)};var dynCall_iiifiifiii=Module["dynCall_iiifiifiii"]=function(){return(dynCall_iiifiifiii=Module["dynCall_iiifiifiii"]=Module["asm"]["rl"]).apply(null,arguments)};var dynCall_iiifiifiiiii=Module["dynCall_iiifiifiiiii"]=function(){return(dynCall_iiifiifiiiii=Module["dynCall_iiifiifiiiii"]=Module["asm"]["sl"]).apply(null,arguments)};var dynCall_ifii=Module["dynCall_ifii"]=function(){return(dynCall_ifii=Module["dynCall_ifii"]=Module["asm"]["tl"]).apply(null,arguments)};var dynCall_ifffii=Module["dynCall_ifffii"]=function(){return(dynCall_ifffii=Module["dynCall_ifffii"]=Module["asm"]["ul"]).apply(null,arguments)};var dynCall_ffffii=Module["dynCall_ffffii"]=function(){return(dynCall_ffffii=Module["dynCall_ffffii"]=Module["asm"]["vl"]).apply(null,arguments)};var dynCall_ffffifi=Module["dynCall_ffffifi"]=function(){return(dynCall_ffffifi=Module["dynCall_ffffifi"]=Module["asm"]["wl"]).apply(null,arguments)};var dynCall_ffffiffi=Module["dynCall_ffffiffi"]=function(){return(dynCall_ffffiffi=Module["dynCall_ffffiffi"]=Module["asm"]["xl"]).apply(null,arguments)};var dynCall_viiififi=Module["dynCall_viiififi"]=function(){return(dynCall_viiififi=Module["dynCall_viiififi"]=Module["asm"]["yl"]).apply(null,arguments)};var dynCall_viiififfi=Module["dynCall_viiififfi"]=function(){return(dynCall_viiififfi=Module["dynCall_viiififfi"]=Module["asm"]["zl"]).apply(null,arguments)};var dynCall_ifiii=Module["dynCall_ifiii"]=function(){return(dynCall_ifiii=Module["dynCall_ifiii"]=Module["asm"]["Al"]).apply(null,arguments)};var dynCall_iifiiiiii=Module["dynCall_iifiiiiii"]=function(){return(dynCall_iifiiiiii=Module["dynCall_iifiiiiii"]=Module["asm"]["Bl"]).apply(null,arguments)};var dynCall_iifiiiii=Module["dynCall_iifiiiii"]=function(){return(dynCall_iifiiiii=Module["dynCall_iifiiiii"]=Module["asm"]["Cl"]).apply(null,arguments)};var dynCall_iiffiiiii=Module["dynCall_iiffiiiii"]=function(){return(dynCall_iiffiiiii=Module["dynCall_iiffiiiii"]=Module["asm"]["Dl"]).apply(null,arguments)};var dynCall_iiffifiii=Module["dynCall_iiffifiii"]=function(){return(dynCall_iiffifiii=Module["dynCall_iiffifiii"]=Module["asm"]["El"]).apply(null,arguments)};var dynCall_iififi=Module["dynCall_iififi"]=function(){return(dynCall_iififi=Module["dynCall_iififi"]=Module["asm"]["Fl"]).apply(null,arguments)};var dynCall_iiififi=Module["dynCall_iiififi"]=function(){return(dynCall_iiififi=Module["dynCall_iiififi"]=Module["asm"]["Gl"]).apply(null,arguments)};var dynCall_iifiii=Module["dynCall_iifiii"]=function(){return(dynCall_iifiii=Module["dynCall_iifiii"]=Module["asm"]["Hl"]).apply(null,arguments)};var dynCall_iiiiifiiii=Module["dynCall_iiiiifiiii"]=function(){return(dynCall_iiiiifiiii=Module["dynCall_iiiiifiiii"]=Module["asm"]["Il"]).apply(null,arguments)};var dynCall_viiiiiifiifiiii=Module["dynCall_viiiiiifiifiiii"]=function(){return(dynCall_viiiiiifiifiiii=Module["dynCall_viiiiiifiifiiii"]=Module["asm"]["Jl"]).apply(null,arguments)};var dynCall_viidiii=Module["dynCall_viidiii"]=function(){return(dynCall_viidiii=Module["dynCall_viidiii"]=Module["asm"]["Kl"]).apply(null,arguments)};var dynCall_diidi=Module["dynCall_diidi"]=function(){return(dynCall_diidi=Module["dynCall_diidi"]=Module["asm"]["Ll"]).apply(null,arguments)};var dynCall_fiifdi=Module["dynCall_fiifdi"]=function(){return(dynCall_fiifdi=Module["dynCall_fiifdi"]=Module["asm"]["Ml"]).apply(null,arguments)};var dynCall_viiiiiifddfiiii=Module["dynCall_viiiiiifddfiiii"]=function(){return(dynCall_viiiiiifddfiiii=Module["dynCall_viiiiiifddfiiii"]=Module["asm"]["Nl"]).apply(null,arguments)};var dynCall_viijiii=Module["dynCall_viijiii"]=function(){return(dynCall_viijiii=Module["dynCall_viijiii"]=Module["asm"]["Ol"]).apply(null,arguments)};var dynCall_fiifji=Module["dynCall_fiifji"]=function(){return(dynCall_fiifji=Module["dynCall_fiifji"]=Module["asm"]["Pl"]).apply(null,arguments)};var dynCall_viiiiiifjjfiiii=Module["dynCall_viiiiiifjjfiiii"]=function(){return(dynCall_viiiiiifjjfiiii=Module["dynCall_viiiiiifjjfiiii"]=Module["asm"]["Ql"]).apply(null,arguments)};var dynCall_viiiifiii=Module["dynCall_viiiifiii"]=function(){return(dynCall_viiiifiii=Module["dynCall_viiiifiii"]=Module["asm"]["Rl"]).apply(null,arguments)};var dynCall_viiiiiiffffiiii=Module["dynCall_viiiiiiffffiiii"]=function(){return(dynCall_viiiiiiffffiiii=Module["dynCall_viiiiiiffffiiii"]=Module["asm"]["Sl"]).apply(null,arguments)};var dynCall_viifiiii=Module["dynCall_viifiiii"]=function(){return(dynCall_viifiiii=Module["dynCall_viifiiii"]=Module["asm"]["Tl"]).apply(null,arguments)};var dynCall_iiiiifiii=Module["dynCall_iiiiifiii"]=function(){return(dynCall_iiiiifiii=Module["dynCall_iiiiifiii"]=Module["asm"]["Ul"]).apply(null,arguments)};var dynCall_fffffi=Module["dynCall_fffffi"]=function(){return(dynCall_fffffi=Module["dynCall_fffffi"]=Module["asm"]["Vl"]).apply(null,arguments)};var dynCall_fiiffffi=Module["dynCall_fiiffffi"]=function(){return(dynCall_fiiffffi=Module["dynCall_fiiffffi"]=Module["asm"]["Wl"]).apply(null,arguments)};var dynCall_fffifffi=Module["dynCall_fffifffi"]=function(){return(dynCall_fffifffi=Module["dynCall_fffifffi"]=Module["asm"]["Xl"]).apply(null,arguments)};var dynCall_iiiji=Module["dynCall_iiiji"]=function(){return(dynCall_iiiji=Module["dynCall_iiiji"]=Module["asm"]["Yl"]).apply(null,arguments)};var dynCall_viiiiiiiiiiiiii=Module["dynCall_viiiiiiiiiiiiii"]=function(){return(dynCall_viiiiiiiiiiiiii=Module["dynCall_viiiiiiiiiiiiii"]=Module["asm"]["Zl"]).apply(null,arguments)};var dynCall_iiiiji=Module["dynCall_iiiiji"]=function(){return(dynCall_iiiiji=Module["dynCall_iiiiji"]=Module["asm"]["_l"]).apply(null,arguments)};var dynCall_iiiiiji=Module["dynCall_iiiiiji"]=function(){return(dynCall_iiiiiji=Module["dynCall_iiiiiji"]=Module["asm"]["$l"]).apply(null,arguments)};var dynCall_viiijii=Module["dynCall_viiijii"]=function(){return(dynCall_viiijii=Module["dynCall_viiijii"]=Module["asm"]["am"]).apply(null,arguments)};var dynCall_vidddi=Module["dynCall_vidddi"]=function(){return(dynCall_vidddi=Module["dynCall_vidddi"]=Module["asm"]["bm"]).apply(null,arguments)};var dynCall_vjii=Module["dynCall_vjii"]=function(){return(dynCall_vjii=Module["dynCall_vjii"]=Module["asm"]["cm"]).apply(null,arguments)};var dynCall_jji=Module["dynCall_jji"]=function(){return(dynCall_jji=Module["dynCall_jji"]=Module["asm"]["dm"]).apply(null,arguments)};var dynCall_ijii=Module["dynCall_ijii"]=function(){return(dynCall_ijii=Module["dynCall_ijii"]=Module["asm"]["em"]).apply(null,arguments)};var dynCall_ijiii=Module["dynCall_ijiii"]=function(){return(dynCall_ijiii=Module["dynCall_ijiii"]=Module["asm"]["fm"]).apply(null,arguments)};var dynCall_iffffi=Module["dynCall_iffffi"]=function(){return(dynCall_iffffi=Module["dynCall_iffffi"]=Module["asm"]["gm"]).apply(null,arguments)};var dynCall_vfffi=Module["dynCall_vfffi"]=function(){return(dynCall_vfffi=Module["dynCall_vfffi"]=Module["asm"]["hm"]).apply(null,arguments)};var dynCall_vffffi=Module["dynCall_vffffi"]=function(){return(dynCall_vffffi=Module["dynCall_vffffi"]=Module["asm"]["im"]).apply(null,arguments)};var dynCall_viiiffii=Module["dynCall_viiiffii"]=function(){return(dynCall_viiiffii=Module["dynCall_viiiffii"]=Module["asm"]["jm"]).apply(null,arguments)};var dynCall_viffffffi=Module["dynCall_viffffffi"]=function(){return(dynCall_viffffffi=Module["dynCall_viffffffi"]=Module["asm"]["km"]).apply(null,arguments)};var dynCall_vffffffii=Module["dynCall_vffffffii"]=function(){return(dynCall_vffffffii=Module["dynCall_vffffffii"]=Module["asm"]["lm"]).apply(null,arguments)};var dynCall_vffffii=Module["dynCall_vffffii"]=function(){return(dynCall_vffffii=Module["dynCall_vffffii"]=Module["asm"]["mm"]).apply(null,arguments)};var dynCall_viiiifffi=Module["dynCall_viiiifffi"]=function(){return(dynCall_viiiifffi=Module["dynCall_viiiifffi"]=Module["asm"]["nm"]).apply(null,arguments)};var dynCall_ifi=Module["dynCall_ifi"]=function(){return(dynCall_ifi=Module["dynCall_ifi"]=Module["asm"]["om"]).apply(null,arguments)};var dynCall_vfiii=Module["dynCall_vfiii"]=function(){return(dynCall_vfiii=Module["dynCall_vfiii"]=Module["asm"]["pm"]).apply(null,arguments)};var dynCall_iffi=Module["dynCall_iffi"]=function(){return(dynCall_iffi=Module["dynCall_iffi"]=Module["asm"]["qm"]).apply(null,arguments)};var dynCall_vfii=Module["dynCall_vfii"]=function(){return(dynCall_vfii=Module["dynCall_vfii"]=Module["asm"]["rm"]).apply(null,arguments)};var dynCall_vjiiii=Module["dynCall_vjiiii"]=function(){return(dynCall_vjiiii=Module["dynCall_vjiiii"]=Module["asm"]["sm"]).apply(null,arguments)};var dynCall_iiiifiiiii=Module["dynCall_iiiifiiiii"]=function(){return(dynCall_iiiifiiiii=Module["dynCall_iiiifiiiii"]=Module["asm"]["tm"]).apply(null,arguments)};var dynCall_iiiifiiii=Module["dynCall_iiiifiiii"]=function(){return(dynCall_iiiifiiii=Module["dynCall_iiiifiiii"]=Module["asm"]["um"]).apply(null,arguments)};var dynCall_vijjii=Module["dynCall_vijjii"]=function(){return(dynCall_vijjii=Module["dynCall_vijjii"]=Module["asm"]["vm"]).apply(null,arguments)};var dynCall_viiiiiiifi=Module["dynCall_viiiiiiifi"]=function(){return(dynCall_viiiiiiifi=Module["dynCall_viiiiiiifi"]=Module["asm"]["wm"]).apply(null,arguments)};var dynCall_iiiiiiifiiii=Module["dynCall_iiiiiiifiiii"]=function(){return(dynCall_iiiiiiifiiii=Module["dynCall_iiiiiiifiiii"]=Module["asm"]["xm"]).apply(null,arguments)};var dynCall_viiiiiffii=Module["dynCall_viiiiiffii"]=function(){return(dynCall_viiiiiffii=Module["dynCall_viiiiiffii"]=Module["asm"]["ym"]).apply(null,arguments)};var dynCall_viffffii=Module["dynCall_viffffii"]=function(){return(dynCall_viffffii=Module["dynCall_viffffii"]=Module["asm"]["zm"]).apply(null,arguments)};var dynCall_vifiiii=Module["dynCall_vifiiii"]=function(){return(dynCall_vifiiii=Module["dynCall_vifiiii"]=Module["asm"]["Am"]).apply(null,arguments)};var dynCall_viiifiii=Module["dynCall_viiifiii"]=function(){return(dynCall_viiifiii=Module["dynCall_viiifiii"]=Module["asm"]["Bm"]).apply(null,arguments)};var dynCall_iiiiiiiiiiii=Module["dynCall_iiiiiiiiiiii"]=function(){return(dynCall_iiiiiiiiiiii=Module["dynCall_iiiiiiiiiiii"]=Module["asm"]["Cm"]).apply(null,arguments)};var dynCall_viffiiii=Module["dynCall_viffiiii"]=function(){return(dynCall_viffiiii=Module["dynCall_viffiiii"]=Module["asm"]["Dm"]).apply(null,arguments)};var dynCall_viiiiffffiiii=Module["dynCall_viiiiffffiiii"]=function(){return(dynCall_viiiiffffiiii=Module["dynCall_viiiiffffiiii"]=Module["asm"]["Em"]).apply(null,arguments)};var dynCall_iiiiiiffiiiiiiiiiffffiiii=Module["dynCall_iiiiiiffiiiiiiiiiffffiiii"]=function(){return(dynCall_iiiiiiffiiiiiiiiiffffiiii=Module["dynCall_iiiiiiffiiiiiiiiiffffiiii"]=Module["asm"]["Fm"]).apply(null,arguments)};var dynCall_iiiiiiffiiiiiiiiiiiiiii=Module["dynCall_iiiiiiffiiiiiiiiiiiiiii"]=function(){return(dynCall_iiiiiiffiiiiiiiiiiiiiii=Module["dynCall_iiiiiiffiiiiiiiiiiiiiii"]=Module["asm"]["Gm"]).apply(null,arguments)};var dynCall_fiiiffi=Module["dynCall_fiiiffi"]=function(){return(dynCall_fiiiffi=Module["dynCall_fiiiffi"]=Module["asm"]["Hm"]).apply(null,arguments)};var dynCall_viffffiii=Module["dynCall_viffffiii"]=function(){return(dynCall_viffffiii=Module["dynCall_viffffiii"]=Module["asm"]["Im"]).apply(null,arguments)};var dynCall_viijji=Module["dynCall_viijji"]=function(){return(dynCall_viijji=Module["dynCall_viijji"]=Module["asm"]["Jm"]).apply(null,arguments)};var dynCall_viififii=Module["dynCall_viififii"]=function(){return(dynCall_viififii=Module["dynCall_viififii"]=Module["asm"]["Km"]).apply(null,arguments)};var dynCall_iiiffiiii=Module["dynCall_iiiffiiii"]=function(){return(dynCall_iiiffiiii=Module["dynCall_iiiffiiii"]=Module["asm"]["Lm"]).apply(null,arguments)};var dynCall_iiiiffiiii=Module["dynCall_iiiiffiiii"]=function(){return(dynCall_iiiiffiiii=Module["dynCall_iiiiffiiii"]=Module["asm"]["Mm"]).apply(null,arguments)};var dynCall_viiffffi=Module["dynCall_viiffffi"]=function(){return(dynCall_viiffffi=Module["dynCall_viiffffi"]=Module["asm"]["Nm"]).apply(null,arguments)};var dynCall_viffiii=Module["dynCall_viffiii"]=function(){return(dynCall_viffiii=Module["dynCall_viffiii"]=Module["asm"]["Om"]).apply(null,arguments)};var dynCall_fffffffi=Module["dynCall_fffffffi"]=function(){return(dynCall_fffffffi=Module["dynCall_fffffffi"]=Module["asm"]["Pm"]).apply(null,arguments)};var dynCall_viffifi=Module["dynCall_viffifi"]=function(){return(dynCall_viffifi=Module["dynCall_viffifi"]=Module["asm"]["Qm"]).apply(null,arguments)};var dynCall_viiffifi=Module["dynCall_viiffifi"]=function(){return(dynCall_viiffifi=Module["dynCall_viiffifi"]=Module["asm"]["Rm"]).apply(null,arguments)};var dynCall_iijiii=Module["dynCall_iijiii"]=function(){return(dynCall_iijiii=Module["dynCall_iijiii"]=Module["asm"]["Sm"]).apply(null,arguments)};var dynCall_ifffi=Module["dynCall_ifffi"]=function(){return(dynCall_ifffi=Module["dynCall_ifffi"]=Module["asm"]["Tm"]).apply(null,arguments)};var dynCall_viiififiii=Module["dynCall_viiififiii"]=function(){return(dynCall_viiififiii=Module["dynCall_viiififiii"]=Module["asm"]["Um"]).apply(null,arguments)};var dynCall_viiffiiiiiiiii=Module["dynCall_viiffiiiiiiiii"]=function(){return(dynCall_viiffiiiiiiiii=Module["dynCall_viiffiiiiiiiii"]=Module["asm"]["Vm"]).apply(null,arguments)};var dynCall_viiiiiffiii=Module["dynCall_viiiiiffiii"]=function(){return(dynCall_viiiiiffiii=Module["dynCall_viiiiiffiii"]=Module["asm"]["Wm"]).apply(null,arguments)};var dynCall_viiffiii=Module["dynCall_viiffiii"]=function(){return(dynCall_viiffiii=Module["dynCall_viiffiii"]=Module["asm"]["Xm"]).apply(null,arguments)};var dynCall_viiffiiiiiii=Module["dynCall_viiffiiiiiii"]=function(){return(dynCall_viiffiiiiiii=Module["dynCall_viiffiiiiiii"]=Module["asm"]["Ym"]).apply(null,arguments)};var dynCall_viiffii=Module["dynCall_viiffii"]=function(){return(dynCall_viiffii=Module["dynCall_viiffii"]=Module["asm"]["Zm"]).apply(null,arguments)};var dynCall_fffffffffi=Module["dynCall_fffffffffi"]=function(){return(dynCall_fffffffffi=Module["dynCall_fffffffffi"]=Module["asm"]["_m"]).apply(null,arguments)};var dynCall_vifiiiiii=Module["dynCall_vifiiiiii"]=function(){return(dynCall_vifiiiiii=Module["dynCall_vifiiiiii"]=Module["asm"]["$m"]).apply(null,arguments)};var dynCall_viifiiiiiii=Module["dynCall_viifiiiiiii"]=function(){return(dynCall_viifiiiiiii=Module["dynCall_viifiiiiiii"]=Module["asm"]["an"]).apply(null,arguments)};var dynCall_viiififfiiiiiii=Module["dynCall_viiififfiiiiiii"]=function(){return(dynCall_viiififfiiiiiii=Module["dynCall_viiififfiiiiiii"]=Module["asm"]["bn"]).apply(null,arguments)};var dynCall_viiffiifiiiiiii=Module["dynCall_viiffiifiiiiiii"]=function(){return(dynCall_viiffiifiiiiiii=Module["dynCall_viiffiifiiiiiii"]=Module["asm"]["cn"]).apply(null,arguments)};var dynCall_viifiiiiii=Module["dynCall_viifiiiiii"]=function(){return(dynCall_viifiiiiii=Module["dynCall_viifiiiiii"]=Module["asm"]["dn"]).apply(null,arguments)};var dynCall_viiifiiiiii=Module["dynCall_viiifiiiiii"]=function(){return(dynCall_viiifiiiiii=Module["dynCall_viiifiiiiii"]=Module["asm"]["en"]).apply(null,arguments)};var dynCall_viiiifiiiiii=Module["dynCall_viiiifiiiiii"]=function(){return(dynCall_viiiifiiiiii=Module["dynCall_viiiifiiiiii"]=Module["asm"]["fn"]).apply(null,arguments)};var dynCall_viififiiiiii=Module["dynCall_viififiiiiii"]=function(){return(dynCall_viififiiiiii=Module["dynCall_viififiiiiii"]=Module["asm"]["gn"]).apply(null,arguments)};var dynCall_viiiffiifiiiiiii=Module["dynCall_viiiffiifiiiiiii"]=function(){return(dynCall_viiiffiifiiiiiii=Module["dynCall_viiiffiifiiiiiii"]=Module["asm"]["hn"]).apply(null,arguments)};var dynCall_viiiiiifiiiiii=Module["dynCall_viiiiiifiiiiii"]=function(){return(dynCall_viiiiiifiiiiii=Module["dynCall_viiiiiifiiiiii"]=Module["asm"]["jn"]).apply(null,arguments)};var dynCall_ffii=Module["dynCall_ffii"]=function(){return(dynCall_ffii=Module["dynCall_ffii"]=Module["asm"]["kn"]).apply(null,arguments)};var dynCall_viffii=Module["dynCall_viffii"]=function(){return(dynCall_viffii=Module["dynCall_viffii"]=Module["asm"]["ln"]).apply(null,arguments)};var dynCall_vififiii=Module["dynCall_vififiii"]=function(){return(dynCall_vififiii=Module["dynCall_vififiii"]=Module["asm"]["mn"]).apply(null,arguments)};var dynCall_viiiiiiiijiiii=Module["dynCall_viiiiiiiijiiii"]=function(){return(dynCall_viiiiiiiijiiii=Module["dynCall_viiiiiiiijiiii"]=Module["asm"]["nn"]).apply(null,arguments)};var dynCall_vifffii=Module["dynCall_vifffii"]=function(){return(dynCall_vifffii=Module["dynCall_vifffii"]=Module["asm"]["on"]).apply(null,arguments)};var dynCall_viiidii=Module["dynCall_viiidii"]=function(){return(dynCall_viiidii=Module["dynCall_viiidii"]=Module["asm"]["pn"]).apply(null,arguments)};var dynCall_ijiiiiiiiii=Module["dynCall_ijiiiiiiiii"]=function(){return(dynCall_ijiiiiiiiii=Module["dynCall_ijiiiiiiiii"]=Module["asm"]["qn"]).apply(null,arguments)};var dynCall_iiijiiiii=Module["dynCall_iiijiiiii"]=function(){return(dynCall_iiijiiiii=Module["dynCall_iiijiiiii"]=Module["asm"]["rn"]).apply(null,arguments)};var dynCall_viiijiii=Module["dynCall_viiijiii"]=function(){return(dynCall_viiijiii=Module["dynCall_viiijiii"]=Module["asm"]["sn"]).apply(null,arguments)};var dynCall_ijjiii=Module["dynCall_ijjiii"]=function(){return(dynCall_ijjiii=Module["dynCall_ijjiii"]=Module["asm"]["tn"]).apply(null,arguments)};var dynCall_ffiii=Module["dynCall_ffiii"]=function(){return(dynCall_ffiii=Module["dynCall_ffiii"]=Module["asm"]["un"]).apply(null,arguments)};var dynCall_ddiii=Module["dynCall_ddiii"]=function(){return(dynCall_ddiii=Module["dynCall_ddiii"]=Module["asm"]["vn"]).apply(null,arguments)};var dynCall_fffiii=Module["dynCall_fffiii"]=function(){return(dynCall_fffiii=Module["dynCall_fffiii"]=Module["asm"]["wn"]).apply(null,arguments)};var dynCall_dddiii=Module["dynCall_dddiii"]=function(){return(dynCall_dddiii=Module["dynCall_dddiii"]=Module["asm"]["xn"]).apply(null,arguments)};var dynCall_jjiii=Module["dynCall_jjiii"]=function(){return(dynCall_jjiii=Module["dynCall_jjiii"]=Module["asm"]["yn"]).apply(null,arguments)};var dynCall_jddi=Module["dynCall_jddi"]=function(){return(dynCall_jddi=Module["dynCall_jddi"]=Module["asm"]["zn"]).apply(null,arguments)};var dynCall_jjii=Module["dynCall_jjii"]=function(){return(dynCall_jjii=Module["dynCall_jjii"]=Module["asm"]["An"]).apply(null,arguments)};var dynCall_jjjii=Module["dynCall_jjjii"]=function(){return(dynCall_jjjii=Module["dynCall_jjjii"]=Module["asm"]["Bn"]).apply(null,arguments)};var dynCall_jdii=Module["dynCall_jdii"]=function(){return(dynCall_jdii=Module["dynCall_jdii"]=Module["asm"]["Cn"]).apply(null,arguments)};var dynCall_djii=Module["dynCall_djii"]=function(){return(dynCall_djii=Module["dynCall_djii"]=Module["asm"]["Dn"]).apply(null,arguments)};var dynCall_fdi=Module["dynCall_fdi"]=function(){return(dynCall_fdi=Module["dynCall_fdi"]=Module["asm"]["En"]).apply(null,arguments)};var dynCall_jjiiii=Module["dynCall_jjiiii"]=function(){return(dynCall_jjiiii=Module["dynCall_jjiiii"]=Module["asm"]["Fn"]).apply(null,arguments)};var dynCall_ddi=Module["dynCall_ddi"]=function(){return(dynCall_ddi=Module["dynCall_ddi"]=Module["asm"]["Gn"]).apply(null,arguments)};var dynCall_viiiiiiiiiiiiiiiiii=Module["dynCall_viiiiiiiiiiiiiiiiii"]=function(){return(dynCall_viiiiiiiiiiiiiiiiii=Module["dynCall_viiiiiiiiiiiiiiiiii"]=Module["asm"]["Hn"]).apply(null,arguments)};var dynCall_viiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii=Module["dynCall_viiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"]=function(){return(dynCall_viiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii=Module["dynCall_viiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"]=Module["asm"]["In"]).apply(null,arguments)};var dynCall_viffffffffi=Module["dynCall_viffffffffi"]=function(){return(dynCall_viffffffffi=Module["dynCall_viffffffffi"]=Module["asm"]["Jn"]).apply(null,arguments)};var dynCall_viddddi=Module["dynCall_viddddi"]=function(){return(dynCall_viddddi=Module["dynCall_viddddi"]=Module["asm"]["Kn"]).apply(null,arguments)};var dynCall_ddii=Module["dynCall_ddii"]=function(){return(dynCall_ddii=Module["dynCall_ddii"]=Module["asm"]["Ln"]).apply(null,arguments)};var dynCall_vijiiii=Module["dynCall_vijiiii"]=function(){return(dynCall_vijiiii=Module["dynCall_vijiiii"]=Module["asm"]["Mn"]).apply(null,arguments)};var dynCall_viiiidii=Module["dynCall_viiiidii"]=function(){return(dynCall_viiiidii=Module["dynCall_viiiidii"]=Module["asm"]["Nn"]).apply(null,arguments)};var dynCall_vidiiiii=Module["dynCall_vidiiiii"]=function(){return(dynCall_vidiiiii=Module["dynCall_vidiiiii"]=Module["asm"]["On"]).apply(null,arguments)};var dynCall_viiidjii=Module["dynCall_viiidjii"]=function(){return(dynCall_viiidjii=Module["dynCall_viiidjii"]=Module["asm"]["Pn"]).apply(null,arguments)};var dynCall_iidii=Module["dynCall_iidii"]=function(){return(dynCall_iidii=Module["dynCall_iidii"]=Module["asm"]["Qn"]).apply(null,arguments)};var dynCall_viijijji=Module["dynCall_viijijji"]=function(){return(dynCall_viijijji=Module["dynCall_viijijji"]=Module["asm"]["Rn"]).apply(null,arguments)};var dynCall_vijijji=Module["dynCall_vijijji"]=function(){return(dynCall_vijijji=Module["dynCall_vijijji"]=Module["asm"]["Sn"]).apply(null,arguments)};var dynCall_vidii=Module["dynCall_vidii"]=function(){return(dynCall_vidii=Module["dynCall_vidii"]=Module["asm"]["Tn"]).apply(null,arguments)};var dynCall_iddi=Module["dynCall_iddi"]=function(){return(dynCall_iddi=Module["dynCall_iddi"]=Module["asm"]["Un"]).apply(null,arguments)};var dynCall_viddddddi=Module["dynCall_viddddddi"]=function(){return(dynCall_viddddddi=Module["dynCall_viddddddi"]=Module["asm"]["Vn"]).apply(null,arguments)};var dynCall_viddddddddi=Module["dynCall_viddddddddi"]=function(){return(dynCall_viddddddddi=Module["dynCall_viddddddddi"]=Module["asm"]["Wn"]).apply(null,arguments)};var dynCall_vidddddddddi=Module["dynCall_vidddddddddi"]=function(){return(dynCall_vidddddddddi=Module["dynCall_vidddddddddi"]=Module["asm"]["Xn"]).apply(null,arguments)};var dynCall_viddddddddddddi=Module["dynCall_viddddddddddddi"]=function(){return(dynCall_viddddddddddddi=Module["dynCall_viddddddddddddi"]=Module["asm"]["Yn"]).apply(null,arguments)};var dynCall_viddii=Module["dynCall_viddii"]=function(){return(dynCall_viddii=Module["dynCall_viddii"]=Module["asm"]["Zn"]).apply(null,arguments)};var dynCall_vididi=Module["dynCall_vididi"]=function(){return(dynCall_vididi=Module["dynCall_vididi"]=Module["asm"]["_n"]).apply(null,arguments)};var dynCall_viddddddddddddddddi=Module["dynCall_viddddddddddddddddi"]=function(){return(dynCall_viddddddddddddddddi=Module["dynCall_viddddddddddddddddi"]=Module["asm"]["$n"]).apply(null,arguments)};var dynCall_vifffffffffi=Module["dynCall_vifffffffffi"]=function(){return(dynCall_vifffffffffi=Module["dynCall_vifffffffffi"]=Module["asm"]["ao"]).apply(null,arguments)};var dynCall_viffffffffffffi=Module["dynCall_viffffffffffffi"]=function(){return(dynCall_viffffffffffffi=Module["dynCall_viffffffffffffi"]=Module["asm"]["bo"]).apply(null,arguments)};var dynCall_vififi=Module["dynCall_vififi"]=function(){return(dynCall_vififi=Module["dynCall_vififi"]=Module["asm"]["co"]).apply(null,arguments)};var dynCall_viffffffffffffffffi=Module["dynCall_viffffffffffffffffi"]=function(){return(dynCall_viffffffffffffffffi=Module["dynCall_viffffffffffffffffi"]=Module["asm"]["eo"]).apply(null,arguments)};var dynCall_ddddi=Module["dynCall_ddddi"]=function(){return(dynCall_ddddi=Module["dynCall_ddddi"]=Module["asm"]["fo"]).apply(null,arguments)};var dynCall_ddddddi=Module["dynCall_ddddddi"]=function(){return(dynCall_ddddddi=Module["dynCall_ddddddi"]=Module["asm"]["go"]).apply(null,arguments)};var dynCall_jjjji=Module["dynCall_jjjji"]=function(){return(dynCall_jjjji=Module["dynCall_jjjji"]=Module["asm"]["ho"]).apply(null,arguments)};var dynCall_fffii=Module["dynCall_fffii"]=function(){return(dynCall_fffii=Module["dynCall_fffii"]=Module["asm"]["io"]).apply(null,arguments)};var dynCall_dddii=Module["dynCall_dddii"]=function(){return(dynCall_dddii=Module["dynCall_dddii"]=Module["asm"]["jo"]).apply(null,arguments)};var dynCall_vdiii=Module["dynCall_vdiii"]=function(){return(dynCall_vdiii=Module["dynCall_vdiii"]=Module["asm"]["ko"]).apply(null,arguments)};var dynCall_didi=Module["dynCall_didi"]=function(){return(dynCall_didi=Module["dynCall_didi"]=Module["asm"]["lo"]).apply(null,arguments)};var dynCall_diddi=Module["dynCall_diddi"]=function(){return(dynCall_diddi=Module["dynCall_diddi"]=Module["asm"]["mo"]).apply(null,arguments)};var dynCall_viifffii=Module["dynCall_viifffii"]=function(){return(dynCall_viifffii=Module["dynCall_viifffii"]=Module["asm"]["no"]).apply(null,arguments)};var dynCall_viiiffiffiiiiiiiiiiiiiii=Module["dynCall_viiiffiffiiiiiiiiiiiiiii"]=function(){return(dynCall_viiiffiffiiiiiiiiiiiiiii=Module["dynCall_viiiffiffiiiiiiiiiiiiiii"]=Module["asm"]["oo"]).apply(null,arguments)};var dynCall_viiiffiffiiiiiiiiiiiiiiiii=Module["dynCall_viiiffiffiiiiiiiiiiiiiiiii"]=function(){return(dynCall_viiiffiffiiiiiiiiiiiiiiiii=Module["dynCall_viiiffiffiiiiiiiiiiiiiiiii"]=Module["asm"]["po"]).apply(null,arguments)};var dynCall_viiiiiffiiiii=Module["dynCall_viiiiiffiiiii"]=function(){return(dynCall_viiiiiffiiiii=Module["dynCall_viiiiiffiiiii"]=Module["asm"]["qo"]).apply(null,arguments)};var dynCall_iiiiiiiiiiiiiifiiiiii=Module["dynCall_iiiiiiiiiiiiiifiiiiii"]=function(){return(dynCall_iiiiiiiiiiiiiifiiiiii=Module["dynCall_iiiiiiiiiiiiiifiiiiii"]=Module["asm"]["ro"]).apply(null,arguments)};var dynCall_iiiiiiiiiiiiifiiiiii=Module["dynCall_iiiiiiiiiiiiifiiiiii"]=function(){return(dynCall_iiiiiiiiiiiiifiiiiii=Module["dynCall_iiiiiiiiiiiiifiiiiii"]=Module["asm"]["so"]).apply(null,arguments)};var dynCall_iiiiiiiiiiiiiiifiiiiii=Module["dynCall_iiiiiiiiiiiiiiifiiiiii"]=function(){return(dynCall_iiiiiiiiiiiiiiifiiiiii=Module["dynCall_iiiiiiiiiiiiiiifiiiiii"]=Module["asm"]["to"]).apply(null,arguments)};var dynCall_viiiffffi=Module["dynCall_viiiffffi"]=function(){return(dynCall_viiiffffi=Module["dynCall_viiiffffi"]=Module["asm"]["uo"]).apply(null,arguments)};var dynCall_iiiiiiifi=Module["dynCall_iiiiiiifi"]=function(){return(dynCall_iiiiiiifi=Module["dynCall_iiiiiiifi"]=Module["asm"]["vo"]).apply(null,arguments)};var dynCall_iiiiiifiii=Module["dynCall_iiiiiifiii"]=function(){return(dynCall_iiiiiifiii=Module["dynCall_iiiiiifiii"]=Module["asm"]["wo"]).apply(null,arguments)};var dynCall_iiiiiiiifiiiii=Module["dynCall_iiiiiiiifiiiii"]=function(){return(dynCall_iiiiiiiifiiiii=Module["dynCall_iiiiiiiifiiiii"]=Module["asm"]["xo"]).apply(null,arguments)};var dynCall_vffiii=Module["dynCall_vffiii"]=function(){return(dynCall_vffiii=Module["dynCall_vffiii"]=Module["asm"]["yo"]).apply(null,arguments)};var dynCall_vififiiii=Module["dynCall_vififiiii"]=function(){return(dynCall_vififiiii=Module["dynCall_vififiiii"]=Module["asm"]["zo"]).apply(null,arguments)};var dynCall_viiiiiiiifi=Module["dynCall_viiiiiiiifi"]=function(){return(dynCall_viiiiiiiifi=Module["dynCall_viiiiiiiifi"]=Module["asm"]["Ao"]).apply(null,arguments)};var dynCall_iiiiiffii=Module["dynCall_iiiiiffii"]=function(){return(dynCall_iiiiiffii=Module["dynCall_iiiiiffii"]=Module["asm"]["Bo"]).apply(null,arguments)};var dynCall_viiffffffi=Module["dynCall_viiffffffi"]=function(){return(dynCall_viiffffffi=Module["dynCall_viiffffffi"]=Module["asm"]["Co"]).apply(null,arguments)};var dynCall_viifffffffi=Module["dynCall_viifffffffi"]=function(){return(dynCall_viifffffffi=Module["dynCall_viifffffffi"]=Module["asm"]["Do"]).apply(null,arguments)};var dynCall_viiffffffffi=Module["dynCall_viiffffffffi"]=function(){return(dynCall_viiffffffffi=Module["dynCall_viiffffffffi"]=Module["asm"]["Eo"]).apply(null,arguments)};var dynCall_viiffffffffiii=Module["dynCall_viiffffffffiii"]=function(){return(dynCall_viiffffffffiii=Module["dynCall_viiffffffffiii"]=Module["asm"]["Fo"]).apply(null,arguments)};var dynCall_viiiiffffii=Module["dynCall_viiiiffffii"]=function(){return(dynCall_viiiiffffii=Module["dynCall_viiiiffffii"]=Module["asm"]["Go"]).apply(null,arguments)};var dynCall_fidi=Module["dynCall_fidi"]=function(){return(dynCall_fidi=Module["dynCall_fidi"]=Module["asm"]["Ho"]).apply(null,arguments)};var dynCall_ddidi=Module["dynCall_ddidi"]=function(){return(dynCall_ddidi=Module["dynCall_ddidi"]=Module["asm"]["Io"]).apply(null,arguments)};var dynCall_jfi=Module["dynCall_jfi"]=function(){return(dynCall_jfi=Module["dynCall_jfi"]=Module["asm"]["Jo"]).apply(null,arguments)};var dynCall_fji=Module["dynCall_fji"]=function(){return(dynCall_fji=Module["dynCall_fji"]=Module["asm"]["Ko"]).apply(null,arguments)};var dynCall_viiiiddi=Module["dynCall_viiiiddi"]=function(){return(dynCall_viiiiddi=Module["dynCall_viiiiddi"]=Module["asm"]["Lo"]).apply(null,arguments)};var dynCall_iiiddi=Module["dynCall_iiiddi"]=function(){return(dynCall_iiiddi=Module["dynCall_iiiddi"]=Module["asm"]["Mo"]).apply(null,arguments)};var dynCall_viddiiii=Module["dynCall_viddiiii"]=function(){return(dynCall_viddiiii=Module["dynCall_viddiiii"]=Module["asm"]["No"]).apply(null,arguments)};var dynCall_vdi=Module["dynCall_vdi"]=function(){return(dynCall_vdi=Module["dynCall_vdi"]=Module["asm"]["Oo"]).apply(null,arguments)};var dynCall_idddi=Module["dynCall_idddi"]=function(){return(dynCall_idddi=Module["dynCall_idddi"]=Module["asm"]["Po"]).apply(null,arguments)};var dynCall_iddii=Module["dynCall_iddii"]=function(){return(dynCall_iddii=Module["dynCall_iddii"]=Module["asm"]["Qo"]).apply(null,arguments)};var dynCall_idiiii=Module["dynCall_idiiii"]=function(){return(dynCall_idiiii=Module["dynCall_idiiii"]=Module["asm"]["Ro"]).apply(null,arguments)};var dynCall_iiiiiiiiiiiiii=Module["dynCall_iiiiiiiiiiiiii"]=function(){return(dynCall_iiiiiiiiiiiiii=Module["dynCall_iiiiiiiiiiiiii"]=Module["asm"]["So"]).apply(null,arguments)};var dynCall_vijiiiiiii=Module["dynCall_vijiiiiiii"]=function(){return(dynCall_vijiiiiiii=Module["dynCall_vijiiiiiii"]=Module["asm"]["To"]).apply(null,arguments)};var dynCall_vijiiiiiiii=Module["dynCall_vijiiiiiiii"]=function(){return(dynCall_vijiiiiiiii=Module["dynCall_vijiiiiiiii"]=Module["asm"]["Uo"]).apply(null,arguments)};var dynCall_jijii=Module["dynCall_jijii"]=function(){return(dynCall_jijii=Module["dynCall_jijii"]=Module["asm"]["Vo"]).apply(null,arguments)};var dynCall_jjiiiii=Module["dynCall_jjiiiii"]=function(){return(dynCall_jjiiiii=Module["dynCall_jjiiiii"]=Module["asm"]["Wo"]).apply(null,arguments)};var dynCall_iijiiiiii=Module["dynCall_iijiiiiii"]=function(){return(dynCall_iijiiiiii=Module["dynCall_iijiiiiii"]=Module["asm"]["Xo"]).apply(null,arguments)};var dynCall_iiiijjii=Module["dynCall_iiiijjii"]=function(){return(dynCall_iiiijjii=Module["dynCall_iiiijjii"]=Module["asm"]["Yo"]).apply(null,arguments)};var dynCall_jijjji=Module["dynCall_jijjji"]=function(){return(dynCall_jijjji=Module["dynCall_jijjji"]=Module["asm"]["Zo"]).apply(null,arguments)};var dynCall_jijjjii=Module["dynCall_jijjjii"]=function(){return(dynCall_jijjjii=Module["dynCall_jijjjii"]=Module["asm"]["_o"]).apply(null,arguments)};var dynCall_ijiiii=Module["dynCall_ijiiii"]=function(){return(dynCall_ijiiii=Module["dynCall_ijiiii"]=Module["asm"]["$o"]).apply(null,arguments)};var dynCall_ijijiiiii=Module["dynCall_ijijiiiii"]=function(){return(dynCall_ijijiiiii=Module["dynCall_ijijiiiii"]=Module["asm"]["ap"]).apply(null,arguments)};var dynCall_ijjjiii=Module["dynCall_ijjjiii"]=function(){return(dynCall_ijjjiii=Module["dynCall_ijjjiii"]=Module["asm"]["bp"]).apply(null,arguments)};var dynCall_vijjjiijii=Module["dynCall_vijjjiijii"]=function(){return(dynCall_vijjjiijii=Module["dynCall_vijjjiijii"]=Module["asm"]["cp"]).apply(null,arguments)};var dynCall_ijjjiijii=Module["dynCall_ijjjiijii"]=function(){return(dynCall_ijjjiijii=Module["dynCall_ijjjiijii"]=Module["asm"]["dp"]).apply(null,arguments)};var dynCall_vijiiiiii=Module["dynCall_vijiiiiii"]=function(){return(dynCall_vijiiiiii=Module["dynCall_vijiiiiii"]=Module["asm"]["ep"]).apply(null,arguments)};var dynCall_dfi=Module["dynCall_dfi"]=function(){return(dynCall_dfi=Module["dynCall_dfi"]=Module["asm"]["fp"]).apply(null,arguments)};var dynCall_jidii=Module["dynCall_jidii"]=function(){return(dynCall_jidii=Module["dynCall_jidii"]=Module["asm"]["gp"]).apply(null,arguments)};var dynCall_jidi=Module["dynCall_jidi"]=function(){return(dynCall_jidi=Module["dynCall_jidi"]=Module["asm"]["hp"]).apply(null,arguments)};var dynCall_ijiijii=Module["dynCall_ijiijii"]=function(){return(dynCall_ijiijii=Module["dynCall_ijiijii"]=Module["asm"]["ip"]).apply(null,arguments)};var dynCall_vjjiiiii=Module["dynCall_vjjiiiii"]=function(){return(dynCall_vjjiiiii=Module["dynCall_vjjiiiii"]=Module["asm"]["jp"]).apply(null,arguments)};var dynCall_vjjii=Module["dynCall_vjjii"]=function(){return(dynCall_vjjii=Module["dynCall_vjjii"]=Module["asm"]["kp"]).apply(null,arguments)};var dynCall_ijiiji=Module["dynCall_ijiiji"]=function(){return(dynCall_ijiiji=Module["dynCall_ijiiji"]=Module["asm"]["lp"]).apply(null,arguments)};var dynCall_ijiiiii=Module["dynCall_ijiiiii"]=function(){return(dynCall_ijiiiii=Module["dynCall_ijiiiii"]=Module["asm"]["mp"]).apply(null,arguments)};var dynCall_ijiiiiji=Module["dynCall_ijiiiiji"]=function(){return(dynCall_ijiiiiji=Module["dynCall_ijiiiiji"]=Module["asm"]["np"]).apply(null,arguments)};var dynCall_idiii=Module["dynCall_idiii"]=function(){return(dynCall_idiii=Module["dynCall_idiii"]=Module["asm"]["op"]).apply(null,arguments)};var dynCall_idiiiii=Module["dynCall_idiiiii"]=function(){return(dynCall_idiiiii=Module["dynCall_idiiiii"]=Module["asm"]["pp"]).apply(null,arguments)};var dynCall_iidiii=Module["dynCall_iidiii"]=function(){return(dynCall_iidiii=Module["dynCall_iidiii"]=Module["asm"]["qp"]).apply(null,arguments)};var dynCall_ifiiiii=Module["dynCall_ifiiiii"]=function(){return(dynCall_ifiiiii=Module["dynCall_ifiiiii"]=Module["asm"]["rp"]).apply(null,arguments)};var dynCall_iijjji=Module["dynCall_iijjji"]=function(){return(dynCall_iijjji=Module["dynCall_iijjji"]=Module["asm"]["sp"]).apply(null,arguments)};var dynCall_viijjji=Module["dynCall_viijjji"]=function(){return(dynCall_viijjji=Module["dynCall_viijjji"]=Module["asm"]["tp"]).apply(null,arguments)};var dynCall_vdii=Module["dynCall_vdii"]=function(){return(dynCall_vdii=Module["dynCall_vdii"]=Module["asm"]["up"]).apply(null,arguments)};var dynCall_iiiijii=Module["dynCall_iiiijii"]=function(){return(dynCall_iiiijii=Module["dynCall_iiiijii"]=Module["asm"]["vp"]).apply(null,arguments)};var dynCall_jijji=Module["dynCall_jijji"]=function(){return(dynCall_jijji=Module["dynCall_jijji"]=Module["asm"]["wp"]).apply(null,arguments)};var dynCall_viiiijii=Module["dynCall_viiiijii"]=function(){return(dynCall_viiiijii=Module["dynCall_viiiijii"]=Module["asm"]["xp"]).apply(null,arguments)};var dynCall_viiijji=Module["dynCall_viiijji"]=function(){return(dynCall_viiijji=Module["dynCall_viiijji"]=Module["asm"]["yp"]).apply(null,arguments)};var dynCall_iijjii=Module["dynCall_iijjii"]=function(){return(dynCall_iijjii=Module["dynCall_iijjii"]=Module["asm"]["zp"]).apply(null,arguments)};var dynCall_viijijii=Module["dynCall_viijijii"]=function(){return(dynCall_viijijii=Module["dynCall_viijijii"]=Module["asm"]["Ap"]).apply(null,arguments)};var dynCall_viijijiii=Module["dynCall_viijijiii"]=function(){return(dynCall_viijijiii=Module["dynCall_viijijiii"]=Module["asm"]["Bp"]).apply(null,arguments)};var dynCall_vijiji=Module["dynCall_vijiji"]=function(){return(dynCall_vijiji=Module["dynCall_vijiji"]=Module["asm"]["Cp"]).apply(null,arguments)};var dynCall_viijiijiii=Module["dynCall_viijiijiii"]=function(){return(dynCall_viijiijiii=Module["dynCall_viijiijiii"]=Module["asm"]["Dp"]).apply(null,arguments)};var dynCall_viiiijiiii=Module["dynCall_viiiijiiii"]=function(){return(dynCall_viiiijiiii=Module["dynCall_viiiijiiii"]=Module["asm"]["Ep"]).apply(null,arguments)};var dynCall_jiiiiii=Module["dynCall_jiiiiii"]=function(){return(dynCall_jiiiiii=Module["dynCall_jiiiiii"]=Module["asm"]["Fp"]).apply(null,arguments)};var dynCall_viijjii=Module["dynCall_viijjii"]=function(){return(dynCall_viijjii=Module["dynCall_viijjii"]=Module["asm"]["Gp"]).apply(null,arguments)};var dynCall_vijjji=Module["dynCall_vijjji"]=function(){return(dynCall_vijjji=Module["dynCall_vijjji"]=Module["asm"]["Hp"]).apply(null,arguments)};var dynCall_fiiffii=Module["dynCall_fiiffii"]=function(){return(dynCall_fiiffii=Module["dynCall_fiiffii"]=Module["asm"]["Ip"]).apply(null,arguments)};var dynCall_fiifiii=Module["dynCall_fiifiii"]=function(){return(dynCall_fiifiii=Module["dynCall_fiifiii"]=Module["asm"]["Jp"]).apply(null,arguments)};var dynCall_viiffiiii=Module["dynCall_viiffiiii"]=function(){return(dynCall_viiffiiii=Module["dynCall_viiffiiii"]=Module["asm"]["Kp"]).apply(null,arguments)};var dynCall_fiiffiii=Module["dynCall_fiiffiii"]=function(){return(dynCall_fiiffiii=Module["dynCall_fiiffiii"]=Module["asm"]["Lp"]).apply(null,arguments)};var dynCall_iififfi=Module["dynCall_iififfi"]=function(){return(dynCall_iififfi=Module["dynCall_iififfi"]=Module["asm"]["Mp"]).apply(null,arguments)};var dynCall_iiiiijii=Module["dynCall_iiiiijii"]=function(){return(dynCall_iiiiijii=Module["dynCall_iiiiijii"]=Module["asm"]["Np"]).apply(null,arguments)};var dynCall_iiijii=Module["dynCall_iiijii"]=function(){return(dynCall_iiijii=Module["dynCall_iiijii"]=Module["asm"]["Op"]).apply(null,arguments)};var dynCall_iidfii=Module["dynCall_iidfii"]=function(){return(dynCall_iidfii=Module["dynCall_iidfii"]=Module["asm"]["Pp"]).apply(null,arguments)};var dynCall_iidfi=Module["dynCall_iidfi"]=function(){return(dynCall_iidfi=Module["dynCall_iidfi"]=Module["asm"]["Qp"]).apply(null,arguments)};var dynCall_iiddfi=Module["dynCall_iiddfi"]=function(){return(dynCall_iiddfi=Module["dynCall_iiddfi"]=Module["asm"]["Rp"]).apply(null,arguments)};var dynCall_iijfii=Module["dynCall_iijfii"]=function(){return(dynCall_iijfii=Module["dynCall_iijfii"]=Module["asm"]["Sp"]).apply(null,arguments)};var dynCall_iijfi=Module["dynCall_iijfi"]=function(){return(dynCall_iijfi=Module["dynCall_iijfi"]=Module["asm"]["Tp"]).apply(null,arguments)};var dynCall_iijjfi=Module["dynCall_iijjfi"]=function(){return(dynCall_iijjfi=Module["dynCall_iijjfi"]=Module["asm"]["Up"]).apply(null,arguments)};var dynCall_iiiiffiiiji=Module["dynCall_iiiiffiiiji"]=function(){return(dynCall_iiiiffiiiji=Module["dynCall_iiiiffiiiji"]=Module["asm"]["Vp"]).apply(null,arguments)};var dynCall_iiidfii=Module["dynCall_iiidfii"]=function(){return(dynCall_iiidfii=Module["dynCall_iiidfii"]=Module["asm"]["Wp"]).apply(null,arguments)};var dynCall_iiijfii=Module["dynCall_iiijfii"]=function(){return(dynCall_iiijfii=Module["dynCall_iiijfii"]=Module["asm"]["Xp"]).apply(null,arguments)};var dynCall_fiiiiiii=Module["dynCall_fiiiiiii"]=function(){return(dynCall_fiiiiiii=Module["dynCall_fiiiiiii"]=Module["asm"]["Yp"]).apply(null,arguments)};var dynCall_iiiiffiiiii=Module["dynCall_iiiiffiiiii"]=function(){return(dynCall_iiiiffiiiii=Module["dynCall_iiiiffiiiii"]=Module["asm"]["Zp"]).apply(null,arguments)};var dynCall_iiiidfii=Module["dynCall_iiiidfii"]=function(){return(dynCall_iiiidfii=Module["dynCall_iiiidfii"]=Module["asm"]["_p"]).apply(null,arguments)};var dynCall_iiiijfii=Module["dynCall_iiiijfii"]=function(){return(dynCall_iiiijfii=Module["dynCall_iiiijfii"]=Module["asm"]["$p"]).apply(null,arguments)};var dynCall_iiiiffii=Module["dynCall_iiiiffii"]=function(){return(dynCall_iiiiffii=Module["dynCall_iiiiffii"]=Module["asm"]["aq"]).apply(null,arguments)};var dynCall_jiiiiji=Module["dynCall_jiiiiji"]=function(){return(dynCall_jiiiiji=Module["dynCall_jiiiiji"]=Module["asm"]["bq"]).apply(null,arguments)};var dynCall_fiiiifi=Module["dynCall_fiiiifi"]=function(){return(dynCall_fiiiifi=Module["dynCall_fiiiifi"]=Module["asm"]["cq"]).apply(null,arguments)};var dynCall_didii=Module["dynCall_didii"]=function(){return(dynCall_didii=Module["dynCall_didii"]=Module["asm"]["dq"]).apply(null,arguments)};var dynCall_vidiji=Module["dynCall_vidiji"]=function(){return(dynCall_vidiji=Module["dynCall_vidiji"]=Module["asm"]["eq"]).apply(null,arguments)};var dynCall_vidjii=Module["dynCall_vidjii"]=function(){return(dynCall_vidjii=Module["dynCall_vidjii"]=Module["asm"]["fq"]).apply(null,arguments)};var dynCall_iiiijiii=Module["dynCall_iiiijiii"]=function(){return(dynCall_iiiijiii=Module["dynCall_iiiijiii"]=Module["asm"]["gq"]).apply(null,arguments)};var dynCall_iiiij=Module["dynCall_iiiij"]=function(){return(dynCall_iiiij=Module["dynCall_iiiij"]=Module["asm"]["hq"]).apply(null,arguments)};var dynCall_fff=Module["dynCall_fff"]=function(){return(dynCall_fff=Module["dynCall_fff"]=Module["asm"]["iq"]).apply(null,arguments)};var dynCall_ijj=Module["dynCall_ijj"]=function(){return(dynCall_ijj=Module["dynCall_ijj"]=Module["asm"]["jq"]).apply(null,arguments)};var dynCall_vjji=Module["dynCall_vjji"]=function(){return(dynCall_vjji=Module["dynCall_vjji"]=Module["asm"]["kq"]).apply(null,arguments)};var dynCall_ij=Module["dynCall_ij"]=function(){return(dynCall_ij=Module["dynCall_ij"]=Module["asm"]["lq"]).apply(null,arguments)};var dynCall_vif=Module["dynCall_vif"]=function(){return(dynCall_vif=Module["dynCall_vif"]=Module["asm"]["mq"]).apply(null,arguments)};var dynCall_vjiiiiiii=Module["dynCall_vjiiiiiii"]=function(){return(dynCall_vjiiiiiii=Module["dynCall_vjiiiiiii"]=Module["asm"]["nq"]).apply(null,arguments)};var dynCall_vid=Module["dynCall_vid"]=function(){return(dynCall_vid=Module["dynCall_vid"]=Module["asm"]["oq"]).apply(null,arguments)};var dynCall_viiiiif=Module["dynCall_viiiiif"]=function(){return(dynCall_viiiiif=Module["dynCall_viiiiif"]=Module["asm"]["pq"]).apply(null,arguments)};var dynCall_viiiif=Module["dynCall_viiiif"]=function(){return(dynCall_viiiif=Module["dynCall_viiiif"]=Module["asm"]["qq"]).apply(null,arguments)};var dynCall_viiiiiif=Module["dynCall_viiiiiif"]=function(){return(dynCall_viiiiiif=Module["dynCall_viiiiiif"]=Module["asm"]["rq"]).apply(null,arguments)};var dynCall_iiif=Module["dynCall_iiif"]=function(){return(dynCall_iiif=Module["dynCall_iiif"]=Module["asm"]["sq"]).apply(null,arguments)};var dynCall_viiiiiji=Module["dynCall_viiiiiji"]=function(){return(dynCall_viiiiiji=Module["dynCall_viiiiiji"]=Module["asm"]["tq"]).apply(null,arguments)};var dynCall_fif=Module["dynCall_fif"]=function(){return(dynCall_fif=Module["dynCall_fif"]=Module["asm"]["uq"]).apply(null,arguments)};var dynCall_iiiiiifff=Module["dynCall_iiiiiifff"]=function(){return(dynCall_iiiiiifff=Module["dynCall_iiiiiifff"]=Module["asm"]["vq"]).apply(null,arguments)};var dynCall_iiiiiifiif=Module["dynCall_iiiiiifiif"]=function(){return(dynCall_iiiiiifiif=Module["dynCall_iiiiiifiif"]=Module["asm"]["wq"]).apply(null,arguments)};var dynCall_iiiiiiifiif=Module["dynCall_iiiiiiifiif"]=function(){return(dynCall_iiiiiiifiif=Module["dynCall_iiiiiiifiif"]=Module["asm"]["xq"]).apply(null,arguments)};var dynCall_fiff=Module["dynCall_fiff"]=function(){return(dynCall_fiff=Module["dynCall_fiff"]=Module["asm"]["yq"]).apply(null,arguments)};var dynCall_fiiiiiifiifif=Module["dynCall_fiiiiiifiifif"]=function(){return(dynCall_fiiiiiifiifif=Module["dynCall_fiiiiiifiifif"]=Module["asm"]["zq"]).apply(null,arguments)};var dynCall_fiiiiiifiiiif=Module["dynCall_fiiiiiifiiiif"]=function(){return(dynCall_fiiiiiifiiiif=Module["dynCall_fiiiiiifiiiif"]=Module["asm"]["Aq"]).apply(null,arguments)};var dynCall_iifiiiijii=Module["dynCall_iifiiiijii"]=function(){return(dynCall_iifiiiijii=Module["dynCall_iifiiiijii"]=Module["asm"]["Bq"]).apply(null,arguments)};var dynCall_vifijii=Module["dynCall_vifijii"]=function(){return(dynCall_vifijii=Module["dynCall_vifijii"]=Module["asm"]["Cq"]).apply(null,arguments)};var dynCall_iiiifffiii=Module["dynCall_iiiifffiii"]=function(){return(dynCall_iiiifffiii=Module["dynCall_iiiifffiii"]=Module["asm"]["Dq"]).apply(null,arguments)};var dynCall_iiiifffffi=Module["dynCall_iiiifffffi"]=function(){return(dynCall_iiiifffffi=Module["dynCall_iiiifffffi"]=Module["asm"]["Eq"]).apply(null,arguments)};var dynCall_viffiiiif=Module["dynCall_viffiiiif"]=function(){return(dynCall_viffiiiif=Module["dynCall_viffiiiif"]=Module["asm"]["Fq"]).apply(null,arguments)};var dynCall_viffiifffffiii=Module["dynCall_viffiifffffiii"]=function(){return(dynCall_viffiifffffiii=Module["dynCall_viffiifffffiii"]=Module["asm"]["Gq"]).apply(null,arguments)};var dynCall_viffffiifffiiiiif=Module["dynCall_viffffiifffiiiiif"]=function(){return(dynCall_viffffiifffiiiiif=Module["dynCall_viffffiifffiiiiif"]=Module["asm"]["Hq"]).apply(null,arguments)};var dynCall_iiiifffffii=Module["dynCall_iiiifffffii"]=function(){return(dynCall_iiiifffffii=Module["dynCall_iiiifffffii"]=Module["asm"]["Iq"]).apply(null,arguments)};var dynCall_viiiiiiiiiiifii=Module["dynCall_viiiiiiiiiiifii"]=function(){return(dynCall_viiiiiiiiiiifii=Module["dynCall_viiiiiiiiiiifii"]=Module["asm"]["Jq"]).apply(null,arguments)};var dynCall_viff=Module["dynCall_viff"]=function(){return(dynCall_viff=Module["dynCall_viff"]=Module["asm"]["Kq"]).apply(null,arguments)};var dynCall_iiiiifiiiiif=Module["dynCall_iiiiifiiiiif"]=function(){return(dynCall_iiiiifiiiiif=Module["dynCall_iiiiifiiiiif"]=Module["asm"]["Lq"]).apply(null,arguments)};var dynCall_viiifiiiii=Module["dynCall_viiifiiiii"]=function(){return(dynCall_viiifiiiii=Module["dynCall_viiifiiiii"]=Module["asm"]["Mq"]).apply(null,arguments)};var dynCall_viiiifiiiiif=Module["dynCall_viiiifiiiiif"]=function(){return(dynCall_viiiifiiiiif=Module["dynCall_viiiifiiiiif"]=Module["asm"]["Nq"]).apply(null,arguments)};var dynCall_iifff=Module["dynCall_iifff"]=function(){return(dynCall_iifff=Module["dynCall_iifff"]=Module["asm"]["Oq"]).apply(null,arguments)};var dynCall_iif=Module["dynCall_iif"]=function(){return(dynCall_iif=Module["dynCall_iif"]=Module["asm"]["Pq"]).apply(null,arguments)};var dynCall_viijijj=Module["dynCall_viijijj"]=function(){return(dynCall_viijijj=Module["dynCall_viijijj"]=Module["asm"]["Qq"]).apply(null,arguments)};var dynCall_viijj=Module["dynCall_viijj"]=function(){return(dynCall_viijj=Module["dynCall_viijj"]=Module["asm"]["Rq"]).apply(null,arguments)};var dynCall_viiiij=Module["dynCall_viiiij"]=function(){return(dynCall_viiiij=Module["dynCall_viiiij"]=Module["asm"]["Sq"]).apply(null,arguments)};var dynCall_iiiiiifffiiifiii=Module["dynCall_iiiiiifffiiifiii"]=function(){return(dynCall_iiiiiifffiiifiii=Module["dynCall_iiiiiifffiiifiii"]=Module["asm"]["Tq"]).apply(null,arguments)};var dynCall_viid=Module["dynCall_viid"]=function(){return(dynCall_viid=Module["dynCall_viid"]=Module["asm"]["Uq"]).apply(null,arguments)};var dynCall_fiiiif=Module["dynCall_fiiiif"]=function(){return(dynCall_fiiiif=Module["dynCall_fiiiif"]=Module["asm"]["Vq"]).apply(null,arguments)};var dynCall_iiiiiff=Module["dynCall_iiiiiff"]=function(){return(dynCall_iiiiiff=Module["dynCall_iiiiiff"]=Module["asm"]["Wq"]).apply(null,arguments)};var dynCall_viffff=Module["dynCall_viffff"]=function(){return(dynCall_viffff=Module["dynCall_viffff"]=Module["asm"]["Xq"]).apply(null,arguments)};var dynCall_vf=Module["dynCall_vf"]=function(){return(dynCall_vf=Module["dynCall_vf"]=Module["asm"]["Yq"]).apply(null,arguments)};var dynCall_vffff=Module["dynCall_vffff"]=function(){return(dynCall_vffff=Module["dynCall_vffff"]=Module["asm"]["Zq"]).apply(null,arguments)};var dynCall_vff=Module["dynCall_vff"]=function(){return(dynCall_vff=Module["dynCall_vff"]=Module["asm"]["_q"]).apply(null,arguments)};var dynCall_vifff=Module["dynCall_vifff"]=function(){return(dynCall_vifff=Module["dynCall_vifff"]=Module["asm"]["$q"]).apply(null,arguments)};var dynCall_viifff=Module["dynCall_viifff"]=function(){return(dynCall_viifff=Module["dynCall_viifff"]=Module["asm"]["ar"]).apply(null,arguments)};var dynCall_vij=Module["dynCall_vij"]=function(){return(dynCall_vij=Module["dynCall_vij"]=Module["asm"]["br"]).apply(null,arguments)};var dynCall_vfff=Module["dynCall_vfff"]=function(){return(dynCall_vfff=Module["dynCall_vfff"]=Module["asm"]["cr"]).apply(null,arguments)};var dynCall_iiff=Module["dynCall_iiff"]=function(){return(dynCall_iiff=Module["dynCall_iiff"]=Module["asm"]["dr"]).apply(null,arguments)};var dynCall_f=Module["dynCall_f"]=function(){return(dynCall_f=Module["dynCall_f"]=Module["asm"]["er"]).apply(null,arguments)};var dynCall_vffffffi=Module["dynCall_vffffffi"]=function(){return(dynCall_vffffffi=Module["dynCall_vffffffi"]=Module["asm"]["fr"]).apply(null,arguments)};var dynCall_ff=Module["dynCall_ff"]=function(){return(dynCall_ff=Module["dynCall_ff"]=Module["asm"]["gr"]).apply(null,arguments)};var dynCall_if=Module["dynCall_if"]=function(){return(dynCall_if=Module["dynCall_if"]=Module["asm"]["hr"]).apply(null,arguments)};var dynCall_iiiiiiifiii=Module["dynCall_iiiiiiifiii"]=function(){return(dynCall_iiiiiiifiii=Module["dynCall_iiiiiiifiii"]=Module["asm"]["ir"]).apply(null,arguments)};var dynCall_iiifiifii=Module["dynCall_iiifiifii"]=function(){return(dynCall_iiifiifii=Module["dynCall_iiifiifii"]=Module["asm"]["jr"]).apply(null,arguments)};var dynCall_fiif=Module["dynCall_fiif"]=function(){return(dynCall_fiif=Module["dynCall_fiif"]=Module["asm"]["kr"]).apply(null,arguments)};var dynCall_iiiiiiffiiiiiiiiiffffiii=Module["dynCall_iiiiiiffiiiiiiiiiffffiii"]=function(){return(dynCall_iiiiiiffiiiiiiiiiffffiii=Module["dynCall_iiiiiiffiiiiiiiiiffffiii"]=Module["asm"]["lr"]).apply(null,arguments)};var dynCall_viififi=Module["dynCall_viififi"]=function(){return(dynCall_viififi=Module["dynCall_viififi"]=Module["asm"]["mr"]).apply(null,arguments)};var dynCall_viiiiiiiijiii=Module["dynCall_viiiiiiiijiii"]=function(){return(dynCall_viiiiiiiijiii=Module["dynCall_viiiiiiiijiii"]=Module["asm"]["nr"]).apply(null,arguments)};var dynCall_d=Module["dynCall_d"]=function(){return(dynCall_d=Module["dynCall_d"]=Module["asm"]["or"]).apply(null,arguments)};function invoke_iii(index,a1,a2){var sp=stackSave();try{return dynCall_iii(index,a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_iiiiii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vii(index,a1,a2){var sp=stackSave();try{dynCall_vii(index,a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{dynCall_viii(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return dynCall_iiii(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiii(index,a1,a2,a3,a4){var sp=stackSave();try{dynCall_viiii(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_iiiii(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fiii(index,a1,a2,a3){var sp=stackSave();try{return dynCall_fiii(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_diii(index,a1,a2,a3){var sp=stackSave();try{return dynCall_diii(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viif(index,a1,a2,a3){var sp=stackSave();try{dynCall_viif(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vi(index,a1){var sp=stackSave();try{dynCall_vi(index,a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_ii(index,a1){var sp=stackSave();try{return dynCall_ii(index,a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_v(index){var sp=stackSave();try{dynCall_v(index)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_i(index){var sp=stackSave();try{return dynCall_i(index)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{return dynCall_iiiiiiii(index,a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_viiiii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return dynCall_iiiiiii(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{return dynCall_iiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12){var sp=stackSave();try{return dynCall_iiiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{dynCall_viiiiiii(index,a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{dynCall_viiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_viiiiii(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8){var sp=stackSave();try{return dynCall_iiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8){var sp=stackSave();try{dynCall_viiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiifiifiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14){var sp=stackSave();try{dynCall_viiiiiiifiifiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viifi(index,a1,a2,a3,a4){var sp=stackSave();try{dynCall_viifi(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vifi(index,a1,a2,a3){var sp=stackSave();try{dynCall_vifi(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiddi(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_viiddi(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viffffi(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_viffffi(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_dddi(index,a1,a2,a3){var sp=stackSave();try{return dynCall_dddi(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fii(index,a1,a2){var sp=stackSave();try{return dynCall_fii(index,a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiffi(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_viiffi(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viffi(index,a1,a2,a3,a4){var sp=stackSave();try{dynCall_viffi(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiifi(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_viiifi(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_ffi(index,a1,a2){var sp=stackSave();try{return dynCall_ffi(index,a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{dynCall_viiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{dynCall_viiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiiifiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{return dynCall_iiiiiiiifiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiifi(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{dynCall_viiiiifi(index,a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiffi(index,a1,a2,a3,a4,a5,a6,a7,a8){var sp=stackSave();try{dynCall_viiiiiffi(index,a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiifiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{return dynCall_iiiiifiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viidii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_viidii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vidiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_vidiii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_dii(index,a1,a2){var sp=stackSave();try{return dynCall_dii(index,a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_fiiii(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fi(index,a1){var sp=stackSave();try{return dynCall_fi(index,a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viifiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8){var sp=stackSave();try{dynCall_viifiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iifii(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_iifii(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vfi(index,a1,a2){var sp=stackSave();try{dynCall_vfi(index,a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12){var sp=stackSave();try{dynCall_viiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fffi(index,a1,a2,a3){var sp=stackSave();try{return dynCall_fffi(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viifffi(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_viifffi(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiifddfiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14){var sp=stackSave();try{dynCall_viiiiiiifddfiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiffffiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14){var sp=stackSave();try{dynCall_viiiiiiiffffiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiff(index,a1,a2,a3,a4){var sp=stackSave();try{dynCall_viiff(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiifi(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_iiifi(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiifi(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_viiiifi(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiifi(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{dynCall_viiiiiiiiifi(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiidi(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_viiiidi(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vidi(index,a1,a2,a3){var sp=stackSave();try{dynCall_vidi(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiidii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{return dynCall_iiiiiiidii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13){var sp=stackSave();try{dynCall_viiiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viifffffi(index,a1,a2,a3,a4,a5,a6,a7,a8){var sp=stackSave();try{dynCall_viifffffi(index,a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fifi(index,a1,a2,a3){var sp=stackSave();try{return dynCall_fifi(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiifffiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{dynCall_viiiiifffiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_fiiiii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiif(index,a1,a2,a3,a4){var sp=stackSave();try{dynCall_viiif(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_diiid(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_diiid(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_fiiif(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_fiiif(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_di(index,a1){var sp=stackSave();try{return dynCall_di(index,a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiifii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_iiifii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iifi(index,a1,a2,a3){var sp=stackSave();try{return dynCall_iifi(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{return dynCall_iiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_jiiii(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiij(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_iiij(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_j(index){var sp=stackSave();try{return dynCall_j(index)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iij(index,a1,a2,a3){var sp=stackSave();try{return dynCall_iij(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiijiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{return dynCall_iiijiii(index,a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jii(index,a1,a2){var sp=stackSave();try{return dynCall_jii(index,a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_ji(index,a1){var sp=stackSave();try{return dynCall_ji(index,a1)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viijii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_viijii(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jiii(index,a1,a2,a3){var sp=stackSave();try{return dynCall_jiii(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiji(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_iiji(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiji(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_viiji(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{return dynCall_jiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiji(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{return dynCall_iiiiiiiiiji(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vijii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_vijii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jdi(index,a1,a2){var sp=stackSave();try{return dynCall_jdi(index,a1,a2)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_ijji(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_ijji(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_dji(index,a1,a2,a3){var sp=stackSave();try{return dynCall_dji(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viji(index,a1,a2,a3,a4){var sp=stackSave();try{dynCall_viji(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiiiiifjjfiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16){var sp=stackSave();try{dynCall_viiiiiiifjjfiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vji(index,a1,a2,a3){var sp=stackSave();try{dynCall_vji(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiji(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_viiiji(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiij(index,a1,a2,a3,a4,a5){var sp=stackSave();try{dynCall_viiij(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viiiidij(index,a1,a2,a3,a4,a5,a6,a7,a8){var sp=stackSave();try{dynCall_viiiidij(index,a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jiiij(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_jiiij(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jiji(index,a1,a2,a3,a4){var sp=stackSave();try{return dynCall_jiji(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iijji(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return dynCall_iijji(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jijiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return dynCall_jijiii(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jiiji(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_jiiji(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viij(index,a1,a2,a3,a4){var sp=stackSave();try{dynCall_viij(index,a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jijj(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_jijj(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iijii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_iijii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vijiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{dynCall_vijiii(index,a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vjjjiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{dynCall_vjjjiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_vjiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{dynCall_vjiiiii(index,a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_viijiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{dynCall_viijiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iji(index,a1,a2,a3){var sp=stackSave();try{return dynCall_iji(index,a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jjji(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_jjji(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_jiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return dynCall_jiiiii(index,a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}function invoke_iiiijii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{return dynCall_iiiijii(index,a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(e!==e+0&&e!=="longjmp")throw e;_setThrew(1,0)}}Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["stackTrace"]=stackTrace;Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["stackTrace"]=stackTrace;var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}var calledMain=false;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function callMain(args){var entryFunction=Module["_main"];args=args||[];var argc=args.length+1;var argv=stackAlloc((argc+1)*4);HEAP32[argv>>2]=allocateUTF8OnStack(thisProgram);for(var i=1;i>2)+i]=allocateUTF8OnStack(args[i-1])}HEAP32[(argv>>2)+argc]=0;try{var ret=entryFunction(argc,argv);exit(ret,true)}catch(e){if(e instanceof ExitStatus){return}else if(e=="unwind"){return}else{var toLog=e;if(e&&typeof e==="object"&&e.stack){toLog=[e,e.stack]}err("exception thrown: "+toLog);quit_(1,e)}}finally{calledMain=true}}function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(shouldRunNow)callMain(args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;function exit(status,implicit){EXITSTATUS=status;if(implicit&&keepRuntimeAlive()&&status===0){return}if(keepRuntimeAlive()){}else{exitRuntime();if(Module["onExit"])Module["onExit"](status);ABORT=true}quit_(status,new ExitStatus(status))}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=true;if(Module["noInitialRun"])shouldRunNow=false;run(); - -} diff --git a/spaces/edugp/clip-spanish-demo/README.md b/spaces/edugp/clip-spanish-demo/README.md deleted file mode 100644 index a8a2e1a764b395b8810955d6c7d62fa0bc77bc60..0000000000000000000000000000000000000000 --- a/spaces/edugp/clip-spanish-demo/README.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Clip Spanish Demo -emoji: 📈 -colorFrom: purple -colorTo: pink -sdk: streamlit -app_file: app.py -pinned: false ---- - -# Configuration - -`title`: _string_ -Display title for the Space - -`emoji`: _string_ -Space emoji (emoji-only character allowed) - -`colorFrom`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`colorTo`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`sdk`: _string_ -Can be either `gradio` or `streamlit` - -`app_file`: _string_ -Path to your main application file (which contains either `gradio` or `streamlit` Python code). -Path is relative to the root of the repository. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/eldobbins/coral-spawning-detector/app.py b/spaces/eldobbins/coral-spawning-detector/app.py deleted file mode 100644 index 664a18df00fc13cb591568f767a9bbfec23a7bf8..0000000000000000000000000000000000000000 --- a/spaces/eldobbins/coral-spawning-detector/app.py +++ /dev/null @@ -1,29 +0,0 @@ -import gradio -from fastai.vision.all import * -import skimage - -learn = load_learner('sample-resnet34.pkl') - -labels = learn.dls.vocab -def predict(img): - img = PILImage.create(img) - pred,pred_idx,probs = learn.predict(img) - return {labels[i]: float(probs[i]) for i in range(len(labels))} - -gradio.Interface( - fn=predict, - inputs=gradio.inputs.Image(shape=(512, 512)), - outputs=gradio.outputs.Label(num_top_classes=3), - title="Is the coral spawning?", - description="This model was trained with images of spawning and non-spawning coral. Does it know its business?.", - examples= - [ - 'images/sample-data_negative-01.png', - 'images/sample-data_positive-01.png', - 'images/sample-data_positive-02.png', - 'images/clean_aquarium_camera.jpg' - ], - interpretation='default', - enable_queue=True -).launch() - diff --git a/spaces/emc348/faces-through-time/dnnlib/util.py b/spaces/emc348/faces-through-time/dnnlib/util.py deleted file mode 100644 index 76725336d01e75e1c68daa88be47f4fde0bbc63b..0000000000000000000000000000000000000000 --- a/spaces/emc348/faces-through-time/dnnlib/util.py +++ /dev/null @@ -1,477 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - -"""Miscellaneous utility classes and functions.""" - -import ctypes -import fnmatch -import importlib -import inspect -import numpy as np -import os -import shutil -import sys -import types -import io -import pickle -import re -import requests -import html -import hashlib -import glob -import tempfile -import urllib -import urllib.request -import uuid - -from distutils.util import strtobool -from typing import Any, List, Tuple, Union - - -# Util classes -# ------------------------------------------------------------------------------------------ - - -class EasyDict(dict): - """Convenience class that behaves like a dict but allows access with the attribute syntax.""" - - def __getattr__(self, name: str) -> Any: - try: - return self[name] - except KeyError: - raise AttributeError(name) - - def __setattr__(self, name: str, value: Any) -> None: - self[name] = value - - def __delattr__(self, name: str) -> None: - del self[name] - - -class Logger(object): - """Redirect stderr to stdout, optionally print stdout to a file, and optionally force flushing on both stdout and the file.""" - - def __init__(self, file_name: str = None, file_mode: str = "w", should_flush: bool = True): - self.file = None - - if file_name is not None: - self.file = open(file_name, file_mode) - - self.should_flush = should_flush - self.stdout = sys.stdout - self.stderr = sys.stderr - - sys.stdout = self - sys.stderr = self - - def __enter__(self) -> "Logger": - return self - - def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: - self.close() - - def write(self, text: Union[str, bytes]) -> None: - """Write text to stdout (and a file) and optionally flush.""" - if isinstance(text, bytes): - text = text.decode() - if len(text) == 0: # workaround for a bug in VSCode debugger: sys.stdout.write(''); sys.stdout.flush() => crash - return - - if self.file is not None: - self.file.write(text) - - self.stdout.write(text) - - if self.should_flush: - self.flush() - - def flush(self) -> None: - """Flush written text to both stdout and a file, if open.""" - if self.file is not None: - self.file.flush() - - self.stdout.flush() - - def close(self) -> None: - """Flush, close possible files, and remove stdout/stderr mirroring.""" - self.flush() - - # if using multiple loggers, prevent closing in wrong order - if sys.stdout is self: - sys.stdout = self.stdout - if sys.stderr is self: - sys.stderr = self.stderr - - if self.file is not None: - self.file.close() - self.file = None - - -# Cache directories -# ------------------------------------------------------------------------------------------ - -_dnnlib_cache_dir = None - -def set_cache_dir(path: str) -> None: - global _dnnlib_cache_dir - _dnnlib_cache_dir = path - -def make_cache_dir_path(*paths: str) -> str: - if _dnnlib_cache_dir is not None: - return os.path.join(_dnnlib_cache_dir, *paths) - if 'DNNLIB_CACHE_DIR' in os.environ: - return os.path.join(os.environ['DNNLIB_CACHE_DIR'], *paths) - if 'HOME' in os.environ: - return os.path.join(os.environ['HOME'], '.cache', 'dnnlib', *paths) - if 'USERPROFILE' in os.environ: - return os.path.join(os.environ['USERPROFILE'], '.cache', 'dnnlib', *paths) - return os.path.join(tempfile.gettempdir(), '.cache', 'dnnlib', *paths) - -# Small util functions -# ------------------------------------------------------------------------------------------ - - -def format_time(seconds: Union[int, float]) -> str: - """Convert the seconds to human readable string with days, hours, minutes and seconds.""" - s = int(np.rint(seconds)) - - if s < 60: - return "{0}s".format(s) - elif s < 60 * 60: - return "{0}m {1:02}s".format(s // 60, s % 60) - elif s < 24 * 60 * 60: - return "{0}h {1:02}m {2:02}s".format(s // (60 * 60), (s // 60) % 60, s % 60) - else: - return "{0}d {1:02}h {2:02}m".format(s // (24 * 60 * 60), (s // (60 * 60)) % 24, (s // 60) % 60) - - -def ask_yes_no(question: str) -> bool: - """Ask the user the question until the user inputs a valid answer.""" - while True: - try: - print("{0} [y/n]".format(question)) - return strtobool(input().lower()) - except ValueError: - pass - - -def tuple_product(t: Tuple) -> Any: - """Calculate the product of the tuple elements.""" - result = 1 - - for v in t: - result *= v - - return result - - -_str_to_ctype = { - "uint8": ctypes.c_ubyte, - "uint16": ctypes.c_uint16, - "uint32": ctypes.c_uint32, - "uint64": ctypes.c_uint64, - "int8": ctypes.c_byte, - "int16": ctypes.c_int16, - "int32": ctypes.c_int32, - "int64": ctypes.c_int64, - "float32": ctypes.c_float, - "float64": ctypes.c_double -} - - -def get_dtype_and_ctype(type_obj: Any) -> Tuple[np.dtype, Any]: - """Given a type name string (or an object having a __name__ attribute), return matching Numpy and ctypes types that have the same size in bytes.""" - type_str = None - - if isinstance(type_obj, str): - type_str = type_obj - elif hasattr(type_obj, "__name__"): - type_str = type_obj.__name__ - elif hasattr(type_obj, "name"): - type_str = type_obj.name - else: - raise RuntimeError("Cannot infer type name from input") - - assert type_str in _str_to_ctype.keys() - - my_dtype = np.dtype(type_str) - my_ctype = _str_to_ctype[type_str] - - assert my_dtype.itemsize == ctypes.sizeof(my_ctype) - - return my_dtype, my_ctype - - -def is_pickleable(obj: Any) -> bool: - try: - with io.BytesIO() as stream: - pickle.dump(obj, stream) - return True - except: - return False - - -# Functionality to import modules/objects by name, and call functions by name -# ------------------------------------------------------------------------------------------ - -def get_module_from_obj_name(obj_name: str) -> Tuple[types.ModuleType, str]: - """Searches for the underlying module behind the name to some python object. - Returns the module and the object name (original name with module part removed).""" - - # allow convenience shorthands, substitute them by full names - obj_name = re.sub("^np.", "numpy.", obj_name) - obj_name = re.sub("^tf.", "tensorflow.", obj_name) - - # list alternatives for (module_name, local_obj_name) - parts = obj_name.split(".") - name_pairs = [(".".join(parts[:i]), ".".join(parts[i:])) for i in range(len(parts), 0, -1)] - - # try each alternative in turn - for module_name, local_obj_name in name_pairs: - try: - module = importlib.import_module(module_name) # may raise ImportError - get_obj_from_module(module, local_obj_name) # may raise AttributeError - return module, local_obj_name - except: - pass - - # maybe some of the modules themselves contain errors? - for module_name, _local_obj_name in name_pairs: - try: - importlib.import_module(module_name) # may raise ImportError - except ImportError: - if not str(sys.exc_info()[1]).startswith("No module named '" + module_name + "'"): - raise - - # maybe the requested attribute is missing? - for module_name, local_obj_name in name_pairs: - try: - module = importlib.import_module(module_name) # may raise ImportError - get_obj_from_module(module, local_obj_name) # may raise AttributeError - except ImportError: - pass - - # we are out of luck, but we have no idea why - raise ImportError(obj_name) - - -def get_obj_from_module(module: types.ModuleType, obj_name: str) -> Any: - """Traverses the object name and returns the last (rightmost) python object.""" - if obj_name == '': - return module - obj = module - for part in obj_name.split("."): - obj = getattr(obj, part) - return obj - - -def get_obj_by_name(name: str) -> Any: - """Finds the python object with the given name.""" - module, obj_name = get_module_from_obj_name(name) - return get_obj_from_module(module, obj_name) - - -def call_func_by_name(*args, func_name: str = None, **kwargs) -> Any: - """Finds the python object with the given name and calls it as a function.""" - assert func_name is not None - func_obj = get_obj_by_name(func_name) - assert callable(func_obj) - return func_obj(*args, **kwargs) - - -def construct_class_by_name(*args, class_name: str = None, **kwargs) -> Any: - """Finds the python class with the given name and constructs it with the given arguments.""" - return call_func_by_name(*args, func_name=class_name, **kwargs) - - -def get_module_dir_by_obj_name(obj_name: str) -> str: - """Get the directory path of the module containing the given object name.""" - module, _ = get_module_from_obj_name(obj_name) - return os.path.dirname(inspect.getfile(module)) - - -def is_top_level_function(obj: Any) -> bool: - """Determine whether the given object is a top-level function, i.e., defined at module scope using 'def'.""" - return callable(obj) and obj.__name__ in sys.modules[obj.__module__].__dict__ - - -def get_top_level_function_name(obj: Any) -> str: - """Return the fully-qualified name of a top-level function.""" - assert is_top_level_function(obj) - module = obj.__module__ - if module == '__main__': - module = os.path.splitext(os.path.basename(sys.modules[module].__file__))[0] - return module + "." + obj.__name__ - - -# File system helpers -# ------------------------------------------------------------------------------------------ - -def list_dir_recursively_with_ignore(dir_path: str, ignores: List[str] = None, add_base_to_relative: bool = False) -> List[Tuple[str, str]]: - """List all files recursively in a given directory while ignoring given file and directory names. - Returns list of tuples containing both absolute and relative paths.""" - assert os.path.isdir(dir_path) - base_name = os.path.basename(os.path.normpath(dir_path)) - - if ignores is None: - ignores = [] - - result = [] - - for root, dirs, files in os.walk(dir_path, topdown=True): - for ignore_ in ignores: - dirs_to_remove = [d for d in dirs if fnmatch.fnmatch(d, ignore_)] - - # dirs need to be edited in-place - for d in dirs_to_remove: - dirs.remove(d) - - files = [f for f in files if not fnmatch.fnmatch(f, ignore_)] - - absolute_paths = [os.path.join(root, f) for f in files] - relative_paths = [os.path.relpath(p, dir_path) for p in absolute_paths] - - if add_base_to_relative: - relative_paths = [os.path.join(base_name, p) for p in relative_paths] - - assert len(absolute_paths) == len(relative_paths) - result += zip(absolute_paths, relative_paths) - - return result - - -def copy_files_and_create_dirs(files: List[Tuple[str, str]]) -> None: - """Takes in a list of tuples of (src, dst) paths and copies files. - Will create all necessary directories.""" - for file in files: - target_dir_name = os.path.dirname(file[1]) - - # will create all intermediate-level directories - if not os.path.exists(target_dir_name): - os.makedirs(target_dir_name) - - shutil.copyfile(file[0], file[1]) - - -# URL helpers -# ------------------------------------------------------------------------------------------ - -def is_url(obj: Any, allow_file_urls: bool = False) -> bool: - """Determine whether the given object is a valid URL string.""" - if not isinstance(obj, str) or not "://" in obj: - return False - if allow_file_urls and obj.startswith('file://'): - return True - try: - res = requests.compat.urlparse(obj) - if not res.scheme or not res.netloc or not "." in res.netloc: - return False - res = requests.compat.urlparse(requests.compat.urljoin(obj, "/")) - if not res.scheme or not res.netloc or not "." in res.netloc: - return False - except: - return False - return True - - -def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: bool = True, return_filename: bool = False, cache: bool = True) -> Any: - """Download the given URL and return a binary-mode file object to access the data.""" - assert num_attempts >= 1 - assert not (return_filename and (not cache)) - - # Doesn't look like an URL scheme so interpret it as a local filename. - if not re.match('^[a-z]+://', url): - return url if return_filename else open(url, "rb") - - # Handle file URLs. This code handles unusual file:// patterns that - # arise on Windows: - # - # file:///c:/foo.txt - # - # which would translate to a local '/c:/foo.txt' filename that's - # invalid. Drop the forward slash for such pathnames. - # - # If you touch this code path, you should test it on both Linux and - # Windows. - # - # Some internet resources suggest using urllib.request.url2pathname() but - # but that converts forward slashes to backslashes and this causes - # its own set of problems. - if url.startswith('file://'): - filename = urllib.parse.urlparse(url).path - if re.match(r'^/[a-zA-Z]:', filename): - filename = filename[1:] - return filename if return_filename else open(filename, "rb") - - assert is_url(url) - - # Lookup from cache. - if cache_dir is None: - cache_dir = make_cache_dir_path('downloads') - - url_md5 = hashlib.md5(url.encode("utf-8")).hexdigest() - if cache: - cache_files = glob.glob(os.path.join(cache_dir, url_md5 + "_*")) - if len(cache_files) == 1: - filename = cache_files[0] - return filename if return_filename else open(filename, "rb") - - # Download. - url_name = None - url_data = None - with requests.Session() as session: - if verbose: - print("Downloading %s ..." % url, end="", flush=True) - for attempts_left in reversed(range(num_attempts)): - try: - with session.get(url) as res: - res.raise_for_status() - if len(res.content) == 0: - raise IOError("No data received") - - if len(res.content) < 8192: - content_str = res.content.decode("utf-8") - if "download_warning" in res.headers.get("Set-Cookie", ""): - links = [html.unescape(link) for link in content_str.split('"') if "export=download" in link] - if len(links) == 1: - url = requests.compat.urljoin(url, links[0]) - raise IOError("Google Drive virus checker nag") - if "Google Drive - Quota exceeded" in content_str: - raise IOError("Google Drive download quota exceeded -- please try again later") - - match = re.search(r'filename="([^"]*)"', res.headers.get("Content-Disposition", "")) - url_name = match[1] if match else url - url_data = res.content - if verbose: - print(" done") - break - except KeyboardInterrupt: - raise - except: - if not attempts_left: - if verbose: - print(" failed") - raise - if verbose: - print(".", end="", flush=True) - - # Save to cache. - if cache: - safe_name = re.sub(r"[^0-9a-zA-Z-._]", "_", url_name) - cache_file = os.path.join(cache_dir, url_md5 + "_" + safe_name) - temp_file = os.path.join(cache_dir, "tmp_" + uuid.uuid4().hex + "_" + url_md5 + "_" + safe_name) - os.makedirs(cache_dir, exist_ok=True) - with open(temp_file, "wb") as f: - f.write(url_data) - os.replace(temp_file, cache_file) # atomic - if return_filename: - return cache_file - - # Return data as file object. - assert not return_filename - return io.BytesIO(url_data) diff --git a/spaces/erbanku/gpt-academic/crazy_functions/crazy_utils.py b/spaces/erbanku/gpt-academic/crazy_functions/crazy_utils.py deleted file mode 100644 index e54136c441e7d713b0e8f5a66de9fb8bae1b1f4c..0000000000000000000000000000000000000000 --- a/spaces/erbanku/gpt-academic/crazy_functions/crazy_utils.py +++ /dev/null @@ -1,608 +0,0 @@ -from toolbox import update_ui, get_conf, trimmed_format_exc - -def input_clipping(inputs, history, max_token_limit): - import numpy as np - from request_llm.bridge_all import model_info - enc = model_info["gpt-3.5-turbo"]['tokenizer'] - def get_token_num(txt): return len(enc.encode(txt, disallowed_special=())) - - mode = 'input-and-history' - # 当 输入部分的token占比 小于 全文的一半时,只裁剪历史 - input_token_num = get_token_num(inputs) - if input_token_num < max_token_limit//2: - mode = 'only-history' - max_token_limit = max_token_limit - input_token_num - - everything = [inputs] if mode == 'input-and-history' else [''] - everything.extend(history) - n_token = get_token_num('\n'.join(everything)) - everything_token = [get_token_num(e) for e in everything] - delta = max(everything_token) // 16 # 截断时的颗粒度 - - while n_token > max_token_limit: - where = np.argmax(everything_token) - encoded = enc.encode(everything[where], disallowed_special=()) - clipped_encoded = encoded[:len(encoded)-delta] - everything[where] = enc.decode(clipped_encoded)[:-1] # -1 to remove the may-be illegal char - everything_token[where] = get_token_num(everything[where]) - n_token = get_token_num('\n'.join(everything)) - - if mode == 'input-and-history': - inputs = everything[0] - else: - pass - history = everything[1:] - return inputs, history - -def request_gpt_model_in_new_thread_with_ui_alive( - inputs, inputs_show_user, llm_kwargs, - chatbot, history, sys_prompt, refresh_interval=0.2, - handle_token_exceed=True, - retry_times_at_unknown_error=2, - ): - """ - Request GPT model,请求GPT模型同时维持用户界面活跃。 - - 输入参数 Args (以_array结尾的输入变量都是列表,列表长度为子任务的数量,执行时,会把列表拆解,放到每个子线程中分别执行): - inputs (string): List of inputs (输入) - inputs_show_user (string): List of inputs to show user(展现在报告中的输入,借助此参数,在汇总报告中隐藏啰嗦的真实输入,增强报告的可读性) - top_p (float): Top p value for sampling from model distribution (GPT参数,浮点数) - temperature (float): Temperature value for sampling from model distribution(GPT参数,浮点数) - chatbot: chatbot inputs and outputs (用户界面对话窗口句柄,用于数据流可视化) - history (list): List of chat history (历史,对话历史列表) - sys_prompt (string): List of system prompts (系统输入,列表,用于输入给GPT的前提提示,比如你是翻译官怎样怎样) - refresh_interval (float, optional): Refresh interval for UI (default: 0.2) (刷新时间间隔频率,建议低于1,不可高于3,仅仅服务于视觉效果) - handle_token_exceed:是否自动处理token溢出的情况,如果选择自动处理,则会在溢出时暴力截断,默认开启 - retry_times_at_unknown_error:失败时的重试次数 - - 输出 Returns: - future: 输出,GPT返回的结果 - """ - import time - from concurrent.futures import ThreadPoolExecutor - from request_llm.bridge_all import predict_no_ui_long_connection - # 用户反馈 - chatbot.append([inputs_show_user, ""]) - yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 - executor = ThreadPoolExecutor(max_workers=16) - mutable = ["", time.time(), ""] - def _req_gpt(inputs, history, sys_prompt): - retry_op = retry_times_at_unknown_error - exceeded_cnt = 0 - while True: - # watchdog error - if len(mutable) >= 2 and (time.time()-mutable[1]) > 5: - raise RuntimeError("检测到程序终止。") - try: - # 【第一种情况】:顺利完成 - result = predict_no_ui_long_connection( - inputs=inputs, llm_kwargs=llm_kwargs, - history=history, sys_prompt=sys_prompt, observe_window=mutable) - return result - except ConnectionAbortedError as token_exceeded_error: - # 【第二种情况】:Token溢出 - if handle_token_exceed: - exceeded_cnt += 1 - # 【选择处理】 尝试计算比例,尽可能多地保留文本 - from toolbox import get_reduce_token_percent - p_ratio, n_exceed = get_reduce_token_percent(str(token_exceeded_error)) - MAX_TOKEN = 4096 - EXCEED_ALLO = 512 + 512 * exceeded_cnt - inputs, history = input_clipping(inputs, history, max_token_limit=MAX_TOKEN-EXCEED_ALLO) - mutable[0] += f'[Local Message] 警告,文本过长将进行截断,Token溢出数:{n_exceed}。\n\n' - continue # 返回重试 - else: - # 【选择放弃】 - tb_str = '```\n' + trimmed_format_exc() + '```' - mutable[0] += f"[Local Message] 警告,在执行过程中遭遇问题, Traceback:\n\n{tb_str}\n\n" - return mutable[0] # 放弃 - except: - # 【第三种情况】:其他错误:重试几次 - tb_str = '```\n' + trimmed_format_exc() + '```' - print(tb_str) - mutable[0] += f"[Local Message] 警告,在执行过程中遭遇问题, Traceback:\n\n{tb_str}\n\n" - if retry_op > 0: - retry_op -= 1 - mutable[0] += f"[Local Message] 重试中,请稍等 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}:\n\n" - if ("Rate limit reached" in tb_str) or ("Too Many Requests" in tb_str): - time.sleep(30) - time.sleep(5) - continue # 返回重试 - else: - time.sleep(5) - return mutable[0] # 放弃 - - # 提交任务 - future = executor.submit(_req_gpt, inputs, history, sys_prompt) - while True: - # yield一次以刷新前端页面 - time.sleep(refresh_interval) - # “喂狗”(看门狗) - mutable[1] = time.time() - if future.done(): - break - chatbot[-1] = [chatbot[-1][0], mutable[0]] - yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 - - final_result = future.result() - chatbot[-1] = [chatbot[-1][0], final_result] - yield from update_ui(chatbot=chatbot, history=[]) # 如果最后成功了,则删除报错信息 - return final_result - - -def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( - inputs_array, inputs_show_user_array, llm_kwargs, - chatbot, history_array, sys_prompt_array, - refresh_interval=0.2, max_workers=-1, scroller_max_len=30, - handle_token_exceed=True, show_user_at_complete=False, - retry_times_at_unknown_error=2, - ): - """ - Request GPT model using multiple threads with UI and high efficiency - 请求GPT模型的[多线程]版。 - 具备以下功能: - 实时在UI上反馈远程数据流 - 使用线程池,可调节线程池的大小避免openai的流量限制错误 - 处理中途中止的情况 - 网络等出问题时,会把traceback和已经接收的数据转入输出 - - 输入参数 Args (以_array结尾的输入变量都是列表,列表长度为子任务的数量,执行时,会把列表拆解,放到每个子线程中分别执行): - inputs_array (list): List of inputs (每个子任务的输入) - inputs_show_user_array (list): List of inputs to show user(每个子任务展现在报告中的输入,借助此参数,在汇总报告中隐藏啰嗦的真实输入,增强报告的可读性) - llm_kwargs: llm_kwargs参数 - chatbot: chatbot (用户界面对话窗口句柄,用于数据流可视化) - history_array (list): List of chat history (历史对话输入,双层列表,第一层列表是子任务分解,第二层列表是对话历史) - sys_prompt_array (list): List of system prompts (系统输入,列表,用于输入给GPT的前提提示,比如你是翻译官怎样怎样) - refresh_interval (float, optional): Refresh interval for UI (default: 0.2) (刷新时间间隔频率,建议低于1,不可高于3,仅仅服务于视觉效果) - max_workers (int, optional): Maximum number of threads (default: see config.py) (最大线程数,如果子任务非常多,需要用此选项防止高频地请求openai导致错误) - scroller_max_len (int, optional): Maximum length for scroller (default: 30)(数据流的显示最后收到的多少个字符,仅仅服务于视觉效果) - handle_token_exceed (bool, optional): (是否在输入过长时,自动缩减文本) - handle_token_exceed:是否自动处理token溢出的情况,如果选择自动处理,则会在溢出时暴力截断,默认开启 - show_user_at_complete (bool, optional): (在结束时,把完整输入-输出结果显示在聊天框) - retry_times_at_unknown_error:子任务失败时的重试次数 - - 输出 Returns: - list: List of GPT model responses (每个子任务的输出汇总,如果某个子任务出错,response中会携带traceback报错信息,方便调试和定位问题。) - """ - import time, random - from concurrent.futures import ThreadPoolExecutor - from request_llm.bridge_all import predict_no_ui_long_connection - assert len(inputs_array) == len(history_array) - assert len(inputs_array) == len(sys_prompt_array) - if max_workers == -1: # 读取配置文件 - try: max_workers, = get_conf('DEFAULT_WORKER_NUM') - except: max_workers = 8 - if max_workers <= 0: max_workers = 3 - # 屏蔽掉 chatglm的多线程,可能会导致严重卡顿 - if not (llm_kwargs['llm_model'].startswith('gpt-') or llm_kwargs['llm_model'].startswith('api2d-')): - max_workers = 1 - - executor = ThreadPoolExecutor(max_workers=max_workers) - n_frag = len(inputs_array) - # 用户反馈 - chatbot.append(["请开始多线程操作。", ""]) - yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 - # 跨线程传递 - mutable = [["", time.time(), "等待中"] for _ in range(n_frag)] - - # 子线程任务 - def _req_gpt(index, inputs, history, sys_prompt): - gpt_say = "" - retry_op = retry_times_at_unknown_error - exceeded_cnt = 0 - mutable[index][2] = "执行中" - while True: - # watchdog error - if len(mutable[index]) >= 2 and (time.time()-mutable[index][1]) > 5: - raise RuntimeError("检测到程序终止。") - try: - # 【第一种情况】:顺利完成 - # time.sleep(10); raise RuntimeError("测试") - gpt_say = predict_no_ui_long_connection( - inputs=inputs, llm_kwargs=llm_kwargs, history=history, - sys_prompt=sys_prompt, observe_window=mutable[index], console_slience=True - ) - mutable[index][2] = "已成功" - return gpt_say - except ConnectionAbortedError as token_exceeded_error: - # 【第二种情况】:Token溢出, - if handle_token_exceed: - exceeded_cnt += 1 - # 【选择处理】 尝试计算比例,尽可能多地保留文本 - from toolbox import get_reduce_token_percent - p_ratio, n_exceed = get_reduce_token_percent(str(token_exceeded_error)) - MAX_TOKEN = 4096 - EXCEED_ALLO = 512 + 512 * exceeded_cnt - inputs, history = input_clipping(inputs, history, max_token_limit=MAX_TOKEN-EXCEED_ALLO) - gpt_say += f'[Local Message] 警告,文本过长将进行截断,Token溢出数:{n_exceed}。\n\n' - mutable[index][2] = f"截断重试" - continue # 返回重试 - else: - # 【选择放弃】 - tb_str = '```\n' + trimmed_format_exc() + '```' - gpt_say += f"[Local Message] 警告,线程{index}在执行过程中遭遇问题, Traceback:\n\n{tb_str}\n\n" - if len(mutable[index][0]) > 0: gpt_say += "此线程失败前收到的回答:\n\n" + mutable[index][0] - mutable[index][2] = "输入过长已放弃" - return gpt_say # 放弃 - except: - # 【第三种情况】:其他错误 - tb_str = '```\n' + trimmed_format_exc() + '```' - print(tb_str) - gpt_say += f"[Local Message] 警告,线程{index}在执行过程中遭遇问题, Traceback:\n\n{tb_str}\n\n" - if len(mutable[index][0]) > 0: gpt_say += "此线程失败前收到的回答:\n\n" + mutable[index][0] - if retry_op > 0: - retry_op -= 1 - wait = random.randint(5, 20) - if ("Rate limit reached" in tb_str) or ("Too Many Requests" in tb_str): - wait = wait * 3 - fail_info = "OpenAI绑定信用卡可解除频率限制 " - else: - fail_info = "" - # 也许等待十几秒后,情况会好转 - for i in range(wait): - mutable[index][2] = f"{fail_info}等待重试 {wait-i}"; time.sleep(1) - # 开始重试 - mutable[index][2] = f"重试中 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}" - continue # 返回重试 - else: - mutable[index][2] = "已失败" - wait = 5 - time.sleep(5) - return gpt_say # 放弃 - - # 异步任务开始 - futures = [executor.submit(_req_gpt, index, inputs, history, sys_prompt) for index, inputs, history, sys_prompt in zip( - range(len(inputs_array)), inputs_array, history_array, sys_prompt_array)] - cnt = 0 - while True: - # yield一次以刷新前端页面 - time.sleep(refresh_interval) - cnt += 1 - worker_done = [h.done() for h in futures] - if all(worker_done): - executor.shutdown() - break - # 更好的UI视觉效果 - observe_win = [] - # 每个线程都要“喂狗”(看门狗) - for thread_index, _ in enumerate(worker_done): - mutable[thread_index][1] = time.time() - # 在前端打印些好玩的东西 - for thread_index, _ in enumerate(worker_done): - print_something_really_funny = "[ ...`"+mutable[thread_index][0][-scroller_max_len:].\ - replace('\n', '').replace('```', '...').replace( - ' ', '.').replace('
    ', '.....').replace('$', '.')+"`... ]" - observe_win.append(print_something_really_funny) - # 在前端打印些好玩的东西 - stat_str = ''.join([f'`{mutable[thread_index][2]}`: {obs}\n\n' - if not done else f'`{mutable[thread_index][2]}`\n\n' - for thread_index, done, obs in zip(range(len(worker_done)), worker_done, observe_win)]) - # 在前端打印些好玩的东西 - chatbot[-1] = [chatbot[-1][0], f'多线程操作已经开始,完成情况: \n\n{stat_str}' + ''.join(['.']*(cnt % 10+1))] - yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 - - # 异步任务结束 - gpt_response_collection = [] - for inputs_show_user, f in zip(inputs_show_user_array, futures): - gpt_res = f.result() - gpt_response_collection.extend([inputs_show_user, gpt_res]) - - # 是否在结束时,在界面上显示结果 - if show_user_at_complete: - for inputs_show_user, f in zip(inputs_show_user_array, futures): - gpt_res = f.result() - chatbot.append([inputs_show_user, gpt_res]) - yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 - time.sleep(0.3) - return gpt_response_collection - - -def breakdown_txt_to_satisfy_token_limit(txt, get_token_fn, limit): - def cut(txt_tocut, must_break_at_empty_line): # 递归 - if get_token_fn(txt_tocut) <= limit: - return [txt_tocut] - else: - lines = txt_tocut.split('\n') - estimated_line_cut = limit / get_token_fn(txt_tocut) * len(lines) - estimated_line_cut = int(estimated_line_cut) - for cnt in reversed(range(estimated_line_cut)): - if must_break_at_empty_line: - if lines[cnt] != "": - continue - print(cnt) - prev = "\n".join(lines[:cnt]) - post = "\n".join(lines[cnt:]) - if get_token_fn(prev) < limit: - break - if cnt == 0: - raise RuntimeError("存在一行极长的文本!") - # print(len(post)) - # 列表递归接龙 - result = [prev] - result.extend(cut(post, must_break_at_empty_line)) - return result - try: - return cut(txt, must_break_at_empty_line=True) - except RuntimeError: - return cut(txt, must_break_at_empty_line=False) - - -def force_breakdown(txt, limit, get_token_fn): - """ - 当无法用标点、空行分割时,我们用最暴力的方法切割 - """ - for i in reversed(range(len(txt))): - if get_token_fn(txt[:i]) < limit: - return txt[:i], txt[i:] - return "Tiktoken未知错误", "Tiktoken未知错误" - -def breakdown_txt_to_satisfy_token_limit_for_pdf(txt, get_token_fn, limit): - # 递归 - def cut(txt_tocut, must_break_at_empty_line, break_anyway=False): - if get_token_fn(txt_tocut) <= limit: - return [txt_tocut] - else: - lines = txt_tocut.split('\n') - estimated_line_cut = limit / get_token_fn(txt_tocut) * len(lines) - estimated_line_cut = int(estimated_line_cut) - cnt = 0 - for cnt in reversed(range(estimated_line_cut)): - if must_break_at_empty_line: - if lines[cnt] != "": - continue - prev = "\n".join(lines[:cnt]) - post = "\n".join(lines[cnt:]) - if get_token_fn(prev) < limit: - break - if cnt == 0: - if break_anyway: - prev, post = force_breakdown(txt_tocut, limit, get_token_fn) - else: - raise RuntimeError(f"存在一行极长的文本!{txt_tocut}") - # print(len(post)) - # 列表递归接龙 - result = [prev] - result.extend(cut(post, must_break_at_empty_line, break_anyway=break_anyway)) - return result - try: - # 第1次尝试,将双空行(\n\n)作为切分点 - return cut(txt, must_break_at_empty_line=True) - except RuntimeError: - try: - # 第2次尝试,将单空行(\n)作为切分点 - return cut(txt, must_break_at_empty_line=False) - except RuntimeError: - try: - # 第3次尝试,将英文句号(.)作为切分点 - res = cut(txt.replace('.', '。\n'), must_break_at_empty_line=False) # 这个中文的句号是故意的,作为一个标识而存在 - return [r.replace('。\n', '.') for r in res] - except RuntimeError as e: - try: - # 第4次尝试,将中文句号(。)作为切分点 - res = cut(txt.replace('。', '。。\n'), must_break_at_empty_line=False) - return [r.replace('。。\n', '。') for r in res] - except RuntimeError as e: - # 第5次尝试,没办法了,随便切一下敷衍吧 - return cut(txt, must_break_at_empty_line=False, break_anyway=True) - - - -def read_and_clean_pdf_text(fp): - """ - 这个函数用于分割pdf,用了很多trick,逻辑较乱,效果奇好 - - **输入参数说明** - - `fp`:需要读取和清理文本的pdf文件路径 - - **输出参数说明** - - `meta_txt`:清理后的文本内容字符串 - - `page_one_meta`:第一页清理后的文本内容列表 - - **函数功能** - 读取pdf文件并清理其中的文本内容,清理规则包括: - - 提取所有块元的文本信息,并合并为一个字符串 - - 去除短块(字符数小于100)并替换为回车符 - - 清理多余的空行 - - 合并小写字母开头的段落块并替换为空格 - - 清除重复的换行 - - 将每个换行符替换为两个换行符,使每个段落之间有两个换行符分隔 - """ - import fitz, copy - import re - import numpy as np - from colorful import print亮黄, print亮绿 - fc = 0 # Index 0 文本 - fs = 1 # Index 1 字体 - fb = 2 # Index 2 框框 - REMOVE_FOOT_NOTE = True # 是否丢弃掉 不是正文的内容 (比正文字体小,如参考文献、脚注、图注等) - REMOVE_FOOT_FFSIZE_PERCENT = 0.95 # 小于正文的?时,判定为不是正文(有些文章的正文部分字体大小不是100%统一的,有肉眼不可见的小变化) - def primary_ffsize(l): - """ - 提取文本块主字体 - """ - fsize_statiscs = {} - for wtf in l['spans']: - if wtf['size'] not in fsize_statiscs: fsize_statiscs[wtf['size']] = 0 - fsize_statiscs[wtf['size']] += len(wtf['text']) - return max(fsize_statiscs, key=fsize_statiscs.get) - - def ffsize_same(a,b): - """ - 提取字体大小是否近似相等 - """ - return abs((a-b)/max(a,b)) < 0.02 - - with fitz.open(fp) as doc: - meta_txt = [] - meta_font = [] - - meta_line = [] - meta_span = [] - ############################## <第 1 步,搜集初始信息> ################################## - for index, page in enumerate(doc): - # file_content += page.get_text() - text_areas = page.get_text("dict") # 获取页面上的文本信息 - for t in text_areas['blocks']: - if 'lines' in t: - pf = 998 - for l in t['lines']: - txt_line = "".join([wtf['text'] for wtf in l['spans']]) - if len(txt_line) == 0: continue - pf = primary_ffsize(l) - meta_line.append([txt_line, pf, l['bbox'], l]) - for wtf in l['spans']: # for l in t['lines']: - meta_span.append([wtf['text'], wtf['size'], len(wtf['text'])]) - # meta_line.append(["NEW_BLOCK", pf]) - # 块元提取 for each word segment with in line for each line cross-line words for each block - meta_txt.extend([" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace( - '- ', '') for t in text_areas['blocks'] if 'lines' in t]) - meta_font.extend([np.mean([np.mean([wtf['size'] for wtf in l['spans']]) - for l in t['lines']]) for t in text_areas['blocks'] if 'lines' in t]) - if index == 0: - page_one_meta = [" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace( - '- ', '') for t in text_areas['blocks'] if 'lines' in t] - - ############################## <第 2 步,获取正文主字体> ################################## - fsize_statiscs = {} - for span in meta_span: - if span[1] not in fsize_statiscs: fsize_statiscs[span[1]] = 0 - fsize_statiscs[span[1]] += span[2] - main_fsize = max(fsize_statiscs, key=fsize_statiscs.get) - if REMOVE_FOOT_NOTE: - give_up_fize_threshold = main_fsize * REMOVE_FOOT_FFSIZE_PERCENT - - ############################## <第 3 步,切分和重新整合> ################################## - mega_sec = [] - sec = [] - for index, line in enumerate(meta_line): - if index == 0: - sec.append(line[fc]) - continue - if REMOVE_FOOT_NOTE: - if meta_line[index][fs] <= give_up_fize_threshold: - continue - if ffsize_same(meta_line[index][fs], meta_line[index-1][fs]): - # 尝试识别段落 - if meta_line[index][fc].endswith('.') and\ - (meta_line[index-1][fc] != 'NEW_BLOCK') and \ - (meta_line[index][fb][2] - meta_line[index][fb][0]) < (meta_line[index-1][fb][2] - meta_line[index-1][fb][0]) * 0.7: - sec[-1] += line[fc] - sec[-1] += "\n\n" - else: - sec[-1] += " " - sec[-1] += line[fc] - else: - if (index+1 < len(meta_line)) and \ - meta_line[index][fs] > main_fsize: - # 单行 + 字体大 - mega_sec.append(copy.deepcopy(sec)) - sec = [] - sec.append("# " + line[fc]) - else: - # 尝试识别section - if meta_line[index-1][fs] > meta_line[index][fs]: - sec.append("\n" + line[fc]) - else: - sec.append(line[fc]) - mega_sec.append(copy.deepcopy(sec)) - - finals = [] - for ms in mega_sec: - final = " ".join(ms) - final = final.replace('- ', ' ') - finals.append(final) - meta_txt = finals - - ############################## <第 4 步,乱七八糟的后处理> ################################## - def 把字符太少的块清除为回车(meta_txt): - for index, block_txt in enumerate(meta_txt): - if len(block_txt) < 100: - meta_txt[index] = '\n' - return meta_txt - meta_txt = 把字符太少的块清除为回车(meta_txt) - - def 清理多余的空行(meta_txt): - for index in reversed(range(1, len(meta_txt))): - if meta_txt[index] == '\n' and meta_txt[index-1] == '\n': - meta_txt.pop(index) - return meta_txt - meta_txt = 清理多余的空行(meta_txt) - - def 合并小写开头的段落块(meta_txt): - def starts_with_lowercase_word(s): - pattern = r"^[a-z]+" - match = re.match(pattern, s) - if match: - return True - else: - return False - for _ in range(100): - for index, block_txt in enumerate(meta_txt): - if starts_with_lowercase_word(block_txt): - if meta_txt[index-1] != '\n': - meta_txt[index-1] += ' ' - else: - meta_txt[index-1] = '' - meta_txt[index-1] += meta_txt[index] - meta_txt[index] = '\n' - return meta_txt - meta_txt = 合并小写开头的段落块(meta_txt) - meta_txt = 清理多余的空行(meta_txt) - - meta_txt = '\n'.join(meta_txt) - # 清除重复的换行 - for _ in range(5): - meta_txt = meta_txt.replace('\n\n', '\n') - - # 换行 -> 双换行 - meta_txt = meta_txt.replace('\n', '\n\n') - - ############################## <第 5 步,展示分割效果> ################################## - # for f in finals: - # print亮黄(f) - # print亮绿('***************************') - - return meta_txt, page_one_meta - - -def get_files_from_everything(txt, type): # type='.md' - """ - 这个函数是用来获取指定目录下所有指定类型(如.md)的文件,并且对于网络上的文件,也可以获取它。 - 下面是对每个参数和返回值的说明: - 参数 - - txt: 路径或网址,表示要搜索的文件或者文件夹路径或网络上的文件。 - - type: 字符串,表示要搜索的文件类型。默认是.md。 - 返回值 - - success: 布尔值,表示函数是否成功执行。 - - file_manifest: 文件路径列表,里面包含以指定类型为后缀名的所有文件的绝对路径。 - - project_folder: 字符串,表示文件所在的文件夹路径。如果是网络上的文件,就是临时文件夹的路径。 - 该函数详细注释已添加,请确认是否满足您的需要。 - """ - import glob, os - - success = True - if txt.startswith('http'): - # 网络的远程文件 - import requests - from toolbox import get_conf - proxies, = get_conf('proxies') - r = requests.get(txt, proxies=proxies) - with open('./gpt_log/temp'+type, 'wb+') as f: f.write(r.content) - project_folder = './gpt_log/' - file_manifest = ['./gpt_log/temp'+type] - elif txt.endswith(type): - # 直接给定文件 - file_manifest = [txt] - project_folder = os.path.dirname(txt) - elif os.path.exists(txt): - # 本地路径,递归搜索 - project_folder = txt - file_manifest = [f for f in glob.glob(f'{project_folder}/**/*'+type, recursive=True)] - if len(file_manifest) == 0: - success = False - else: - project_folder = None - file_manifest = [] - success = False - - return success, file_manifest, project_folder diff --git a/spaces/erbanku/gpt-academic/crazy_functions/test_project/cpp/libJPG/jpgd.cpp b/spaces/erbanku/gpt-academic/crazy_functions/test_project/cpp/libJPG/jpgd.cpp deleted file mode 100644 index 36d06c8e9068570c3e7624895d474f33dbfe3d29..0000000000000000000000000000000000000000 --- a/spaces/erbanku/gpt-academic/crazy_functions/test_project/cpp/libJPG/jpgd.cpp +++ /dev/null @@ -1,3276 +0,0 @@ -// jpgd.cpp - C++ class for JPEG decompression. -// Public domain, Rich Geldreich -// Last updated Apr. 16, 2011 -// Alex Evans: Linear memory allocator (taken from jpge.h). -// -// Supports progressive and baseline sequential JPEG image files, and the most common chroma subsampling factors: Y, H1V1, H2V1, H1V2, and H2V2. -// -// Chroma upsampling quality: H2V2 is upsampled in the frequency domain, H2V1 and H1V2 are upsampled using point sampling. -// Chroma upsampling reference: "Fast Scheme for Image Size Change in the Compressed Domain" -// http://vision.ai.uiuc.edu/~dugad/research/dct/index.html - -#include "jpgd.h" -#include - -#include -// BEGIN EPIC MOD -#define JPGD_ASSERT(x) { assert(x); CA_ASSUME(x); } (void)0 -// END EPIC MOD - -#ifdef _MSC_VER -#pragma warning (disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable -#endif - -// Set to 1 to enable freq. domain chroma upsampling on images using H2V2 subsampling (0=faster nearest neighbor sampling). -// This is slower, but results in higher quality on images with highly saturated colors. -#define JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING 1 - -#define JPGD_TRUE (1) -#define JPGD_FALSE (0) - -#define JPGD_MAX(a,b) (((a)>(b)) ? (a) : (b)) -#define JPGD_MIN(a,b) (((a)<(b)) ? (a) : (b)) - -namespace jpgd { - - static inline void *jpgd_malloc(size_t nSize) { return FMemory::Malloc(nSize); } - static inline void jpgd_free(void *p) { FMemory::Free(p); } - -// BEGIN EPIC MOD -//@UE3 - use UE3 BGRA encoding instead of assuming RGBA - // stolen from IImageWrapper.h - enum ERGBFormatJPG - { - Invalid = -1, - RGBA = 0, - BGRA = 1, - Gray = 2, - }; - static ERGBFormatJPG jpg_format; -// END EPIC MOD - - // DCT coefficients are stored in this sequence. - static int g_ZAG[64] = { 0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63 }; - - enum JPEG_MARKER - { - M_SOF0 = 0xC0, M_SOF1 = 0xC1, M_SOF2 = 0xC2, M_SOF3 = 0xC3, M_SOF5 = 0xC5, M_SOF6 = 0xC6, M_SOF7 = 0xC7, M_JPG = 0xC8, - M_SOF9 = 0xC9, M_SOF10 = 0xCA, M_SOF11 = 0xCB, M_SOF13 = 0xCD, M_SOF14 = 0xCE, M_SOF15 = 0xCF, M_DHT = 0xC4, M_DAC = 0xCC, - M_RST0 = 0xD0, M_RST1 = 0xD1, M_RST2 = 0xD2, M_RST3 = 0xD3, M_RST4 = 0xD4, M_RST5 = 0xD5, M_RST6 = 0xD6, M_RST7 = 0xD7, - M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_DNL = 0xDC, M_DRI = 0xDD, M_DHP = 0xDE, M_EXP = 0xDF, - M_APP0 = 0xE0, M_APP15 = 0xEF, M_JPG0 = 0xF0, M_JPG13 = 0xFD, M_COM = 0xFE, M_TEM = 0x01, M_ERROR = 0x100, RST0 = 0xD0 - }; - - enum JPEG_SUBSAMPLING { JPGD_GRAYSCALE = 0, JPGD_YH1V1, JPGD_YH2V1, JPGD_YH1V2, JPGD_YH2V2 }; - -#define CONST_BITS 13 -#define PASS1_BITS 2 -#define SCALEDONE ((int32)1) - -#define FIX_0_298631336 ((int32)2446) /* FIX(0.298631336) */ -#define FIX_0_390180644 ((int32)3196) /* FIX(0.390180644) */ -#define FIX_0_541196100 ((int32)4433) /* FIX(0.541196100) */ -#define FIX_0_765366865 ((int32)6270) /* FIX(0.765366865) */ -#define FIX_0_899976223 ((int32)7373) /* FIX(0.899976223) */ -#define FIX_1_175875602 ((int32)9633) /* FIX(1.175875602) */ -#define FIX_1_501321110 ((int32)12299) /* FIX(1.501321110) */ -#define FIX_1_847759065 ((int32)15137) /* FIX(1.847759065) */ -#define FIX_1_961570560 ((int32)16069) /* FIX(1.961570560) */ -#define FIX_2_053119869 ((int32)16819) /* FIX(2.053119869) */ -#define FIX_2_562915447 ((int32)20995) /* FIX(2.562915447) */ -#define FIX_3_072711026 ((int32)25172) /* FIX(3.072711026) */ - -#define DESCALE(x,n) (((x) + (SCALEDONE << ((n)-1))) >> (n)) -#define DESCALE_ZEROSHIFT(x,n) (((x) + (128 << (n)) + (SCALEDONE << ((n)-1))) >> (n)) - -#define MULTIPLY(var, cnst) ((var) * (cnst)) - -#define CLAMP(i) ((static_cast(i) > 255) ? (((~i) >> 31) & 0xFF) : (i)) - - // Compiler creates a fast path 1D IDCT for X non-zero columns - template - struct Row - { - static void idct(int* pTemp, const jpgd_block_t* pSrc) - { - // ACCESS_COL() will be optimized at compile time to either an array access, or 0. -#define ACCESS_COL(x) (((x) < NONZERO_COLS) ? (int)pSrc[x] : 0) - - const int z2 = ACCESS_COL(2), z3 = ACCESS_COL(6); - - const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100); - const int tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065); - const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865); - - const int tmp0 = (ACCESS_COL(0) + ACCESS_COL(4)) << CONST_BITS; - const int tmp1 = (ACCESS_COL(0) - ACCESS_COL(4)) << CONST_BITS; - - const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2; - - const int atmp0 = ACCESS_COL(7), atmp1 = ACCESS_COL(5), atmp2 = ACCESS_COL(3), atmp3 = ACCESS_COL(1); - - const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3; - const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602); - - const int az1 = MULTIPLY(bz1, - FIX_0_899976223); - const int az2 = MULTIPLY(bz2, - FIX_2_562915447); - const int az3 = MULTIPLY(bz3, - FIX_1_961570560) + bz5; - const int az4 = MULTIPLY(bz4, - FIX_0_390180644) + bz5; - - const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3; - const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4; - const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3; - const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4; - - pTemp[0] = DESCALE(tmp10 + btmp3, CONST_BITS-PASS1_BITS); - pTemp[7] = DESCALE(tmp10 - btmp3, CONST_BITS-PASS1_BITS); - pTemp[1] = DESCALE(tmp11 + btmp2, CONST_BITS-PASS1_BITS); - pTemp[6] = DESCALE(tmp11 - btmp2, CONST_BITS-PASS1_BITS); - pTemp[2] = DESCALE(tmp12 + btmp1, CONST_BITS-PASS1_BITS); - pTemp[5] = DESCALE(tmp12 - btmp1, CONST_BITS-PASS1_BITS); - pTemp[3] = DESCALE(tmp13 + btmp0, CONST_BITS-PASS1_BITS); - pTemp[4] = DESCALE(tmp13 - btmp0, CONST_BITS-PASS1_BITS); - } - }; - - template <> - struct Row<0> - { - static void idct(int* pTemp, const jpgd_block_t* pSrc) - { -#ifdef _MSC_VER - pTemp; pSrc; -#endif - } - }; - - template <> - struct Row<1> - { - static void idct(int* pTemp, const jpgd_block_t* pSrc) - { - const int dcval = (pSrc[0] << PASS1_BITS); - - pTemp[0] = dcval; - pTemp[1] = dcval; - pTemp[2] = dcval; - pTemp[3] = dcval; - pTemp[4] = dcval; - pTemp[5] = dcval; - pTemp[6] = dcval; - pTemp[7] = dcval; - } - }; - - // Compiler creates a fast path 1D IDCT for X non-zero rows - template - struct Col - { - static void idct(uint8* pDst_ptr, const int* pTemp) - { - // ACCESS_ROW() will be optimized at compile time to either an array access, or 0. -#define ACCESS_ROW(x) (((x) < NONZERO_ROWS) ? pTemp[x * 8] : 0) - - const int z2 = ACCESS_ROW(2); - const int z3 = ACCESS_ROW(6); - - const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100); - const int tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065); - const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865); - - const int tmp0 = (ACCESS_ROW(0) + ACCESS_ROW(4)) << CONST_BITS; - const int tmp1 = (ACCESS_ROW(0) - ACCESS_ROW(4)) << CONST_BITS; - - const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2; - - const int atmp0 = ACCESS_ROW(7), atmp1 = ACCESS_ROW(5), atmp2 = ACCESS_ROW(3), atmp3 = ACCESS_ROW(1); - - const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3; - const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602); - - const int az1 = MULTIPLY(bz1, - FIX_0_899976223); - const int az2 = MULTIPLY(bz2, - FIX_2_562915447); - const int az3 = MULTIPLY(bz3, - FIX_1_961570560) + bz5; - const int az4 = MULTIPLY(bz4, - FIX_0_390180644) + bz5; - - const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3; - const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4; - const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3; - const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4; - - int i = DESCALE_ZEROSHIFT(tmp10 + btmp3, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*0] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp10 - btmp3, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*7] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp11 + btmp2, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*1] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp11 - btmp2, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*6] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp12 + btmp1, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*2] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp12 - btmp1, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*5] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp13 + btmp0, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*3] = (uint8)CLAMP(i); - - i = DESCALE_ZEROSHIFT(tmp13 - btmp0, CONST_BITS+PASS1_BITS+3); - pDst_ptr[8*4] = (uint8)CLAMP(i); - } - }; - - template <> - struct Col<1> - { - static void idct(uint8* pDst_ptr, const int* pTemp) - { - int dcval = DESCALE_ZEROSHIFT(pTemp[0], PASS1_BITS+3); - const uint8 dcval_clamped = (uint8)CLAMP(dcval); - pDst_ptr[0*8] = dcval_clamped; - pDst_ptr[1*8] = dcval_clamped; - pDst_ptr[2*8] = dcval_clamped; - pDst_ptr[3*8] = dcval_clamped; - pDst_ptr[4*8] = dcval_clamped; - pDst_ptr[5*8] = dcval_clamped; - pDst_ptr[6*8] = dcval_clamped; - pDst_ptr[7*8] = dcval_clamped; - } - }; - - static const uint8 s_idct_row_table[] = - { - 1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0, 2,1,0,0,0,0,0,0, 2,1,1,0,0,0,0,0, 2,2,1,0,0,0,0,0, 3,2,1,0,0,0,0,0, 4,2,1,0,0,0,0,0, 4,3,1,0,0,0,0,0, - 4,3,2,0,0,0,0,0, 4,3,2,1,0,0,0,0, 4,3,2,1,1,0,0,0, 4,3,2,2,1,0,0,0, 4,3,3,2,1,0,0,0, 4,4,3,2,1,0,0,0, 5,4,3,2,1,0,0,0, 6,4,3,2,1,0,0,0, - 6,5,3,2,1,0,0,0, 6,5,4,2,1,0,0,0, 6,5,4,3,1,0,0,0, 6,5,4,3,2,0,0,0, 6,5,4,3,2,1,0,0, 6,5,4,3,2,1,1,0, 6,5,4,3,2,2,1,0, 6,5,4,3,3,2,1,0, - 6,5,4,4,3,2,1,0, 6,5,5,4,3,2,1,0, 6,6,5,4,3,2,1,0, 7,6,5,4,3,2,1,0, 8,6,5,4,3,2,1,0, 8,7,5,4,3,2,1,0, 8,7,6,4,3,2,1,0, 8,7,6,5,3,2,1,0, - 8,7,6,5,4,2,1,0, 8,7,6,5,4,3,1,0, 8,7,6,5,4,3,2,0, 8,7,6,5,4,3,2,1, 8,7,6,5,4,3,2,2, 8,7,6,5,4,3,3,2, 8,7,6,5,4,4,3,2, 8,7,6,5,5,4,3,2, - 8,7,6,6,5,4,3,2, 8,7,7,6,5,4,3,2, 8,8,7,6,5,4,3,2, 8,8,8,6,5,4,3,2, 8,8,8,7,5,4,3,2, 8,8,8,7,6,4,3,2, 8,8,8,7,6,5,3,2, 8,8,8,7,6,5,4,2, - 8,8,8,7,6,5,4,3, 8,8,8,7,6,5,4,4, 8,8,8,7,6,5,5,4, 8,8,8,7,6,6,5,4, 8,8,8,7,7,6,5,4, 8,8,8,8,7,6,5,4, 8,8,8,8,8,6,5,4, 8,8,8,8,8,7,5,4, - 8,8,8,8,8,7,6,4, 8,8,8,8,8,7,6,5, 8,8,8,8,8,7,6,6, 8,8,8,8,8,7,7,6, 8,8,8,8,8,8,7,6, 8,8,8,8,8,8,8,6, 8,8,8,8,8,8,8,7, 8,8,8,8,8,8,8,8, - }; - - static const uint8 s_idct_col_table[] = { 1, 1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }; - - void idct(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr, int block_max_zag) - { - JPGD_ASSERT(block_max_zag >= 1); - JPGD_ASSERT(block_max_zag <= 64); - - if (block_max_zag == 1) - { - int k = ((pSrc_ptr[0] + 4) >> 3) + 128; - k = CLAMP(k); - k = k | (k<<8); - k = k | (k<<16); - - for (int i = 8; i > 0; i--) - { - *(int*)&pDst_ptr[0] = k; - *(int*)&pDst_ptr[4] = k; - pDst_ptr += 8; - } - return; - } - - int temp[64]; - - const jpgd_block_t* pSrc = pSrc_ptr; - int* pTemp = temp; - - const uint8* pRow_tab = &s_idct_row_table[(block_max_zag - 1) * 8]; - int i; - for (i = 8; i > 0; i--, pRow_tab++) - { - switch (*pRow_tab) - { - case 0: Row<0>::idct(pTemp, pSrc); break; - case 1: Row<1>::idct(pTemp, pSrc); break; - case 2: Row<2>::idct(pTemp, pSrc); break; - case 3: Row<3>::idct(pTemp, pSrc); break; - case 4: Row<4>::idct(pTemp, pSrc); break; - case 5: Row<5>::idct(pTemp, pSrc); break; - case 6: Row<6>::idct(pTemp, pSrc); break; - case 7: Row<7>::idct(pTemp, pSrc); break; - case 8: Row<8>::idct(pTemp, pSrc); break; - } - - pSrc += 8; - pTemp += 8; - } - - pTemp = temp; - - const int nonzero_rows = s_idct_col_table[block_max_zag - 1]; - for (i = 8; i > 0; i--) - { - switch (nonzero_rows) - { - case 1: Col<1>::idct(pDst_ptr, pTemp); break; - case 2: Col<2>::idct(pDst_ptr, pTemp); break; - case 3: Col<3>::idct(pDst_ptr, pTemp); break; - case 4: Col<4>::idct(pDst_ptr, pTemp); break; - case 5: Col<5>::idct(pDst_ptr, pTemp); break; - case 6: Col<6>::idct(pDst_ptr, pTemp); break; - case 7: Col<7>::idct(pDst_ptr, pTemp); break; - case 8: Col<8>::idct(pDst_ptr, pTemp); break; - } - - pTemp++; - pDst_ptr++; - } - } - - void idct_4x4(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr) - { - int temp[64]; - int* pTemp = temp; - const jpgd_block_t* pSrc = pSrc_ptr; - - for (int i = 4; i > 0; i--) - { - Row<4>::idct(pTemp, pSrc); - pSrc += 8; - pTemp += 8; - } - - pTemp = temp; - for (int i = 8; i > 0; i--) - { - Col<4>::idct(pDst_ptr, pTemp); - pTemp++; - pDst_ptr++; - } - } - - // Retrieve one character from the input stream. - inline uint jpeg_decoder::get_char() - { - // Any bytes remaining in buffer? - if (!m_in_buf_left) - { - // Try to get more bytes. - prep_in_buffer(); - // Still nothing to get? - if (!m_in_buf_left) - { - // Pad the end of the stream with 0xFF 0xD9 (EOI marker) - int t = m_tem_flag; - m_tem_flag ^= 1; - if (t) - return 0xD9; - else - return 0xFF; - } - } - - uint c = *m_pIn_buf_ofs++; - m_in_buf_left--; - - return c; - } - - // Same as previous method, except can indicate if the character is a pad character or not. - inline uint jpeg_decoder::get_char(bool *pPadding_flag) - { - if (!m_in_buf_left) - { - prep_in_buffer(); - if (!m_in_buf_left) - { - *pPadding_flag = true; - int t = m_tem_flag; - m_tem_flag ^= 1; - if (t) - return 0xD9; - else - return 0xFF; - } - } - - *pPadding_flag = false; - - uint c = *m_pIn_buf_ofs++; - m_in_buf_left--; - - return c; - } - - // Inserts a previously retrieved character back into the input buffer. - inline void jpeg_decoder::stuff_char(uint8 q) - { - *(--m_pIn_buf_ofs) = q; - m_in_buf_left++; - } - - // Retrieves one character from the input stream, but does not read past markers. Will continue to return 0xFF when a marker is encountered. - inline uint8 jpeg_decoder::get_octet() - { - bool padding_flag; - int c = get_char(&padding_flag); - - if (c == 0xFF) - { - if (padding_flag) - return 0xFF; - - c = get_char(&padding_flag); - if (padding_flag) - { - stuff_char(0xFF); - return 0xFF; - } - - if (c == 0x00) - return 0xFF; - else - { - stuff_char(static_cast(c)); - stuff_char(0xFF); - return 0xFF; - } - } - - return static_cast(c); - } - - // Retrieves a variable number of bits from the input stream. Does not recognize markers. - inline uint jpeg_decoder::get_bits(int num_bits) - { - if (!num_bits) - return 0; - - uint i = m_bit_buf >> (32 - num_bits); - - if ((m_bits_left -= num_bits) <= 0) - { - m_bit_buf <<= (num_bits += m_bits_left); - - uint c1 = get_char(); - uint c2 = get_char(); - m_bit_buf = (m_bit_buf & 0xFFFF0000) | (c1 << 8) | c2; - - m_bit_buf <<= -m_bits_left; - - m_bits_left += 16; - - JPGD_ASSERT(m_bits_left >= 0); - } - else - m_bit_buf <<= num_bits; - - return i; - } - - // Retrieves a variable number of bits from the input stream. Markers will not be read into the input bit buffer. Instead, an infinite number of all 1's will be returned when a marker is encountered. - inline uint jpeg_decoder::get_bits_no_markers(int num_bits) - { - if (!num_bits) - return 0; - - uint i = m_bit_buf >> (32 - num_bits); - - if ((m_bits_left -= num_bits) <= 0) - { - m_bit_buf <<= (num_bits += m_bits_left); - - if ((m_in_buf_left < 2) || (m_pIn_buf_ofs[0] == 0xFF) || (m_pIn_buf_ofs[1] == 0xFF)) - { - uint c1 = get_octet(); - uint c2 = get_octet(); - m_bit_buf |= (c1 << 8) | c2; - } - else - { - m_bit_buf |= ((uint)m_pIn_buf_ofs[0] << 8) | m_pIn_buf_ofs[1]; - m_in_buf_left -= 2; - m_pIn_buf_ofs += 2; - } - - m_bit_buf <<= -m_bits_left; - - m_bits_left += 16; - - JPGD_ASSERT(m_bits_left >= 0); - } - else - m_bit_buf <<= num_bits; - - return i; - } - - // Decodes a Huffman encoded symbol. - inline int jpeg_decoder::huff_decode(huff_tables *pH) - { - int symbol; - - // Check first 8-bits: do we have a complete symbol? - if ((symbol = pH->look_up[m_bit_buf >> 24]) < 0) - { - // Decode more bits, use a tree traversal to find symbol. - int ofs = 23; - do - { - symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))]; - ofs--; - } while (symbol < 0); - - get_bits_no_markers(8 + (23 - ofs)); - } - else - get_bits_no_markers(pH->code_size[symbol]); - - return symbol; - } - - // Decodes a Huffman encoded symbol. - inline int jpeg_decoder::huff_decode(huff_tables *pH, int& extra_bits) - { - int symbol; - - // Check first 8-bits: do we have a complete symbol? - if ((symbol = pH->look_up2[m_bit_buf >> 24]) < 0) - { - // Use a tree traversal to find symbol. - int ofs = 23; - do - { - symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))]; - ofs--; - } while (symbol < 0); - - get_bits_no_markers(8 + (23 - ofs)); - - extra_bits = get_bits_no_markers(symbol & 0xF); - } - else - { - JPGD_ASSERT(((symbol >> 8) & 31) == pH->code_size[symbol & 255] + ((symbol & 0x8000) ? (symbol & 15) : 0)); - - if (symbol & 0x8000) - { - get_bits_no_markers((symbol >> 8) & 31); - extra_bits = symbol >> 16; - } - else - { - int code_size = (symbol >> 8) & 31; - int num_extra_bits = symbol & 0xF; - int bits = code_size + num_extra_bits; - if (bits <= (m_bits_left + 16)) - extra_bits = get_bits_no_markers(bits) & ((1 << num_extra_bits) - 1); - else - { - get_bits_no_markers(code_size); - extra_bits = get_bits_no_markers(num_extra_bits); - } - } - - symbol &= 0xFF; - } - - return symbol; - } - - // Tables and macro used to fully decode the DPCM differences. - static const int s_extend_test[16] = { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 }; - static const int s_extend_offset[16] = { 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, -4095, -8191, -16383, -32767 }; - static const int s_extend_mask[] = { 0, (1<<0), (1<<1), (1<<2), (1<<3), (1<<4), (1<<5), (1<<6), (1<<7), (1<<8), (1<<9), (1<<10), (1<<11), (1<<12), (1<<13), (1<<14), (1<<15), (1<<16) }; -#define HUFF_EXTEND(x,s) ((x) < s_extend_test[s] ? (x) + s_extend_offset[s] : (x)) - - // Clamps a value between 0-255. - inline uint8 jpeg_decoder::clamp(int i) - { - if (static_cast(i) > 255) - i = (((~i) >> 31) & 0xFF); - - return static_cast(i); - } - - namespace DCT_Upsample - { - struct Matrix44 - { - typedef int Element_Type; - enum { NUM_ROWS = 4, NUM_COLS = 4 }; - - Element_Type v[NUM_ROWS][NUM_COLS]; - - inline int rows() const { return NUM_ROWS; } - inline int cols() const { return NUM_COLS; } - - inline const Element_Type & at(int r, int c) const { return v[r][c]; } - inline Element_Type & at(int r, int c) { return v[r][c]; } - - inline Matrix44() { } - - inline Matrix44& operator += (const Matrix44& a) - { - for (int r = 0; r < NUM_ROWS; r++) - { - at(r, 0) += a.at(r, 0); - at(r, 1) += a.at(r, 1); - at(r, 2) += a.at(r, 2); - at(r, 3) += a.at(r, 3); - } - return *this; - } - - inline Matrix44& operator -= (const Matrix44& a) - { - for (int r = 0; r < NUM_ROWS; r++) - { - at(r, 0) -= a.at(r, 0); - at(r, 1) -= a.at(r, 1); - at(r, 2) -= a.at(r, 2); - at(r, 3) -= a.at(r, 3); - } - return *this; - } - - friend inline Matrix44 operator + (const Matrix44& a, const Matrix44& b) - { - Matrix44 ret; - for (int r = 0; r < NUM_ROWS; r++) - { - ret.at(r, 0) = a.at(r, 0) + b.at(r, 0); - ret.at(r, 1) = a.at(r, 1) + b.at(r, 1); - ret.at(r, 2) = a.at(r, 2) + b.at(r, 2); - ret.at(r, 3) = a.at(r, 3) + b.at(r, 3); - } - return ret; - } - - friend inline Matrix44 operator - (const Matrix44& a, const Matrix44& b) - { - Matrix44 ret; - for (int r = 0; r < NUM_ROWS; r++) - { - ret.at(r, 0) = a.at(r, 0) - b.at(r, 0); - ret.at(r, 1) = a.at(r, 1) - b.at(r, 1); - ret.at(r, 2) = a.at(r, 2) - b.at(r, 2); - ret.at(r, 3) = a.at(r, 3) - b.at(r, 3); - } - return ret; - } - - static inline void add_and_store(jpgd_block_t* pDst, const Matrix44& a, const Matrix44& b) - { - for (int r = 0; r < 4; r++) - { - pDst[0*8 + r] = static_cast(a.at(r, 0) + b.at(r, 0)); - pDst[1*8 + r] = static_cast(a.at(r, 1) + b.at(r, 1)); - pDst[2*8 + r] = static_cast(a.at(r, 2) + b.at(r, 2)); - pDst[3*8 + r] = static_cast(a.at(r, 3) + b.at(r, 3)); - } - } - - static inline void sub_and_store(jpgd_block_t* pDst, const Matrix44& a, const Matrix44& b) - { - for (int r = 0; r < 4; r++) - { - pDst[0*8 + r] = static_cast(a.at(r, 0) - b.at(r, 0)); - pDst[1*8 + r] = static_cast(a.at(r, 1) - b.at(r, 1)); - pDst[2*8 + r] = static_cast(a.at(r, 2) - b.at(r, 2)); - pDst[3*8 + r] = static_cast(a.at(r, 3) - b.at(r, 3)); - } - } - }; - - const int FRACT_BITS = 10; - const int SCALE = 1 << FRACT_BITS; - - typedef int Temp_Type; -#define D(i) (((i) + (SCALE >> 1)) >> FRACT_BITS) -#define F(i) ((int)((i) * SCALE + .5f)) - - // Any decent C++ compiler will optimize this at compile time to a 0, or an array access. -#define AT(c, r) ((((c)>=NUM_COLS)||((r)>=NUM_ROWS)) ? 0 : pSrc[(c)+(r)*8]) - - // NUM_ROWS/NUM_COLS = # of non-zero rows/cols in input matrix - template - struct P_Q - { - static void calc(Matrix44& P, Matrix44& Q, const jpgd_block_t* pSrc) - { - // 4x8 = 4x8 times 8x8, matrix 0 is constant - const Temp_Type X000 = AT(0, 0); - const Temp_Type X001 = AT(0, 1); - const Temp_Type X002 = AT(0, 2); - const Temp_Type X003 = AT(0, 3); - const Temp_Type X004 = AT(0, 4); - const Temp_Type X005 = AT(0, 5); - const Temp_Type X006 = AT(0, 6); - const Temp_Type X007 = AT(0, 7); - const Temp_Type X010 = D(F(0.415735f) * AT(1, 0) + F(0.791065f) * AT(3, 0) + F(-0.352443f) * AT(5, 0) + F(0.277785f) * AT(7, 0)); - const Temp_Type X011 = D(F(0.415735f) * AT(1, 1) + F(0.791065f) * AT(3, 1) + F(-0.352443f) * AT(5, 1) + F(0.277785f) * AT(7, 1)); - const Temp_Type X012 = D(F(0.415735f) * AT(1, 2) + F(0.791065f) * AT(3, 2) + F(-0.352443f) * AT(5, 2) + F(0.277785f) * AT(7, 2)); - const Temp_Type X013 = D(F(0.415735f) * AT(1, 3) + F(0.791065f) * AT(3, 3) + F(-0.352443f) * AT(5, 3) + F(0.277785f) * AT(7, 3)); - const Temp_Type X014 = D(F(0.415735f) * AT(1, 4) + F(0.791065f) * AT(3, 4) + F(-0.352443f) * AT(5, 4) + F(0.277785f) * AT(7, 4)); - const Temp_Type X015 = D(F(0.415735f) * AT(1, 5) + F(0.791065f) * AT(3, 5) + F(-0.352443f) * AT(5, 5) + F(0.277785f) * AT(7, 5)); - const Temp_Type X016 = D(F(0.415735f) * AT(1, 6) + F(0.791065f) * AT(3, 6) + F(-0.352443f) * AT(5, 6) + F(0.277785f) * AT(7, 6)); - const Temp_Type X017 = D(F(0.415735f) * AT(1, 7) + F(0.791065f) * AT(3, 7) + F(-0.352443f) * AT(5, 7) + F(0.277785f) * AT(7, 7)); - const Temp_Type X020 = AT(4, 0); - const Temp_Type X021 = AT(4, 1); - const Temp_Type X022 = AT(4, 2); - const Temp_Type X023 = AT(4, 3); - const Temp_Type X024 = AT(4, 4); - const Temp_Type X025 = AT(4, 5); - const Temp_Type X026 = AT(4, 6); - const Temp_Type X027 = AT(4, 7); - const Temp_Type X030 = D(F(0.022887f) * AT(1, 0) + F(-0.097545f) * AT(3, 0) + F(0.490393f) * AT(5, 0) + F(0.865723f) * AT(7, 0)); - const Temp_Type X031 = D(F(0.022887f) * AT(1, 1) + F(-0.097545f) * AT(3, 1) + F(0.490393f) * AT(5, 1) + F(0.865723f) * AT(7, 1)); - const Temp_Type X032 = D(F(0.022887f) * AT(1, 2) + F(-0.097545f) * AT(3, 2) + F(0.490393f) * AT(5, 2) + F(0.865723f) * AT(7, 2)); - const Temp_Type X033 = D(F(0.022887f) * AT(1, 3) + F(-0.097545f) * AT(3, 3) + F(0.490393f) * AT(5, 3) + F(0.865723f) * AT(7, 3)); - const Temp_Type X034 = D(F(0.022887f) * AT(1, 4) + F(-0.097545f) * AT(3, 4) + F(0.490393f) * AT(5, 4) + F(0.865723f) * AT(7, 4)); - const Temp_Type X035 = D(F(0.022887f) * AT(1, 5) + F(-0.097545f) * AT(3, 5) + F(0.490393f) * AT(5, 5) + F(0.865723f) * AT(7, 5)); - const Temp_Type X036 = D(F(0.022887f) * AT(1, 6) + F(-0.097545f) * AT(3, 6) + F(0.490393f) * AT(5, 6) + F(0.865723f) * AT(7, 6)); - const Temp_Type X037 = D(F(0.022887f) * AT(1, 7) + F(-0.097545f) * AT(3, 7) + F(0.490393f) * AT(5, 7) + F(0.865723f) * AT(7, 7)); - - // 4x4 = 4x8 times 8x4, matrix 1 is constant - P.at(0, 0) = X000; - P.at(0, 1) = D(X001 * F(0.415735f) + X003 * F(0.791065f) + X005 * F(-0.352443f) + X007 * F(0.277785f)); - P.at(0, 2) = X004; - P.at(0, 3) = D(X001 * F(0.022887f) + X003 * F(-0.097545f) + X005 * F(0.490393f) + X007 * F(0.865723f)); - P.at(1, 0) = X010; - P.at(1, 1) = D(X011 * F(0.415735f) + X013 * F(0.791065f) + X015 * F(-0.352443f) + X017 * F(0.277785f)); - P.at(1, 2) = X014; - P.at(1, 3) = D(X011 * F(0.022887f) + X013 * F(-0.097545f) + X015 * F(0.490393f) + X017 * F(0.865723f)); - P.at(2, 0) = X020; - P.at(2, 1) = D(X021 * F(0.415735f) + X023 * F(0.791065f) + X025 * F(-0.352443f) + X027 * F(0.277785f)); - P.at(2, 2) = X024; - P.at(2, 3) = D(X021 * F(0.022887f) + X023 * F(-0.097545f) + X025 * F(0.490393f) + X027 * F(0.865723f)); - P.at(3, 0) = X030; - P.at(3, 1) = D(X031 * F(0.415735f) + X033 * F(0.791065f) + X035 * F(-0.352443f) + X037 * F(0.277785f)); - P.at(3, 2) = X034; - P.at(3, 3) = D(X031 * F(0.022887f) + X033 * F(-0.097545f) + X035 * F(0.490393f) + X037 * F(0.865723f)); - // 40 muls 24 adds - - // 4x4 = 4x8 times 8x4, matrix 1 is constant - Q.at(0, 0) = D(X001 * F(0.906127f) + X003 * F(-0.318190f) + X005 * F(0.212608f) + X007 * F(-0.180240f)); - Q.at(0, 1) = X002; - Q.at(0, 2) = D(X001 * F(-0.074658f) + X003 * F(0.513280f) + X005 * F(0.768178f) + X007 * F(-0.375330f)); - Q.at(0, 3) = X006; - Q.at(1, 0) = D(X011 * F(0.906127f) + X013 * F(-0.318190f) + X015 * F(0.212608f) + X017 * F(-0.180240f)); - Q.at(1, 1) = X012; - Q.at(1, 2) = D(X011 * F(-0.074658f) + X013 * F(0.513280f) + X015 * F(0.768178f) + X017 * F(-0.375330f)); - Q.at(1, 3) = X016; - Q.at(2, 0) = D(X021 * F(0.906127f) + X023 * F(-0.318190f) + X025 * F(0.212608f) + X027 * F(-0.180240f)); - Q.at(2, 1) = X022; - Q.at(2, 2) = D(X021 * F(-0.074658f) + X023 * F(0.513280f) + X025 * F(0.768178f) + X027 * F(-0.375330f)); - Q.at(2, 3) = X026; - Q.at(3, 0) = D(X031 * F(0.906127f) + X033 * F(-0.318190f) + X035 * F(0.212608f) + X037 * F(-0.180240f)); - Q.at(3, 1) = X032; - Q.at(3, 2) = D(X031 * F(-0.074658f) + X033 * F(0.513280f) + X035 * F(0.768178f) + X037 * F(-0.375330f)); - Q.at(3, 3) = X036; - // 40 muls 24 adds - } - }; - - template - struct R_S - { - static void calc(Matrix44& R, Matrix44& S, const jpgd_block_t* pSrc) - { - // 4x8 = 4x8 times 8x8, matrix 0 is constant - const Temp_Type X100 = D(F(0.906127f) * AT(1, 0) + F(-0.318190f) * AT(3, 0) + F(0.212608f) * AT(5, 0) + F(-0.180240f) * AT(7, 0)); - const Temp_Type X101 = D(F(0.906127f) * AT(1, 1) + F(-0.318190f) * AT(3, 1) + F(0.212608f) * AT(5, 1) + F(-0.180240f) * AT(7, 1)); - const Temp_Type X102 = D(F(0.906127f) * AT(1, 2) + F(-0.318190f) * AT(3, 2) + F(0.212608f) * AT(5, 2) + F(-0.180240f) * AT(7, 2)); - const Temp_Type X103 = D(F(0.906127f) * AT(1, 3) + F(-0.318190f) * AT(3, 3) + F(0.212608f) * AT(5, 3) + F(-0.180240f) * AT(7, 3)); - const Temp_Type X104 = D(F(0.906127f) * AT(1, 4) + F(-0.318190f) * AT(3, 4) + F(0.212608f) * AT(5, 4) + F(-0.180240f) * AT(7, 4)); - const Temp_Type X105 = D(F(0.906127f) * AT(1, 5) + F(-0.318190f) * AT(3, 5) + F(0.212608f) * AT(5, 5) + F(-0.180240f) * AT(7, 5)); - const Temp_Type X106 = D(F(0.906127f) * AT(1, 6) + F(-0.318190f) * AT(3, 6) + F(0.212608f) * AT(5, 6) + F(-0.180240f) * AT(7, 6)); - const Temp_Type X107 = D(F(0.906127f) * AT(1, 7) + F(-0.318190f) * AT(3, 7) + F(0.212608f) * AT(5, 7) + F(-0.180240f) * AT(7, 7)); - const Temp_Type X110 = AT(2, 0); - const Temp_Type X111 = AT(2, 1); - const Temp_Type X112 = AT(2, 2); - const Temp_Type X113 = AT(2, 3); - const Temp_Type X114 = AT(2, 4); - const Temp_Type X115 = AT(2, 5); - const Temp_Type X116 = AT(2, 6); - const Temp_Type X117 = AT(2, 7); - const Temp_Type X120 = D(F(-0.074658f) * AT(1, 0) + F(0.513280f) * AT(3, 0) + F(0.768178f) * AT(5, 0) + F(-0.375330f) * AT(7, 0)); - const Temp_Type X121 = D(F(-0.074658f) * AT(1, 1) + F(0.513280f) * AT(3, 1) + F(0.768178f) * AT(5, 1) + F(-0.375330f) * AT(7, 1)); - const Temp_Type X122 = D(F(-0.074658f) * AT(1, 2) + F(0.513280f) * AT(3, 2) + F(0.768178f) * AT(5, 2) + F(-0.375330f) * AT(7, 2)); - const Temp_Type X123 = D(F(-0.074658f) * AT(1, 3) + F(0.513280f) * AT(3, 3) + F(0.768178f) * AT(5, 3) + F(-0.375330f) * AT(7, 3)); - const Temp_Type X124 = D(F(-0.074658f) * AT(1, 4) + F(0.513280f) * AT(3, 4) + F(0.768178f) * AT(5, 4) + F(-0.375330f) * AT(7, 4)); - const Temp_Type X125 = D(F(-0.074658f) * AT(1, 5) + F(0.513280f) * AT(3, 5) + F(0.768178f) * AT(5, 5) + F(-0.375330f) * AT(7, 5)); - const Temp_Type X126 = D(F(-0.074658f) * AT(1, 6) + F(0.513280f) * AT(3, 6) + F(0.768178f) * AT(5, 6) + F(-0.375330f) * AT(7, 6)); - const Temp_Type X127 = D(F(-0.074658f) * AT(1, 7) + F(0.513280f) * AT(3, 7) + F(0.768178f) * AT(5, 7) + F(-0.375330f) * AT(7, 7)); - const Temp_Type X130 = AT(6, 0); - const Temp_Type X131 = AT(6, 1); - const Temp_Type X132 = AT(6, 2); - const Temp_Type X133 = AT(6, 3); - const Temp_Type X134 = AT(6, 4); - const Temp_Type X135 = AT(6, 5); - const Temp_Type X136 = AT(6, 6); - const Temp_Type X137 = AT(6, 7); - // 80 muls 48 adds - - // 4x4 = 4x8 times 8x4, matrix 1 is constant - R.at(0, 0) = X100; - R.at(0, 1) = D(X101 * F(0.415735f) + X103 * F(0.791065f) + X105 * F(-0.352443f) + X107 * F(0.277785f)); - R.at(0, 2) = X104; - R.at(0, 3) = D(X101 * F(0.022887f) + X103 * F(-0.097545f) + X105 * F(0.490393f) + X107 * F(0.865723f)); - R.at(1, 0) = X110; - R.at(1, 1) = D(X111 * F(0.415735f) + X113 * F(0.791065f) + X115 * F(-0.352443f) + X117 * F(0.277785f)); - R.at(1, 2) = X114; - R.at(1, 3) = D(X111 * F(0.022887f) + X113 * F(-0.097545f) + X115 * F(0.490393f) + X117 * F(0.865723f)); - R.at(2, 0) = X120; - R.at(2, 1) = D(X121 * F(0.415735f) + X123 * F(0.791065f) + X125 * F(-0.352443f) + X127 * F(0.277785f)); - R.at(2, 2) = X124; - R.at(2, 3) = D(X121 * F(0.022887f) + X123 * F(-0.097545f) + X125 * F(0.490393f) + X127 * F(0.865723f)); - R.at(3, 0) = X130; - R.at(3, 1) = D(X131 * F(0.415735f) + X133 * F(0.791065f) + X135 * F(-0.352443f) + X137 * F(0.277785f)); - R.at(3, 2) = X134; - R.at(3, 3) = D(X131 * F(0.022887f) + X133 * F(-0.097545f) + X135 * F(0.490393f) + X137 * F(0.865723f)); - // 40 muls 24 adds - // 4x4 = 4x8 times 8x4, matrix 1 is constant - S.at(0, 0) = D(X101 * F(0.906127f) + X103 * F(-0.318190f) + X105 * F(0.212608f) + X107 * F(-0.180240f)); - S.at(0, 1) = X102; - S.at(0, 2) = D(X101 * F(-0.074658f) + X103 * F(0.513280f) + X105 * F(0.768178f) + X107 * F(-0.375330f)); - S.at(0, 3) = X106; - S.at(1, 0) = D(X111 * F(0.906127f) + X113 * F(-0.318190f) + X115 * F(0.212608f) + X117 * F(-0.180240f)); - S.at(1, 1) = X112; - S.at(1, 2) = D(X111 * F(-0.074658f) + X113 * F(0.513280f) + X115 * F(0.768178f) + X117 * F(-0.375330f)); - S.at(1, 3) = X116; - S.at(2, 0) = D(X121 * F(0.906127f) + X123 * F(-0.318190f) + X125 * F(0.212608f) + X127 * F(-0.180240f)); - S.at(2, 1) = X122; - S.at(2, 2) = D(X121 * F(-0.074658f) + X123 * F(0.513280f) + X125 * F(0.768178f) + X127 * F(-0.375330f)); - S.at(2, 3) = X126; - S.at(3, 0) = D(X131 * F(0.906127f) + X133 * F(-0.318190f) + X135 * F(0.212608f) + X137 * F(-0.180240f)); - S.at(3, 1) = X132; - S.at(3, 2) = D(X131 * F(-0.074658f) + X133 * F(0.513280f) + X135 * F(0.768178f) + X137 * F(-0.375330f)); - S.at(3, 3) = X136; - // 40 muls 24 adds - } - }; - } // end namespace DCT_Upsample - - // Unconditionally frees all allocated m_blocks. - void jpeg_decoder::free_all_blocks() - { - m_pStream = NULL; - for (mem_block *b = m_pMem_blocks; b; ) - { - mem_block *n = b->m_pNext; - jpgd_free(b); - b = n; - } - m_pMem_blocks = NULL; - } - - // This method handles all errors. - // It could easily be changed to use C++ exceptions. - void jpeg_decoder::stop_decoding(jpgd_status status) - { - m_error_code = status; - free_all_blocks(); - longjmp(m_jmp_state, status); - - // we shouldn't get here as longjmp shouldn't return, but we put it here to make it explicit - // that this function doesn't return, otherwise we get this error: - // - // error : function declared 'noreturn' should not return - exit(1); - } - - void *jpeg_decoder::alloc(size_t nSize, bool zero) - { - nSize = (JPGD_MAX(nSize, 1) + 3) & ~3; - char *rv = NULL; - for (mem_block *b = m_pMem_blocks; b; b = b->m_pNext) - { - if ((b->m_used_count + nSize) <= b->m_size) - { - rv = b->m_data + b->m_used_count; - b->m_used_count += nSize; - break; - } - } - if (!rv) - { - int capacity = JPGD_MAX(32768 - 256, (nSize + 2047) & ~2047); - mem_block *b = (mem_block*)jpgd_malloc(sizeof(mem_block) + capacity); - if (!b) stop_decoding(JPGD_NOTENOUGHMEM); - b->m_pNext = m_pMem_blocks; m_pMem_blocks = b; - b->m_used_count = nSize; - b->m_size = capacity; - rv = b->m_data; - } - if (zero) memset(rv, 0, nSize); - return rv; - } - - void jpeg_decoder::word_clear(void *p, uint16 c, uint n) - { - uint8 *pD = (uint8*)p; - const uint8 l = c & 0xFF, h = (c >> 8) & 0xFF; - while (n) - { - pD[0] = l; pD[1] = h; pD += 2; - n--; - } - } - - // Refill the input buffer. - // This method will sit in a loop until (A) the buffer is full or (B) - // the stream's read() method reports and end of file condition. - void jpeg_decoder::prep_in_buffer() - { - m_in_buf_left = 0; - m_pIn_buf_ofs = m_in_buf; - - if (m_eof_flag) - return; - - do - { - int bytes_read = m_pStream->read(m_in_buf + m_in_buf_left, JPGD_IN_BUF_SIZE - m_in_buf_left, &m_eof_flag); - if (bytes_read == -1) - stop_decoding(JPGD_STREAM_READ); - - m_in_buf_left += bytes_read; - } while ((m_in_buf_left < JPGD_IN_BUF_SIZE) && (!m_eof_flag)); - - m_total_bytes_read += m_in_buf_left; - - // Pad the end of the block with M_EOI (prevents the decompressor from going off the rails if the stream is invalid). - // (This dates way back to when this decompressor was written in C/asm, and the all-asm Huffman decoder did some fancy things to increase perf.) - word_clear(m_pIn_buf_ofs + m_in_buf_left, 0xD9FF, 64); - } - - // Read a Huffman code table. - void jpeg_decoder::read_dht_marker() - { - int i, index, count; - uint8 huff_num[17]; - uint8 huff_val[256]; - - uint num_left = get_bits(16); - - if (num_left < 2) - stop_decoding(JPGD_BAD_DHT_MARKER); - - num_left -= 2; - - while (num_left) - { - index = get_bits(8); - - huff_num[0] = 0; - - count = 0; - - for (i = 1; i <= 16; i++) - { - huff_num[i] = static_cast(get_bits(8)); - count += huff_num[i]; - } - - if (count > 255) - stop_decoding(JPGD_BAD_DHT_COUNTS); - - for (i = 0; i < count; i++) - huff_val[i] = static_cast(get_bits(8)); - - i = 1 + 16 + count; - - if (num_left < (uint)i) - stop_decoding(JPGD_BAD_DHT_MARKER); - - num_left -= i; - - if ((index & 0x10) > 0x10) - stop_decoding(JPGD_BAD_DHT_INDEX); - - index = (index & 0x0F) + ((index & 0x10) >> 4) * (JPGD_MAX_HUFF_TABLES >> 1); - - if (index >= JPGD_MAX_HUFF_TABLES) - stop_decoding(JPGD_BAD_DHT_INDEX); - - if (!m_huff_num[index]) - m_huff_num[index] = (uint8 *)alloc(17); - - if (!m_huff_val[index]) - m_huff_val[index] = (uint8 *)alloc(256); - - m_huff_ac[index] = (index & 0x10) != 0; - memcpy(m_huff_num[index], huff_num, 17); - memcpy(m_huff_val[index], huff_val, 256); - } - } - - // Read a quantization table. - void jpeg_decoder::read_dqt_marker() - { - int n, i, prec; - uint num_left; - uint temp; - - num_left = get_bits(16); - - if (num_left < 2) - stop_decoding(JPGD_BAD_DQT_MARKER); - - num_left -= 2; - - while (num_left) - { - n = get_bits(8); - prec = n >> 4; - n &= 0x0F; - - if (n >= JPGD_MAX_QUANT_TABLES) - stop_decoding(JPGD_BAD_DQT_TABLE); - - if (!m_quant[n]) - m_quant[n] = (jpgd_quant_t *)alloc(64 * sizeof(jpgd_quant_t)); - - // read quantization entries, in zag order - for (i = 0; i < 64; i++) - { - temp = get_bits(8); - - if (prec) - temp = (temp << 8) + get_bits(8); - - m_quant[n][i] = static_cast(temp); - } - - i = 64 + 1; - - if (prec) - i += 64; - - if (num_left < (uint)i) - stop_decoding(JPGD_BAD_DQT_LENGTH); - - num_left -= i; - } - } - - // Read the start of frame (SOF) marker. - void jpeg_decoder::read_sof_marker() - { - int i; - uint num_left; - - num_left = get_bits(16); - - if (get_bits(8) != 8) /* precision: sorry, only 8-bit precision is supported right now */ - stop_decoding(JPGD_BAD_PRECISION); - - m_image_y_size = get_bits(16); - - if ((m_image_y_size < 1) || (m_image_y_size > JPGD_MAX_HEIGHT)) - stop_decoding(JPGD_BAD_HEIGHT); - - m_image_x_size = get_bits(16); - - if ((m_image_x_size < 1) || (m_image_x_size > JPGD_MAX_WIDTH)) - stop_decoding(JPGD_BAD_WIDTH); - - m_comps_in_frame = get_bits(8); - - if (m_comps_in_frame > JPGD_MAX_COMPONENTS) - stop_decoding(JPGD_TOO_MANY_COMPONENTS); - - if (num_left != (uint)(m_comps_in_frame * 3 + 8)) - stop_decoding(JPGD_BAD_SOF_LENGTH); - - for (i = 0; i < m_comps_in_frame; i++) - { - m_comp_ident[i] = get_bits(8); - m_comp_h_samp[i] = get_bits(4); - m_comp_v_samp[i] = get_bits(4); - m_comp_quant[i] = get_bits(8); - } - } - - // Used to skip unrecognized markers. - void jpeg_decoder::skip_variable_marker() - { - uint num_left; - - num_left = get_bits(16); - - if (num_left < 2) - stop_decoding(JPGD_BAD_VARIABLE_MARKER); - - num_left -= 2; - - while (num_left) - { - get_bits(8); - num_left--; - } - } - - // Read a define restart interval (DRI) marker. - void jpeg_decoder::read_dri_marker() - { - if (get_bits(16) != 4) - stop_decoding(JPGD_BAD_DRI_LENGTH); - - m_restart_interval = get_bits(16); - } - - // Read a start of scan (SOS) marker. - void jpeg_decoder::read_sos_marker() - { - uint num_left; - int i, ci, n, c, cc; - - num_left = get_bits(16); - - n = get_bits(8); - - m_comps_in_scan = n; - - num_left -= 3; - - if ( (num_left != (uint)(n * 2 + 3)) || (n < 1) || (n > JPGD_MAX_COMPS_IN_SCAN) ) - stop_decoding(JPGD_BAD_SOS_LENGTH); - - for (i = 0; i < n; i++) - { - cc = get_bits(8); - c = get_bits(8); - num_left -= 2; - - for (ci = 0; ci < m_comps_in_frame; ci++) - if (cc == m_comp_ident[ci]) - break; - - if (ci >= m_comps_in_frame) - stop_decoding(JPGD_BAD_SOS_COMP_ID); - - m_comp_list[i] = ci; - m_comp_dc_tab[ci] = (c >> 4) & 15; - m_comp_ac_tab[ci] = (c & 15) + (JPGD_MAX_HUFF_TABLES >> 1); - } - - m_spectral_start = get_bits(8); - m_spectral_end = get_bits(8); - m_successive_high = get_bits(4); - m_successive_low = get_bits(4); - - if (!m_progressive_flag) - { - m_spectral_start = 0; - m_spectral_end = 63; - } - - num_left -= 3; - - while (num_left) /* read past whatever is num_left */ - { - get_bits(8); - num_left--; - } - } - - // Finds the next marker. - int jpeg_decoder::next_marker() - { - uint c, bytes; - - bytes = 0; - - do - { - do - { - bytes++; - c = get_bits(8); - } while (c != 0xFF); - - do - { - c = get_bits(8); - } while (c == 0xFF); - - } while (c == 0); - - // If bytes > 0 here, there where extra bytes before the marker (not good). - - return c; - } - - // Process markers. Returns when an SOFx, SOI, EOI, or SOS marker is - // encountered. - int jpeg_decoder::process_markers() - { - int c; - - for ( ; ; ) - { - c = next_marker(); - - switch (c) - { - case M_SOF0: - case M_SOF1: - case M_SOF2: - case M_SOF3: - case M_SOF5: - case M_SOF6: - case M_SOF7: - // case M_JPG: - case M_SOF9: - case M_SOF10: - case M_SOF11: - case M_SOF13: - case M_SOF14: - case M_SOF15: - case M_SOI: - case M_EOI: - case M_SOS: - { - return c; - } - case M_DHT: - { - read_dht_marker(); - break; - } - // No arithmitic support - dumb patents! - case M_DAC: - { - stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT); - break; - } - case M_DQT: - { - read_dqt_marker(); - break; - } - case M_DRI: - { - read_dri_marker(); - break; - } - //case M_APP0: /* no need to read the JFIF marker */ - - case M_JPG: - case M_RST0: /* no parameters */ - case M_RST1: - case M_RST2: - case M_RST3: - case M_RST4: - case M_RST5: - case M_RST6: - case M_RST7: - case M_TEM: - { - stop_decoding(JPGD_UNEXPECTED_MARKER); - break; - } - default: /* must be DNL, DHP, EXP, APPn, JPGn, COM, or RESn or APP0 */ - { - skip_variable_marker(); - break; - } - } - } - } - - // Finds the start of image (SOI) marker. - // This code is rather defensive: it only checks the first 512 bytes to avoid - // false positives. - void jpeg_decoder::locate_soi_marker() - { - uint lastchar, thischar; - uint bytesleft; - - lastchar = get_bits(8); - - thischar = get_bits(8); - - /* ok if it's a normal JPEG file without a special header */ - - if ((lastchar == 0xFF) && (thischar == M_SOI)) - return; - - bytesleft = 4096; //512; - - for ( ; ; ) - { - if (--bytesleft == 0) - stop_decoding(JPGD_NOT_JPEG); - - lastchar = thischar; - - thischar = get_bits(8); - - if (lastchar == 0xFF) - { - if (thischar == M_SOI) - break; - else if (thischar == M_EOI) // get_bits will keep returning M_EOI if we read past the end - stop_decoding(JPGD_NOT_JPEG); - } - } - - // Check the next character after marker: if it's not 0xFF, it can't be the start of the next marker, so the file is bad. - thischar = (m_bit_buf >> 24) & 0xFF; - - if (thischar != 0xFF) - stop_decoding(JPGD_NOT_JPEG); - } - - // Find a start of frame (SOF) marker. - void jpeg_decoder::locate_sof_marker() - { - locate_soi_marker(); - - int c = process_markers(); - - switch (c) - { - case M_SOF2: - m_progressive_flag = JPGD_TRUE; - case M_SOF0: /* baseline DCT */ - case M_SOF1: /* extended sequential DCT */ - { - read_sof_marker(); - break; - } - case M_SOF9: /* Arithmitic coding */ - { - stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT); - break; - } - default: - { - stop_decoding(JPGD_UNSUPPORTED_MARKER); - break; - } - } - } - - // Find a start of scan (SOS) marker. - int jpeg_decoder::locate_sos_marker() - { - int c; - - c = process_markers(); - - if (c == M_EOI) - return JPGD_FALSE; - else if (c != M_SOS) - stop_decoding(JPGD_UNEXPECTED_MARKER); - - read_sos_marker(); - - return JPGD_TRUE; - } - - // Reset everything to default/uninitialized state. - void jpeg_decoder::init(jpeg_decoder_stream *pStream) - { - m_pMem_blocks = NULL; - m_error_code = JPGD_SUCCESS; - m_ready_flag = false; - m_image_x_size = m_image_y_size = 0; - m_pStream = pStream; - m_progressive_flag = JPGD_FALSE; - - memset(m_huff_ac, 0, sizeof(m_huff_ac)); - memset(m_huff_num, 0, sizeof(m_huff_num)); - memset(m_huff_val, 0, sizeof(m_huff_val)); - memset(m_quant, 0, sizeof(m_quant)); - - m_scan_type = 0; - m_comps_in_frame = 0; - - memset(m_comp_h_samp, 0, sizeof(m_comp_h_samp)); - memset(m_comp_v_samp, 0, sizeof(m_comp_v_samp)); - memset(m_comp_quant, 0, sizeof(m_comp_quant)); - memset(m_comp_ident, 0, sizeof(m_comp_ident)); - memset(m_comp_h_blocks, 0, sizeof(m_comp_h_blocks)); - memset(m_comp_v_blocks, 0, sizeof(m_comp_v_blocks)); - - m_comps_in_scan = 0; - memset(m_comp_list, 0, sizeof(m_comp_list)); - memset(m_comp_dc_tab, 0, sizeof(m_comp_dc_tab)); - memset(m_comp_ac_tab, 0, sizeof(m_comp_ac_tab)); - - m_spectral_start = 0; - m_spectral_end = 0; - m_successive_low = 0; - m_successive_high = 0; - m_max_mcu_x_size = 0; - m_max_mcu_y_size = 0; - m_blocks_per_mcu = 0; - m_max_blocks_per_row = 0; - m_mcus_per_row = 0; - m_mcus_per_col = 0; - m_expanded_blocks_per_component = 0; - m_expanded_blocks_per_mcu = 0; - m_expanded_blocks_per_row = 0; - m_freq_domain_chroma_upsample = false; - - memset(m_mcu_org, 0, sizeof(m_mcu_org)); - - m_total_lines_left = 0; - m_mcu_lines_left = 0; - m_real_dest_bytes_per_scan_line = 0; - m_dest_bytes_per_scan_line = 0; - m_dest_bytes_per_pixel = 0; - - memset(m_pHuff_tabs, 0, sizeof(m_pHuff_tabs)); - - memset(m_dc_coeffs, 0, sizeof(m_dc_coeffs)); - memset(m_ac_coeffs, 0, sizeof(m_ac_coeffs)); - memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu)); - - m_eob_run = 0; - - memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu)); - - m_pIn_buf_ofs = m_in_buf; - m_in_buf_left = 0; - m_eof_flag = false; - m_tem_flag = 0; - - memset(m_in_buf_pad_start, 0, sizeof(m_in_buf_pad_start)); - memset(m_in_buf, 0, sizeof(m_in_buf)); - memset(m_in_buf_pad_end, 0, sizeof(m_in_buf_pad_end)); - - m_restart_interval = 0; - m_restarts_left = 0; - m_next_restart_num = 0; - - m_max_mcus_per_row = 0; - m_max_blocks_per_mcu = 0; - m_max_mcus_per_col = 0; - - memset(m_last_dc_val, 0, sizeof(m_last_dc_val)); - m_pMCU_coefficients = NULL; - m_pSample_buf = NULL; - - m_total_bytes_read = 0; - - m_pScan_line_0 = NULL; - m_pScan_line_1 = NULL; - - // Ready the input buffer. - prep_in_buffer(); - - // Prime the bit buffer. - m_bits_left = 16; - m_bit_buf = 0; - - get_bits(16); - get_bits(16); - - for (int i = 0; i < JPGD_MAX_BLOCKS_PER_MCU; i++) - m_mcu_block_max_zag[i] = 64; - } - -#define SCALEBITS 16 -#define ONE_HALF ((int) 1 << (SCALEBITS-1)) -#define FIX(x) ((int) ((x) * (1L<> SCALEBITS; - m_cbb[i] = ( FIX(1.77200f) * k + ONE_HALF) >> SCALEBITS; - m_crg[i] = (-FIX(0.71414f)) * k; - m_cbg[i] = (-FIX(0.34414f)) * k + ONE_HALF; - } - } - - // This method throws back into the stream any bytes that where read - // into the bit buffer during initial marker scanning. - void jpeg_decoder::fix_in_buffer() - { - // In case any 0xFF's where pulled into the buffer during marker scanning. - JPGD_ASSERT((m_bits_left & 7) == 0); - - if (m_bits_left == 16) - stuff_char( (uint8)(m_bit_buf & 0xFF)); - - if (m_bits_left >= 8) - stuff_char( (uint8)((m_bit_buf >> 8) & 0xFF)); - - stuff_char((uint8)((m_bit_buf >> 16) & 0xFF)); - stuff_char((uint8)((m_bit_buf >> 24) & 0xFF)); - - m_bits_left = 16; - get_bits_no_markers(16); - get_bits_no_markers(16); - } - - void jpeg_decoder::transform_mcu(int mcu_row) - { - jpgd_block_t* pSrc_ptr = m_pMCU_coefficients; - uint8* pDst_ptr = m_pSample_buf + mcu_row * m_blocks_per_mcu * 64; - - for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++) - { - idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]); - pSrc_ptr += 64; - pDst_ptr += 64; - } - } - - static const uint8 s_max_rc[64] = - { - 17, 18, 34, 50, 50, 51, 52, 52, 52, 68, 84, 84, 84, 84, 85, 86, 86, 86, 86, 86, - 102, 118, 118, 118, 118, 118, 118, 119, 120, 120, 120, 120, 120, 120, 120, 136, - 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, - 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136 - }; - - void jpeg_decoder::transform_mcu_expand(int mcu_row) - { - jpgd_block_t* pSrc_ptr = m_pMCU_coefficients; - uint8* pDst_ptr = m_pSample_buf + mcu_row * m_expanded_blocks_per_mcu * 64; - - // Y IDCT - int mcu_block; - for (mcu_block = 0; mcu_block < m_expanded_blocks_per_component; mcu_block++) - { - idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]); - pSrc_ptr += 64; - pDst_ptr += 64; - } - - // Chroma IDCT, with upsampling - jpgd_block_t temp_block[64]; - - for (int i = 0; i < 2; i++) - { - DCT_Upsample::Matrix44 P, Q, R, S; - - JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] >= 1); - JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] <= 64); - - switch (s_max_rc[m_mcu_block_max_zag[mcu_block++] - 1]) - { - case 1*16+1: - DCT_Upsample::P_Q<1, 1>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<1, 1>::calc(R, S, pSrc_ptr); - break; - case 1*16+2: - DCT_Upsample::P_Q<1, 2>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<1, 2>::calc(R, S, pSrc_ptr); - break; - case 2*16+2: - DCT_Upsample::P_Q<2, 2>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<2, 2>::calc(R, S, pSrc_ptr); - break; - case 3*16+2: - DCT_Upsample::P_Q<3, 2>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<3, 2>::calc(R, S, pSrc_ptr); - break; - case 3*16+3: - DCT_Upsample::P_Q<3, 3>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<3, 3>::calc(R, S, pSrc_ptr); - break; - case 3*16+4: - DCT_Upsample::P_Q<3, 4>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<3, 4>::calc(R, S, pSrc_ptr); - break; - case 4*16+4: - DCT_Upsample::P_Q<4, 4>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<4, 4>::calc(R, S, pSrc_ptr); - break; - case 5*16+4: - DCT_Upsample::P_Q<5, 4>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<5, 4>::calc(R, S, pSrc_ptr); - break; - case 5*16+5: - DCT_Upsample::P_Q<5, 5>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<5, 5>::calc(R, S, pSrc_ptr); - break; - case 5*16+6: - DCT_Upsample::P_Q<5, 6>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<5, 6>::calc(R, S, pSrc_ptr); - break; - case 6*16+6: - DCT_Upsample::P_Q<6, 6>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<6, 6>::calc(R, S, pSrc_ptr); - break; - case 7*16+6: - DCT_Upsample::P_Q<7, 6>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<7, 6>::calc(R, S, pSrc_ptr); - break; - case 7*16+7: - DCT_Upsample::P_Q<7, 7>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<7, 7>::calc(R, S, pSrc_ptr); - break; - case 7*16+8: - DCT_Upsample::P_Q<7, 8>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<7, 8>::calc(R, S, pSrc_ptr); - break; - case 8*16+8: - DCT_Upsample::P_Q<8, 8>::calc(P, Q, pSrc_ptr); - DCT_Upsample::R_S<8, 8>::calc(R, S, pSrc_ptr); - break; - default: - JPGD_ASSERT(false); - } - - DCT_Upsample::Matrix44 a(P + Q); P -= Q; - DCT_Upsample::Matrix44& b = P; - DCT_Upsample::Matrix44 c(R + S); R -= S; - DCT_Upsample::Matrix44& d = R; - - DCT_Upsample::Matrix44::add_and_store(temp_block, a, c); - idct_4x4(temp_block, pDst_ptr); - pDst_ptr += 64; - - DCT_Upsample::Matrix44::sub_and_store(temp_block, a, c); - idct_4x4(temp_block, pDst_ptr); - pDst_ptr += 64; - - DCT_Upsample::Matrix44::add_and_store(temp_block, b, d); - idct_4x4(temp_block, pDst_ptr); - pDst_ptr += 64; - - DCT_Upsample::Matrix44::sub_and_store(temp_block, b, d); - idct_4x4(temp_block, pDst_ptr); - pDst_ptr += 64; - - pSrc_ptr += 64; - } - } - - // Loads and dequantizes the next row of (already decoded) coefficients. - // Progressive images only. - void jpeg_decoder::load_next_row() - { - int i; - jpgd_block_t *p; - jpgd_quant_t *q; - int mcu_row, mcu_block, row_block = 0; - int component_num, component_id; - int block_x_mcu[JPGD_MAX_COMPONENTS]; - - memset(block_x_mcu, 0, JPGD_MAX_COMPONENTS * sizeof(int)); - - for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++) - { - int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0; - - for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++) - { - component_id = m_mcu_org[mcu_block]; - q = m_quant[m_comp_quant[component_id]]; - - p = m_pMCU_coefficients + 64 * mcu_block; - - jpgd_block_t* pAC = coeff_buf_getp(m_ac_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs); - jpgd_block_t* pDC = coeff_buf_getp(m_dc_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs); - p[0] = pDC[0]; - memcpy(&p[1], &pAC[1], 63 * sizeof(jpgd_block_t)); - - for (i = 63; i > 0; i--) - if (p[g_ZAG[i]]) - break; - - m_mcu_block_max_zag[mcu_block] = i + 1; - - for ( ; i >= 0; i--) - if (p[g_ZAG[i]]) - p[g_ZAG[i]] = static_cast(p[g_ZAG[i]] * q[i]); - - row_block++; - - if (m_comps_in_scan == 1) - block_x_mcu[component_id]++; - else - { - if (++block_x_mcu_ofs == m_comp_h_samp[component_id]) - { - block_x_mcu_ofs = 0; - - if (++block_y_mcu_ofs == m_comp_v_samp[component_id]) - { - block_y_mcu_ofs = 0; - - block_x_mcu[component_id] += m_comp_h_samp[component_id]; - } - } - } - } - - if (m_freq_domain_chroma_upsample) - transform_mcu_expand(mcu_row); - else - transform_mcu(mcu_row); - } - - if (m_comps_in_scan == 1) - m_block_y_mcu[m_comp_list[0]]++; - else - { - for (component_num = 0; component_num < m_comps_in_scan; component_num++) - { - component_id = m_comp_list[component_num]; - - m_block_y_mcu[component_id] += m_comp_v_samp[component_id]; - } - } - } - - // Restart interval processing. - void jpeg_decoder::process_restart() - { - int i; - int c = 0; - - // Align to a byte boundry - // FIXME: Is this really necessary? get_bits_no_markers() never reads in markers! - //get_bits_no_markers(m_bits_left & 7); - - // Let's scan a little bit to find the marker, but not _too_ far. - // 1536 is a "fudge factor" that determines how much to scan. - for (i = 1536; i > 0; i--) - if (get_char() == 0xFF) - break; - - if (i == 0) - stop_decoding(JPGD_BAD_RESTART_MARKER); - - for ( ; i > 0; i--) - if ((c = get_char()) != 0xFF) - break; - - if (i == 0) - stop_decoding(JPGD_BAD_RESTART_MARKER); - - // Is it the expected marker? If not, something bad happened. - if (c != (m_next_restart_num + M_RST0)) - stop_decoding(JPGD_BAD_RESTART_MARKER); - - // Reset each component's DC prediction values. - memset(&m_last_dc_val, 0, m_comps_in_frame * sizeof(uint)); - - m_eob_run = 0; - - m_restarts_left = m_restart_interval; - - m_next_restart_num = (m_next_restart_num + 1) & 7; - - // Get the bit buffer going again... - - m_bits_left = 16; - get_bits_no_markers(16); - get_bits_no_markers(16); - } - - static inline int dequantize_ac(int c, int q) { c *= q; return c; } - - // Decodes and dequantizes the next row of coefficients. - void jpeg_decoder::decode_next_row() - { - int row_block = 0; - - for (int mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++) - { - if ((m_restart_interval) && (m_restarts_left == 0)) - process_restart(); - - jpgd_block_t* p = m_pMCU_coefficients; - for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++, p += 64) - { - int component_id = m_mcu_org[mcu_block]; - jpgd_quant_t* q = m_quant[m_comp_quant[component_id]]; - - int r, s; - s = huff_decode(m_pHuff_tabs[m_comp_dc_tab[component_id]], r); - s = HUFF_EXTEND(r, s); - - m_last_dc_val[component_id] = (s += m_last_dc_val[component_id]); - - p[0] = static_cast(s * q[0]); - - int prev_num_set = m_mcu_block_max_zag[mcu_block]; - - huff_tables *pH = m_pHuff_tabs[m_comp_ac_tab[component_id]]; - - int k; - for (k = 1; k < 64; k++) - { - int extra_bits; - s = huff_decode(pH, extra_bits); - - r = s >> 4; - s &= 15; - - if (s) - { - if (r) - { - if ((k + r) > 63) - stop_decoding(JPGD_DECODE_ERROR); - - if (k < prev_num_set) - { - int n = JPGD_MIN(r, prev_num_set - k); - int kt = k; - while (n--) - p[g_ZAG[kt++]] = 0; - } - - k += r; - } - - s = HUFF_EXTEND(extra_bits, s); - - JPGD_ASSERT(k < 64); - - p[g_ZAG[k]] = static_cast(dequantize_ac(s, q[k])); //s * q[k]; - } - else - { - if (r == 15) - { - if ((k + 16) > 64) - stop_decoding(JPGD_DECODE_ERROR); - - if (k < prev_num_set) - { - int n = JPGD_MIN(16, prev_num_set - k); - int kt = k; - while (n--) - { - JPGD_ASSERT(kt <= 63); - p[g_ZAG[kt++]] = 0; - } - } - - k += 16 - 1; // - 1 because the loop counter is k - // BEGIN EPIC MOD - JPGD_ASSERT(k < 64 && p[g_ZAG[k]] == 0); - // END EPIC MOD - } - else - break; - } - } - - if (k < prev_num_set) - { - int kt = k; - while (kt < prev_num_set) - p[g_ZAG[kt++]] = 0; - } - - m_mcu_block_max_zag[mcu_block] = k; - - row_block++; - } - - if (m_freq_domain_chroma_upsample) - transform_mcu_expand(mcu_row); - else - transform_mcu(mcu_row); - - m_restarts_left--; - } - } - - // YCbCr H1V1 (1x1:1:1, 3 m_blocks per MCU) to RGB - void jpeg_decoder::H1V1Convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d = m_pScan_line_0; - uint8 *s = m_pSample_buf + row * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int j = 0; j < 8; j++) - { - int y = s[j]; - int cb = s[64+j]; - int cr = s[128+j]; - - if (jpg_format == ERGBFormatJPG::BGRA) - { - d[0] = clamp(y + m_cbb[cb]); - d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16)); - d[2] = clamp(y + m_crr[cr]); - d[3] = 255; - } - else - { - d[0] = clamp(y + m_crr[cr]); - d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16)); - d[2] = clamp(y + m_cbb[cb]); - d[3] = 255; - } - d += 4; - } - - s += 64*3; - } - } - - // YCbCr H2V1 (2x1:1:1, 4 m_blocks per MCU) to RGB - void jpeg_decoder::H2V1Convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d0 = m_pScan_line_0; - uint8 *y = m_pSample_buf + row * 8; - uint8 *c = m_pSample_buf + 2*64 + row * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int l = 0; l < 2; l++) - { - for (int j = 0; j < 4; j++) - { - int cb = c[0]; - int cr = c[64]; - - int rc = m_crr[cr]; - int gc = ((m_crg[cr] + m_cbg[cb]) >> 16); - int bc = m_cbb[cb]; - - int yy = y[j<<1]; - if (jpg_format == ERGBFormatJPG::BGRA) - { - d0[0] = clamp(yy+bc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+rc); - d0[3] = 255; - yy = y[(j<<1)+1]; - d0[4] = clamp(yy+bc); - d0[5] = clamp(yy+gc); - d0[6] = clamp(yy+rc); - d0[7] = 255; - } - else - { - d0[0] = clamp(yy+rc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+bc); - d0[3] = 255; - yy = y[(j<<1)+1]; - d0[4] = clamp(yy+rc); - d0[5] = clamp(yy+gc); - d0[6] = clamp(yy+bc); - d0[7] = 255; - } - - d0 += 8; - - c++; - } - y += 64; - } - - y += 64*4 - 64*2; - c += 64*4 - 8; - } - } - - // YCbCr H2V1 (1x2:1:1, 4 m_blocks per MCU) to RGB - void jpeg_decoder::H1V2Convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d0 = m_pScan_line_0; - uint8 *d1 = m_pScan_line_1; - uint8 *y; - uint8 *c; - - if (row < 8) - y = m_pSample_buf + row * 8; - else - y = m_pSample_buf + 64*1 + (row & 7) * 8; - - c = m_pSample_buf + 64*2 + (row >> 1) * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int j = 0; j < 8; j++) - { - int cb = c[0+j]; - int cr = c[64+j]; - - int rc = m_crr[cr]; - int gc = ((m_crg[cr] + m_cbg[cb]) >> 16); - int bc = m_cbb[cb]; - - int yy = y[j]; - if (jpg_format == ERGBFormatJPG::BGRA) - { - d0[0] = clamp(yy+bc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+rc); - d0[3] = 255; - yy = y[8+j]; - d1[0] = clamp(yy+bc); - d1[1] = clamp(yy+gc); - d1[2] = clamp(yy+rc); - d1[3] = 255; - } - else - { - d0[0] = clamp(yy+rc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+bc); - d0[3] = 255; - yy = y[8+j]; - d1[0] = clamp(yy+rc); - d1[1] = clamp(yy+gc); - d1[2] = clamp(yy+bc); - d1[3] = 255; - } - - d0 += 4; - d1 += 4; - } - - y += 64*4; - c += 64*4; - } - } - - // YCbCr H2V2 (2x2:1:1, 6 m_blocks per MCU) to RGB - void jpeg_decoder::H2V2Convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d0 = m_pScan_line_0; - uint8 *d1 = m_pScan_line_1; - uint8 *y; - uint8 *c; - - if (row < 8) - y = m_pSample_buf + row * 8; - else - y = m_pSample_buf + 64*2 + (row & 7) * 8; - - c = m_pSample_buf + 64*4 + (row >> 1) * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int l = 0; l < 2; l++) - { - for (int j = 0; j < 8; j += 2) - { - int cb = c[0]; - int cr = c[64]; - - int rc = m_crr[cr]; - int gc = ((m_crg[cr] + m_cbg[cb]) >> 16); - int bc = m_cbb[cb]; - - int yy = y[j]; - if (jpg_format == ERGBFormatJPG::BGRA) - { - d0[0] = clamp(yy+bc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+rc); - d0[3] = 255; - yy = y[j+1]; - d0[4] = clamp(yy+bc); - d0[5] = clamp(yy+gc); - d0[6] = clamp(yy+rc); - d0[7] = 255; - yy = y[j+8]; - d1[0] = clamp(yy+bc); - d1[1] = clamp(yy+gc); - d1[2] = clamp(yy+rc); - d1[3] = 255; - yy = y[j+8+1]; - d1[4] = clamp(yy+bc); - d1[5] = clamp(yy+gc); - d1[6] = clamp(yy+rc); - d1[7] = 255; - } - else - { - d0[0] = clamp(yy+rc); - d0[1] = clamp(yy+gc); - d0[2] = clamp(yy+bc); - d0[3] = 255; - yy = y[j+1]; - d0[4] = clamp(yy+rc); - d0[5] = clamp(yy+gc); - d0[6] = clamp(yy+bc); - d0[7] = 255; - yy = y[j+8]; - d1[0] = clamp(yy+rc); - d1[1] = clamp(yy+gc); - d1[2] = clamp(yy+bc); - d1[3] = 255; - yy = y[j+8+1]; - d1[4] = clamp(yy+rc); - d1[5] = clamp(yy+gc); - d1[6] = clamp(yy+bc); - d1[7] = 255; - } - - d0 += 8; - d1 += 8; - - c++; - } - y += 64; - } - - y += 64*6 - 64*2; - c += 64*6 - 8; - } - } - - // Y (1 block per MCU) to 8-bit grayscale - void jpeg_decoder::gray_convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - uint8 *d = m_pScan_line_0; - uint8 *s = m_pSample_buf + row * 8; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - *(uint *)d = *(uint *)s; - *(uint *)(&d[4]) = *(uint *)(&s[4]); - - s += 64; - d += 8; - } - } - - void jpeg_decoder::expanded_convert() - { - int row = m_max_mcu_y_size - m_mcu_lines_left; - - uint8* Py = m_pSample_buf + (row / 8) * 64 * m_comp_h_samp[0] + (row & 7) * 8; - - uint8* d = m_pScan_line_0; - - for (int i = m_max_mcus_per_row; i > 0; i--) - { - for (int k = 0; k < m_max_mcu_x_size; k += 8) - { - const int Y_ofs = k * 8; - const int Cb_ofs = Y_ofs + 64 * m_expanded_blocks_per_component; - const int Cr_ofs = Y_ofs + 64 * m_expanded_blocks_per_component * 2; - for (int j = 0; j < 8; j++) - { - int y = Py[Y_ofs + j]; - int cb = Py[Cb_ofs + j]; - int cr = Py[Cr_ofs + j]; - - if (jpg_format == ERGBFormatJPG::BGRA) - { - d[0] = clamp(y + m_cbb[cb]); - d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16)); - d[2] = clamp(y + m_crr[cr]); - d[3] = 255; - } - else - { - d[0] = clamp(y + m_crr[cr]); - d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16)); - d[2] = clamp(y + m_cbb[cb]); - d[3] = 255; - } - - d += 4; - } - } - - Py += 64 * m_expanded_blocks_per_mcu; - } - } - - // Find end of image (EOI) marker, so we can return to the user the exact size of the input stream. - void jpeg_decoder::find_eoi() - { - if (!m_progressive_flag) - { - // Attempt to read the EOI marker. - //get_bits_no_markers(m_bits_left & 7); - - // Prime the bit buffer - m_bits_left = 16; - get_bits(16); - get_bits(16); - - // The next marker _should_ be EOI - process_markers(); - } - - m_total_bytes_read -= m_in_buf_left; - } - - int jpeg_decoder::decode(const void** pScan_line, uint* pScan_line_len) - { - if ((m_error_code) || (!m_ready_flag)) - return JPGD_FAILED; - - if (m_total_lines_left == 0) - return JPGD_DONE; - - if (m_mcu_lines_left == 0) - { - if (setjmp(m_jmp_state)) - return JPGD_FAILED; - - if (m_progressive_flag) - load_next_row(); - else - decode_next_row(); - - // Find the EOI marker if that was the last row. - if (m_total_lines_left <= m_max_mcu_y_size) - find_eoi(); - - m_mcu_lines_left = m_max_mcu_y_size; - } - - if (m_freq_domain_chroma_upsample) - { - expanded_convert(); - *pScan_line = m_pScan_line_0; - } - else - { - switch (m_scan_type) - { - case JPGD_YH2V2: - { - if ((m_mcu_lines_left & 1) == 0) - { - H2V2Convert(); - *pScan_line = m_pScan_line_0; - } - else - *pScan_line = m_pScan_line_1; - - break; - } - case JPGD_YH2V1: - { - H2V1Convert(); - *pScan_line = m_pScan_line_0; - break; - } - case JPGD_YH1V2: - { - if ((m_mcu_lines_left & 1) == 0) - { - H1V2Convert(); - *pScan_line = m_pScan_line_0; - } - else - *pScan_line = m_pScan_line_1; - - break; - } - case JPGD_YH1V1: - { - H1V1Convert(); - *pScan_line = m_pScan_line_0; - break; - } - case JPGD_GRAYSCALE: - { - gray_convert(); - *pScan_line = m_pScan_line_0; - - break; - } - } - } - - *pScan_line_len = m_real_dest_bytes_per_scan_line; - - m_mcu_lines_left--; - m_total_lines_left--; - - return JPGD_SUCCESS; - } - - // Creates the tables needed for efficient Huffman decoding. - void jpeg_decoder::make_huff_table(int index, huff_tables *pH) - { - int p, i, l, si; - uint8 huffsize[257]; - uint huffcode[257]; - uint code; - uint subtree; - int code_size; - int lastp; - int nextfreeentry; - int currententry; - - pH->ac_table = m_huff_ac[index] != 0; - - p = 0; - - for (l = 1; l <= 16; l++) - { - for (i = 1; i <= m_huff_num[index][l]; i++) - huffsize[p++] = static_cast(l); - } - - huffsize[p] = 0; - - lastp = p; - - code = 0; - si = huffsize[0]; - p = 0; - - while (huffsize[p]) - { - while (huffsize[p] == si) - { - huffcode[p++] = code; - code++; - } - - code <<= 1; - si++; - } - - memset(pH->look_up, 0, sizeof(pH->look_up)); - memset(pH->look_up2, 0, sizeof(pH->look_up2)); - memset(pH->tree, 0, sizeof(pH->tree)); - memset(pH->code_size, 0, sizeof(pH->code_size)); - - nextfreeentry = -1; - - p = 0; - - while (p < lastp) - { - i = m_huff_val[index][p]; - code = huffcode[p]; - code_size = huffsize[p]; - - pH->code_size[i] = static_cast(code_size); - - if (code_size <= 8) - { - code <<= (8 - code_size); - - for (l = 1 << (8 - code_size); l > 0; l--) - { - JPGD_ASSERT(i < 256); - - pH->look_up[code] = i; - - bool has_extrabits = false; - int extra_bits = 0; - int num_extra_bits = i & 15; - - int bits_to_fetch = code_size; - if (num_extra_bits) - { - int total_codesize = code_size + num_extra_bits; - if (total_codesize <= 8) - { - has_extrabits = true; - extra_bits = ((1 << num_extra_bits) - 1) & (code >> (8 - total_codesize)); - JPGD_ASSERT(extra_bits <= 0x7FFF); - bits_to_fetch += num_extra_bits; - } - } - - if (!has_extrabits) - pH->look_up2[code] = i | (bits_to_fetch << 8); - else - pH->look_up2[code] = i | 0x8000 | (extra_bits << 16) | (bits_to_fetch << 8); - - code++; - } - } - else - { - subtree = (code >> (code_size - 8)) & 0xFF; - - currententry = pH->look_up[subtree]; - - if (currententry == 0) - { - pH->look_up[subtree] = currententry = nextfreeentry; - pH->look_up2[subtree] = currententry = nextfreeentry; - - nextfreeentry -= 2; - } - - code <<= (16 - (code_size - 8)); - - for (l = code_size; l > 9; l--) - { - if ((code & 0x8000) == 0) - currententry--; - - if (pH->tree[-currententry - 1] == 0) - { - pH->tree[-currententry - 1] = nextfreeentry; - - currententry = nextfreeentry; - - nextfreeentry -= 2; - } - else - currententry = pH->tree[-currententry - 1]; - - code <<= 1; - } - - if ((code & 0x8000) == 0) - currententry--; - - pH->tree[-currententry - 1] = i; - } - - p++; - } - } - - // Verifies the quantization tables needed for this scan are available. - void jpeg_decoder::check_quant_tables() - { - for (int i = 0; i < m_comps_in_scan; i++) - if (m_quant[m_comp_quant[m_comp_list[i]]] == NULL) - stop_decoding(JPGD_UNDEFINED_QUANT_TABLE); - } - - // Verifies that all the Huffman tables needed for this scan are available. - void jpeg_decoder::check_huff_tables() - { - for (int i = 0; i < m_comps_in_scan; i++) - { - if ((m_spectral_start == 0) && (m_huff_num[m_comp_dc_tab[m_comp_list[i]]] == NULL)) - stop_decoding(JPGD_UNDEFINED_HUFF_TABLE); - - if ((m_spectral_end > 0) && (m_huff_num[m_comp_ac_tab[m_comp_list[i]]] == NULL)) - stop_decoding(JPGD_UNDEFINED_HUFF_TABLE); - } - - for (int i = 0; i < JPGD_MAX_HUFF_TABLES; i++) - if (m_huff_num[i]) - { - if (!m_pHuff_tabs[i]) - m_pHuff_tabs[i] = (huff_tables *)alloc(sizeof(huff_tables)); - - make_huff_table(i, m_pHuff_tabs[i]); - } - } - - // Determines the component order inside each MCU. - // Also calcs how many MCU's are on each row, etc. - void jpeg_decoder::calc_mcu_block_order() - { - int component_num, component_id; - int max_h_samp = 0, max_v_samp = 0; - - for (component_id = 0; component_id < m_comps_in_frame; component_id++) - { - if (m_comp_h_samp[component_id] > max_h_samp) - max_h_samp = m_comp_h_samp[component_id]; - - if (m_comp_v_samp[component_id] > max_v_samp) - max_v_samp = m_comp_v_samp[component_id]; - } - - for (component_id = 0; component_id < m_comps_in_frame; component_id++) - { - m_comp_h_blocks[component_id] = ((((m_image_x_size * m_comp_h_samp[component_id]) + (max_h_samp - 1)) / max_h_samp) + 7) / 8; - m_comp_v_blocks[component_id] = ((((m_image_y_size * m_comp_v_samp[component_id]) + (max_v_samp - 1)) / max_v_samp) + 7) / 8; - } - - if (m_comps_in_scan == 1) - { - m_mcus_per_row = m_comp_h_blocks[m_comp_list[0]]; - m_mcus_per_col = m_comp_v_blocks[m_comp_list[0]]; - } - else - { - m_mcus_per_row = (((m_image_x_size + 7) / 8) + (max_h_samp - 1)) / max_h_samp; - m_mcus_per_col = (((m_image_y_size + 7) / 8) + (max_v_samp - 1)) / max_v_samp; - } - - if (m_comps_in_scan == 1) - { - m_mcu_org[0] = m_comp_list[0]; - - m_blocks_per_mcu = 1; - } - else - { - m_blocks_per_mcu = 0; - - for (component_num = 0; component_num < m_comps_in_scan; component_num++) - { - int num_blocks; - - component_id = m_comp_list[component_num]; - - num_blocks = m_comp_h_samp[component_id] * m_comp_v_samp[component_id]; - - while (num_blocks--) - m_mcu_org[m_blocks_per_mcu++] = component_id; - } - } - } - - // Starts a new scan. - int jpeg_decoder::init_scan() - { - if (!locate_sos_marker()) - return JPGD_FALSE; - - calc_mcu_block_order(); - - check_huff_tables(); - - check_quant_tables(); - - memset(m_last_dc_val, 0, m_comps_in_frame * sizeof(uint)); - - m_eob_run = 0; - - if (m_restart_interval) - { - m_restarts_left = m_restart_interval; - m_next_restart_num = 0; - } - - fix_in_buffer(); - - return JPGD_TRUE; - } - - // Starts a frame. Determines if the number of components or sampling factors - // are supported. - void jpeg_decoder::init_frame() - { - int i; - - if (m_comps_in_frame == 1) - { - if ((m_comp_h_samp[0] != 1) || (m_comp_v_samp[0] != 1)) - stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS); - - m_scan_type = JPGD_GRAYSCALE; - m_max_blocks_per_mcu = 1; - m_max_mcu_x_size = 8; - m_max_mcu_y_size = 8; - } - else if (m_comps_in_frame == 3) - { - if ( ((m_comp_h_samp[1] != 1) || (m_comp_v_samp[1] != 1)) || - ((m_comp_h_samp[2] != 1) || (m_comp_v_samp[2] != 1)) ) - stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS); - - if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1)) - { - m_scan_type = JPGD_YH1V1; - - m_max_blocks_per_mcu = 3; - m_max_mcu_x_size = 8; - m_max_mcu_y_size = 8; - } - else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1)) - { - m_scan_type = JPGD_YH2V1; - m_max_blocks_per_mcu = 4; - m_max_mcu_x_size = 16; - m_max_mcu_y_size = 8; - } - else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 2)) - { - m_scan_type = JPGD_YH1V2; - m_max_blocks_per_mcu = 4; - m_max_mcu_x_size = 8; - m_max_mcu_y_size = 16; - } - else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2)) - { - m_scan_type = JPGD_YH2V2; - m_max_blocks_per_mcu = 6; - m_max_mcu_x_size = 16; - m_max_mcu_y_size = 16; - } - else - stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS); - } - else - stop_decoding(JPGD_UNSUPPORTED_COLORSPACE); - - m_max_mcus_per_row = (m_image_x_size + (m_max_mcu_x_size - 1)) / m_max_mcu_x_size; - m_max_mcus_per_col = (m_image_y_size + (m_max_mcu_y_size - 1)) / m_max_mcu_y_size; - - // These values are for the *destination* pixels: after conversion. - if (m_scan_type == JPGD_GRAYSCALE) - m_dest_bytes_per_pixel = 1; - else - m_dest_bytes_per_pixel = 4; - - m_dest_bytes_per_scan_line = ((m_image_x_size + 15) & 0xFFF0) * m_dest_bytes_per_pixel; - - m_real_dest_bytes_per_scan_line = (m_image_x_size * m_dest_bytes_per_pixel); - - // Initialize two scan line buffers. - m_pScan_line_0 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true); - if ((m_scan_type == JPGD_YH1V2) || (m_scan_type == JPGD_YH2V2)) - m_pScan_line_1 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true); - - m_max_blocks_per_row = m_max_mcus_per_row * m_max_blocks_per_mcu; - - // Should never happen - if (m_max_blocks_per_row > JPGD_MAX_BLOCKS_PER_ROW) - stop_decoding(JPGD_ASSERTION_ERROR); - - // Allocate the coefficient buffer, enough for one MCU - m_pMCU_coefficients = (jpgd_block_t*)alloc(m_max_blocks_per_mcu * 64 * sizeof(jpgd_block_t)); - - for (i = 0; i < m_max_blocks_per_mcu; i++) - m_mcu_block_max_zag[i] = 64; - - m_expanded_blocks_per_component = m_comp_h_samp[0] * m_comp_v_samp[0]; - m_expanded_blocks_per_mcu = m_expanded_blocks_per_component * m_comps_in_frame; - m_expanded_blocks_per_row = m_max_mcus_per_row * m_expanded_blocks_per_mcu; - // Freq. domain chroma upsampling is only supported for H2V2 subsampling factor. -// BEGIN EPIC MOD -#if JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING - m_freq_domain_chroma_upsample = (m_expanded_blocks_per_mcu == 4*3); -#else - m_freq_domain_chroma_upsample = 0; -#endif -// END EPIC MOD - - if (m_freq_domain_chroma_upsample) - m_pSample_buf = (uint8 *)alloc(m_expanded_blocks_per_row * 64); - else - m_pSample_buf = (uint8 *)alloc(m_max_blocks_per_row * 64); - - m_total_lines_left = m_image_y_size; - - m_mcu_lines_left = 0; - - create_look_ups(); - } - - // The coeff_buf series of methods originally stored the coefficients - // into a "virtual" file which was located in EMS, XMS, or a disk file. A cache - // was used to make this process more efficient. Now, we can store the entire - // thing in RAM. - jpeg_decoder::coeff_buf* jpeg_decoder::coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y) - { - coeff_buf* cb = (coeff_buf*)alloc(sizeof(coeff_buf)); - - cb->block_num_x = block_num_x; - cb->block_num_y = block_num_y; - cb->block_len_x = block_len_x; - cb->block_len_y = block_len_y; - cb->block_size = (block_len_x * block_len_y) * sizeof(jpgd_block_t); - cb->pData = (uint8 *)alloc(cb->block_size * block_num_x * block_num_y, true); - return cb; - } - - inline jpgd_block_t *jpeg_decoder::coeff_buf_getp(coeff_buf *cb, int block_x, int block_y) - { - JPGD_ASSERT((block_x < cb->block_num_x) && (block_y < cb->block_num_y)); - return (jpgd_block_t *)(cb->pData + block_x * cb->block_size + block_y * (cb->block_size * cb->block_num_x)); - } - - // The following methods decode the various types of m_blocks encountered - // in progressively encoded images. - void jpeg_decoder::decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y) - { - int s, r; - jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y); - - if ((s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_dc_tab[component_id]])) != 0) - { - r = pD->get_bits_no_markers(s); - s = HUFF_EXTEND(r, s); - } - - pD->m_last_dc_val[component_id] = (s += pD->m_last_dc_val[component_id]); - - p[0] = static_cast(s << pD->m_successive_low); - } - - void jpeg_decoder::decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y) - { - if (pD->get_bits_no_markers(1)) - { - jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y); - - p[0] |= (1 << pD->m_successive_low); - } - } - - void jpeg_decoder::decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y) - { - int k, s, r; - - if (pD->m_eob_run) - { - pD->m_eob_run--; - return; - } - - jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y); - - for (k = pD->m_spectral_start; k <= pD->m_spectral_end; k++) - { - s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]); - - r = s >> 4; - s &= 15; - - if (s) - { - if ((k += r) > 63) - pD->stop_decoding(JPGD_DECODE_ERROR); - - r = pD->get_bits_no_markers(s); - s = HUFF_EXTEND(r, s); - - p[g_ZAG[k]] = static_cast(s << pD->m_successive_low); - } - else - { - if (r == 15) - { - if ((k += 15) > 63) - pD->stop_decoding(JPGD_DECODE_ERROR); - } - else - { - pD->m_eob_run = 1 << r; - - if (r) - pD->m_eob_run += pD->get_bits_no_markers(r); - - pD->m_eob_run--; - - break; - } - } - } - } - - void jpeg_decoder::decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y) - { - int s, k, r; - int p1 = 1 << pD->m_successive_low; - int m1 = (-1) << pD->m_successive_low; - jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y); - - k = pD->m_spectral_start; - - if (pD->m_eob_run == 0) - { - for ( ; k <= pD->m_spectral_end; k++) - { - s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]); - - r = s >> 4; - s &= 15; - - if (s) - { - if (s != 1) - pD->stop_decoding(JPGD_DECODE_ERROR); - - if (pD->get_bits_no_markers(1)) - s = p1; - else - s = m1; - } - else - { - if (r != 15) - { - pD->m_eob_run = 1 << r; - - if (r) - pD->m_eob_run += pD->get_bits_no_markers(r); - - break; - } - } - - do - { - // BEGIN EPIC MOD - JPGD_ASSERT(k < 64); - // END EPIC MOD - - jpgd_block_t *this_coef = p + g_ZAG[k]; - - if (*this_coef != 0) - { - if (pD->get_bits_no_markers(1)) - { - if ((*this_coef & p1) == 0) - { - if (*this_coef >= 0) - *this_coef = static_cast(*this_coef + p1); - else - *this_coef = static_cast(*this_coef + m1); - } - } - } - else - { - if (--r < 0) - break; - } - - k++; - - } while (k <= pD->m_spectral_end); - - if ((s) && (k < 64)) - { - p[g_ZAG[k]] = static_cast(s); - } - } - } - - if (pD->m_eob_run > 0) - { - for ( ; k <= pD->m_spectral_end; k++) - { - // BEGIN EPIC MOD - JPGD_ASSERT(k < 64); - // END EPIC MOD - - jpgd_block_t *this_coef = p + g_ZAG[k]; - - if (*this_coef != 0) - { - if (pD->get_bits_no_markers(1)) - { - if ((*this_coef & p1) == 0) - { - if (*this_coef >= 0) - *this_coef = static_cast(*this_coef + p1); - else - *this_coef = static_cast(*this_coef + m1); - } - } - } - } - - pD->m_eob_run--; - } - } - - // Decode a scan in a progressively encoded image. - void jpeg_decoder::decode_scan(pDecode_block_func decode_block_func) - { - int mcu_row, mcu_col, mcu_block; - int block_x_mcu[JPGD_MAX_COMPONENTS], m_block_y_mcu[JPGD_MAX_COMPONENTS]; - - memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu)); - - for (mcu_col = 0; mcu_col < m_mcus_per_col; mcu_col++) - { - int component_num, component_id; - - memset(block_x_mcu, 0, sizeof(block_x_mcu)); - - for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++) - { - int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0; - - if ((m_restart_interval) && (m_restarts_left == 0)) - process_restart(); - - for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++) - { - component_id = m_mcu_org[mcu_block]; - - decode_block_func(this, component_id, block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs); - - if (m_comps_in_scan == 1) - block_x_mcu[component_id]++; - else - { - if (++block_x_mcu_ofs == m_comp_h_samp[component_id]) - { - block_x_mcu_ofs = 0; - - if (++block_y_mcu_ofs == m_comp_v_samp[component_id]) - { - block_y_mcu_ofs = 0; - block_x_mcu[component_id] += m_comp_h_samp[component_id]; - } - } - } - } - - m_restarts_left--; - } - - if (m_comps_in_scan == 1) - m_block_y_mcu[m_comp_list[0]]++; - else - { - for (component_num = 0; component_num < m_comps_in_scan; component_num++) - { - component_id = m_comp_list[component_num]; - m_block_y_mcu[component_id] += m_comp_v_samp[component_id]; - } - } - } - } - - // Decode a progressively encoded image. - void jpeg_decoder::init_progressive() - { - int i; - - if (m_comps_in_frame == 4) - stop_decoding(JPGD_UNSUPPORTED_COLORSPACE); - - // Allocate the coefficient buffers. - for (i = 0; i < m_comps_in_frame; i++) - { - m_dc_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 1, 1); - m_ac_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 8, 8); - } - - for ( ; ; ) - { - int dc_only_scan, refinement_scan; - pDecode_block_func decode_block_func; - - if (!init_scan()) - break; - - dc_only_scan = (m_spectral_start == 0); - refinement_scan = (m_successive_high != 0); - - if ((m_spectral_start > m_spectral_end) || (m_spectral_end > 63)) - stop_decoding(JPGD_BAD_SOS_SPECTRAL); - - if (dc_only_scan) - { - if (m_spectral_end) - stop_decoding(JPGD_BAD_SOS_SPECTRAL); - } - else if (m_comps_in_scan != 1) /* AC scans can only contain one component */ - stop_decoding(JPGD_BAD_SOS_SPECTRAL); - - if ((refinement_scan) && (m_successive_low != m_successive_high - 1)) - stop_decoding(JPGD_BAD_SOS_SUCCESSIVE); - - if (dc_only_scan) - { - if (refinement_scan) - decode_block_func = decode_block_dc_refine; - else - decode_block_func = decode_block_dc_first; - } - else - { - if (refinement_scan) - decode_block_func = decode_block_ac_refine; - else - decode_block_func = decode_block_ac_first; - } - - decode_scan(decode_block_func); - - m_bits_left = 16; - get_bits(16); - get_bits(16); - } - - m_comps_in_scan = m_comps_in_frame; - - for (i = 0; i < m_comps_in_frame; i++) - m_comp_list[i] = i; - - calc_mcu_block_order(); - } - - void jpeg_decoder::init_sequential() - { - if (!init_scan()) - stop_decoding(JPGD_UNEXPECTED_MARKER); - } - - void jpeg_decoder::decode_start() - { - init_frame(); - - if (m_progressive_flag) - init_progressive(); - else - init_sequential(); - } - - void jpeg_decoder::decode_init(jpeg_decoder_stream *pStream) - { - init(pStream); - locate_sof_marker(); - } - - jpeg_decoder::jpeg_decoder(jpeg_decoder_stream *pStream) - { - if (setjmp(m_jmp_state)) - return; - decode_init(pStream); - } - - int jpeg_decoder::begin_decoding() - { - if (m_ready_flag) - return JPGD_SUCCESS; - - if (m_error_code) - return JPGD_FAILED; - - if (setjmp(m_jmp_state)) - return JPGD_FAILED; - - decode_start(); - - m_ready_flag = true; - - return JPGD_SUCCESS; - } - - jpeg_decoder::~jpeg_decoder() - { - free_all_blocks(); - } - - jpeg_decoder_file_stream::jpeg_decoder_file_stream() - { - m_pFile = NULL; - m_eof_flag = false; - m_error_flag = false; - } - - void jpeg_decoder_file_stream::close() - { - if (m_pFile) - { - fclose(m_pFile); - m_pFile = NULL; - } - - m_eof_flag = false; - m_error_flag = false; - } - - jpeg_decoder_file_stream::~jpeg_decoder_file_stream() - { - close(); - } - - bool jpeg_decoder_file_stream::open(const char *Pfilename) - { - close(); - - m_eof_flag = false; - m_error_flag = false; - -#if defined(_MSC_VER) - m_pFile = NULL; - fopen_s(&m_pFile, Pfilename, "rb"); -#else - m_pFile = fopen(Pfilename, "rb"); -#endif - return m_pFile != NULL; - } - - int jpeg_decoder_file_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) - { - if (!m_pFile) - return -1; - - if (m_eof_flag) - { - *pEOF_flag = true; - return 0; - } - - if (m_error_flag) - return -1; - - int bytes_read = static_cast(fread(pBuf, 1, max_bytes_to_read, m_pFile)); - if (bytes_read < max_bytes_to_read) - { - if (ferror(m_pFile)) - { - m_error_flag = true; - return -1; - } - - m_eof_flag = true; - *pEOF_flag = true; - } - - return bytes_read; - } - - bool jpeg_decoder_mem_stream::open(const uint8 *pSrc_data, uint size) - { - close(); - m_pSrc_data = pSrc_data; - m_ofs = 0; - m_size = size; - return true; - } - - int jpeg_decoder_mem_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) - { - *pEOF_flag = false; - - if (!m_pSrc_data) - return -1; - - uint bytes_remaining = m_size - m_ofs; - if ((uint)max_bytes_to_read > bytes_remaining) - { - max_bytes_to_read = bytes_remaining; - *pEOF_flag = true; - } - - memcpy(pBuf, m_pSrc_data + m_ofs, max_bytes_to_read); - m_ofs += max_bytes_to_read; - - return max_bytes_to_read; - } - - unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps) - { - if (!actual_comps) - return NULL; - *actual_comps = 0; - - if ((!pStream) || (!width) || (!height) || (!req_comps)) - return NULL; - - if ((req_comps != 1) && (req_comps != 3) && (req_comps != 4)) - return NULL; - - jpeg_decoder decoder(pStream); - if (decoder.get_error_code() != JPGD_SUCCESS) - return NULL; - - const int image_width = decoder.get_width(), image_height = decoder.get_height(); - *width = image_width; - *height = image_height; - *actual_comps = decoder.get_num_components(); - - if (decoder.begin_decoding() != JPGD_SUCCESS) - return NULL; - - const int dst_bpl = image_width * req_comps; - - uint8 *pImage_data = (uint8*)jpgd_malloc(dst_bpl * image_height); - if (!pImage_data) - return NULL; - - for (int y = 0; y < image_height; y++) - { - const uint8* pScan_line = 0; - uint scan_line_len; - if (decoder.decode((const void**)&pScan_line, &scan_line_len) != JPGD_SUCCESS) - { - jpgd_free(pImage_data); - return NULL; - } - - uint8 *pDst = pImage_data + y * dst_bpl; - - if (((req_comps == 4) && (decoder.get_num_components() == 3)) || - ((req_comps == 1) && (decoder.get_num_components() == 1))) - { - memcpy(pDst, pScan_line, dst_bpl); - } - else if (decoder.get_num_components() == 1) - { - if (req_comps == 3) - { - for (int x = 0; x < image_width; x++) - { - uint8 luma = pScan_line[x]; - pDst[0] = luma; - pDst[1] = luma; - pDst[2] = luma; - pDst += 3; - } - } - else - { - for (int x = 0; x < image_width; x++) - { - uint8 luma = pScan_line[x]; - pDst[0] = luma; - pDst[1] = luma; - pDst[2] = luma; - pDst[3] = 255; - pDst += 4; - } - } - } - else if (decoder.get_num_components() == 3) - { - if (req_comps == 1) - { - const int YR = 19595, YG = 38470, YB = 7471; - for (int x = 0; x < image_width; x++) - { - int r = pScan_line[x*4+0]; - int g = pScan_line[x*4+1]; - int b = pScan_line[x*4+2]; - *pDst++ = static_cast((r * YR + g * YG + b * YB + 32768) >> 16); - } - } - else - { - for (int x = 0; x < image_width; x++) - { - pDst[0] = pScan_line[x*4+0]; - pDst[1] = pScan_line[x*4+1]; - pDst[2] = pScan_line[x*4+2]; - pDst += 3; - } - } - } - } - - return pImage_data; - } - -// BEGIN EPIC MOD - unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps, int format) - { - jpg_format = (ERGBFormatJPG)format; -// EMD EPIC MOD - jpgd::jpeg_decoder_mem_stream mem_stream(pSrc_data, src_data_size); - return decompress_jpeg_image_from_stream(&mem_stream, width, height, actual_comps, req_comps); - } - - unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps) - { - jpgd::jpeg_decoder_file_stream file_stream; - if (!file_stream.open(pSrc_filename)) - return NULL; - return decompress_jpeg_image_from_stream(&file_stream, width, height, actual_comps, req_comps); - } - -} // namespace jpgd diff --git a/spaces/facebook/StyleNeRF/training/__init__.py b/spaces/facebook/StyleNeRF/training/__init__.py deleted file mode 100644 index e1e1a5ba99e56a56ecaa14f7d4fa41777789c0cf..0000000000000000000000000000000000000000 --- a/spaces/facebook/StyleNeRF/training/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - -# empty diff --git a/spaces/fatiXbelha/sd/Aproveite os clssicos do Mega Drive e Genesis com este pacote incrvel de download.md b/spaces/fatiXbelha/sd/Aproveite os clssicos do Mega Drive e Genesis com este pacote incrvel de download.md deleted file mode 100644 index ec414cdee9cdbf1718fee64f32f3943cb65d436e..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Aproveite os clssicos do Mega Drive e Genesis com este pacote incrvel de download.md +++ /dev/null @@ -1,161 +0,0 @@ -
    -

    How to Download Jogos Mega Drive

    -

    If you grew up in the 90s, chances are you played or heard of jogos mega drive, the games for the Sega Mega Drive console. Also known as Genesis in North America, this 16-bit system was one of the most popular and influential consoles of its time, competing with the Super Nintendo Entertainment System (SNES). With over 900 games released for the Mega Drive, there is something for everyone: from fast-paced platformers like Sonic the Hedgehog to deep RPGs like Phantasy Star. Whether you want to relive your childhood memories or discover some retro gems, you might be wondering how to download jogos mega drive and play them today.

    -

    download jogos mega drive


    Downloadhttps://urllie.com/2uNzss



    -

    There are three main ways to play jogos mega drive in 2023: using original cartridges, using emulators, or using digital collections. Each method has its own advantages and disadvantages, depending on your preferences and budget. In this article, we'll explain each method in detail and give you some tips on where to find the best jogos mega drive.

    -

    Original Cartridges

    -

    The most authentic way to play jogos mega drive is to use original cartridges on a Sega Mega Drive console. These are the same games and hardware that were sold in the 90s, so you can experience them exactly as they were intended. However, finding and buying original cartridges can be challenging and expensive nowadays.

    -

    If you want to buy original jogos mega drive cartridges, you have two main options: online or local. Online, you can browse sites like eBay or Amazon and look for sellers that offer good prices and conditions. You can also check out specialized sites like [Retro Dodo](^6^) or [Shortlist](^7^) that rank the best Sega Mega Drive games of all time and provide links to buy them. Local, you can visit second-hand games stores or flea markets and look for bargains. You might also find some collectors or friends that are willing to sell or trade their old games.

    -

    Once you have your cartridges, you need a Sega Mega Drive console to play them. You can use either a PAL or NTSC console depending on your region. You also need a power adapter that matches your voltage and plug type. To connect your console to a modern TV or monitor, you have several options: composite video (yellow), S-video (black), RGB SCART (multi-colored), or HDMI (blue). The best option is HDMI, as it provides the best quality and compatibility. You can use a [Mega Drive HDMI cable] or a [Mega Drive to HDMI converter] to connect your console to your TV or monitor. Alternatively, you can use RGB SCART or S-video, which are also good options, but you might need an adapter or a switch box. The worst option is composite video, as it provides the lowest quality and can cause interference or distortion.

    -

    The advantages of playing jogos mega drive on the original hardware are:

    -

    download jogos mega drive e genesis classics
    -download jogos mega drive roms collection
    -download jogos mega drive traduzidos português
    -download jogos mega drive emulator pc
    -download jogos mega drive sonic the hedgehog
    -download jogos mega drive online multiplayer
    -download jogos mega drive vr mode
    -download jogos mega drive save states
    -download jogos mega drive mirror mode
    -download jogos mega drive rewind feature
    -download jogos mega drive achievements
    -download jogos mega drive steam
    -download jogos mega drive youtube
    -download jogos mega drive internet archive
    -download jogos mega drive pack 180 roms
    -download jogos mega drive sega collection
    -download jogos mega drive aladdin
    -download jogos mega drive streets of rage
    -download jogos mega drive golden axe
    -download jogos mega drive mortal kombat
    -download jogos mega drive comix zone
    -download jogos mega drive shinobi iii
    -download jogos mega drive gunstar heroes
    -download jogos mega drive phantasy star iv
    -download jogos mega drive shinning force ii
    -download jogos mega drive landstalker
    -download jogos mega drive wonder boy iii
    -download jogos mega drive ristar
    -download jogos mega drive vectorman
    -download jogos mega drive kid chameleon
    -download jogos mega drive toejam and earl
    -download jogos mega drive castle of illusion
    -download jogos mega drive world of illusion
    -download jogos mega drive quackshot
    -download jogos mega drive earthworm jim
    -download jogos mega drive rocket knight adventures
    -download jogos mega drive dynamite headdy
    -download jogos mega drive alien soldier
    -download jogos mega drive light crusader
    -download jogos mega drive beyond oasis
    -download jogos mega drive story of thor
    -download jogos mega drive ecco the dolphin
    -download jogos mega drive flashback
    -download jogos mega drive another world
    -download jogos mega drive pier solar and the great architects

    -
      -
    • Authenticity: You can enjoy the games as they were designed and programmed, without any modifications or alterations.
    • -
    • Nostalgia: You can relive the memories of playing jogos mega drive in the 90s, with the same sound, graphics, and feel.
    • -
    • Collectability: You can build your own collection of jogos mega drive cartridges and display them proudly. Some games are rare and valuable, and can increase in price over time.
    • -
    -

    The disadvantages of playing jogos mega drive on the original hardware are:

    -
      -
    • Cost: You have to spend money on buying the cartridges, the console, the cables, and the adapters. Some games can be very expensive, especially if they are in good condition or have their original box and manual.
    • -
    • Availability: You have to search for the games you want and hope that they are in stock and in working order. Some games are hard to find or out of print, and you might have to wait for a long time or settle for a lower quality.
    • -
    • Compatibility: You have to make sure that your console and your cartridges match your region and your TV or monitor. Some games are region-locked or have different versions for different regions, and you might need a converter or a modchip to play them.
    • -
    • Durability: You have to take care of your cartridges and your console and avoid any damage or wear. Some games can stop working or lose their save data due to age or mishandling.
    • -
    -

    Emulators

    -

    An alternative way to play jogos mega drive is to use emulators on your PC, Mac, or mobile device. Emulators are software programs that simulate the hardware and software of a Sega Mega Drive console on your device. You can download and install an emulator for free from various sites like [EmuParadise] or [CoolROM]. You also need ROM files, which are digital copies of jogos mega drive cartridges that you can load on your emulator. You can download ROM files from sites like [ROMsMania] or [ROM Hustler], but be careful about the legality and safety of these sites.

    -

    The advantages of playing jogos mega drive on an emulator are:

    -
      -
    • Convenience: You can play jogos mega drive anytime and anywhere on your device, without needing any physical cartridges or consoles. You can also pause, resume, and quit the games at any point.
    • -
    • Variety: You can play any jogos mega drive that you want, regardless of their region or availability. You can also play fan-made games, hacks, mods, translations, or unreleased games that are not available on cartridges.
    • -
    • Customization: You can adjust the settings of your emulator to suit your preferences and needs. You can change the resolution, the aspect ratio, the sound volume, the speed, the filters, and more. You can also use cheats, codes, patches, or trainers to modify the games.
    • -
    • Save states: You can save and load your progress at any point in the game, without relying on the in-game save system. You can also create multiple save states for different scenarios or outcomes.
    • -

    The disadvantages of playing jogos mega drive on an emulator are:

    -
      -
    • Legality: You might be breaking the law by downloading and using ROM files without owning the original cartridges. The legal status of emulation and ROMs varies by country and by game, and you should check the local laws and the rights of the game developers before using them.
    • -
    • Quality: You might not get the same quality and accuracy of the games as on the original hardware. Some emulators and ROMs might have bugs, glitches, errors, or missing features that affect the gameplay or the graphics.
    • -
    • Controller support: You might not be able to use the original Sega Mega Drive controller or a similar one on your device. You might have to use a keyboard, a mouse, a touchscreen, or a different controller that might not feel as comfortable or responsive.
    • -
    • Online multiplayer: You might not be able to play online multiplayer games with other players using emulators and ROMs. Some emulators might support online multiplayer, but you might have issues with compatibility, latency, or security.
    • -
    -

    Digital Collections

    -

    A third way to play jogos mega drive is to use digital collections of games that are officially licensed and released by Sega or other publishers. These are collections of jogos mega drive that you can buy and download on various platforms, such as Steam, PS4, Switch, Xbox One, or Mega Drive Mini. These collections usually include dozens of games from different genres and series, such as Sonic, Streets of Rage, Golden Axe, Shining Force, and more.

    -

    The advantages of playing jogos mega drive on digital collections are:

    -
      -
    • Online multiplayer: You can play online multiplayer games with other players using digital collections. Some collections offer online co-op or versus modes for jogos mega drive that support them, such as Streets of Rage 4 or Sonic Mania Plus.
    • -
    • Achievements: You can unlock achievements for completing certain tasks or challenges in jogos mega drive using digital collections. Some collections have their own achievement system, such as Sega Mega Drive Classics on Steam, while others use the platform's achievement system, such as Sega Genesis Classics on PS4.
    • -
    • Graphics filters: You can apply graphics filters to enhance or change the appearance of jogos mega drive using digital collections. Some collections offer filters that simulate the CRT effect, the scanlines, the pixelation, or the smoothing of the games.
    • -
    • Rewind: You can rewind the gameplay to undo your mistakes or try different strategies in jogos mega drive using digital collections. Some collections have a rewind feature that lets you go back a few seconds or minutes in the game.
    • -
    • VR support: You can play jogos mega drive in virtual reality using digital collections. Some collections have VR support that lets you immerse yourself in a 3D environment that resembles a 90s bedroom with a Sega Mega Drive console and a TV.
    • -

    The disadvantages of playing jogos mega drive on digital collections are:

    -
      -
    • Price: You have to pay for the digital collections, which might be more expensive than buying individual cartridges or using emulators and ROMs. Some collections might also have additional costs for DLCs or updates.
    • -
    • Selection: You have to choose from the games that are included in the digital collections, which might not cover all the jogos mega drive that you want to play. Some collections might have more or less games than others, or might have different versions or regions of the games.
    • -
    • Authenticity: You might not get the same authenticity and nostalgia of playing jogos mega drive on the original hardware or on an emulator. Some collections might have changes or modifications in the games, such as altered graphics, sound, or gameplay.
    • -
    • Compatibility: You have to make sure that your device and your platform support the digital collections that you want to buy and download. Some collections might not be available or compatible with certain devices or platforms, or might have different features or performance.
    • -
    -

    Conclusion

    -

    In conclusion, there are three main ways to download and play jogos mega drive in 2023: using original cartridges, using emulators, or using digital collections. Each method has its own pros and cons, and you should choose the one that suits your preferences and budget. Here are some examples of the best jogos mega drive to play and where to find them:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    GameGenreMethodSource
    Sonic the Hedgehog 2PlatformerOriginal cartridge[eBay]
    Phantasy Star IVRPGEmulator[ROMsMania]
    Streets of Rage 4Beat 'em upDigital collection[Steam]
    Gunstar HeroesRun and gunOriginal cartridge[Amazon]
    Shining Force IITactical RPGEmulator[CoolROM]
    Sonic Mania PlusPlatformerDigital collection[PS4]
    -

    We hope you enjoyed this article on how to download jogos mega drive and play them in 2023. Jogos mega drive are some of the best games ever made, and they deserve to be played and appreciated by new and old fans alike. Whether you prefer the original cartridges, the emulators, or the digital collections, you can have fun and nostalgia with these classic games.

    -

    Do you have any questions or comments about jogos mega drive? Do you have any favorite games or tips to share? Let us know in the comments section below. We'd love to hear from you!

    -

    FAQs

    -

    Here are some frequently asked questions about jogos mega drive:

    -

    What is the difference between Sega Mega Drive and Sega Genesis?

    -

    Sega Mega Drive and Sega Genesis are the same console, but with different names depending on the region. Sega Mega Drive is the name used in Europe, Japan, and most of Asia, while Sega Genesis is the name used in North America and some parts of South America.

    -

    What is the best emulator for Sega Mega Drive?

    -

    There is no definitive answer to this question, as different emulators have different features and performance. However, some of the most popular and reliable emulators for Sega Mega Drive are [Kega Fusion], [Gens], [BizHawk], and [RetroArch]. You can try them out and see which one works best for you.

    -

    What is the best digital collection for Sega Mega Drive?

    -

    Again, this depends on your preferences and budget, as well as your device and platform. However, some of the most comprehensive and acclaimed digital collections for Sega Mega Drive are [Sega Mega Drive Classics] on Steam, PS4, Switch, and Xbox One, [Sega Genesis Classics] on PS4, Switch, and Xbox One, and [Mega Drive Mini] on a dedicated mini console.

    -

    How can I play jogos mega drive online with other players?

    -

    If you want to play jogos mega drive online with other players, you have two main options: using digital collections or using emulators. Some digital collections offer online multiplayer modes for certain games, such as Streets of Rage 4 or Sonic Mania Plus. Some emulators also support online multiplayer, but you might need to configure some settings or use additional software.

    -

    How can I play jogos mega drive in virtual reality?

    -

    If you want to play jogos mega drive in virtual reality, you need a VR headset and a compatible device and platform. Some digital collections offer VR support, such as Sega Mega Drive Classics on Steam. You can also use an emulator that supports VR, such as RetroArch with the OpenVR driver.

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download Coin Master- Free Spin APK and Enjoy Unlimited Spins.md b/spaces/fatiXbelha/sd/Download Coin Master- Free Spin APK and Enjoy Unlimited Spins.md deleted file mode 100644 index 9aa27061e6a35c12a369bcd46ad6013a8520b028..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download Coin Master- Free Spin APK and Enjoy Unlimited Spins.md +++ /dev/null @@ -1,140 +0,0 @@ - -

    How to Get Coin Master Free Spins with APK

    -

    If you are a fan of Coin Master, you know how addictive and fun this game can be. But you also know how frustrating it can be when you run out of spins and have to wait for hours or even days to get more. That's why many players are looking for ways to get coin master free spins with apk. But what is coin master free spin apk and how does it work? Is it safe and legal to use? And how can you download and install it on your device? In this article, we will answer all these questions and more. Read on to find out everything you need to know about coin master free spin apk.

    -

    coin master free spin apk


    Download File ••• https://urllie.com/2uNvAV



    -

    What is Coin Master and why do you need free spins?

    -

    Coin Master gameplay and features

    -

    Coin Master is a popular adventure game developed by Moon Active. The game combines elements of slot machines, base building, card collecting, and social interaction. You can play with your friends or millions of other players around the world. The goal of the game is to build your own village, raid other players' villages, collect cards, and become the coin master.

    -

    The role of spins in Coin Master

    -

    Spins are the currency of the game. You need them to spin the slot machine, which can give you various rewards such as coins, shields, attacks, raids, or chests. You can use coins to upgrade your village, shields to protect your village from attacks, attacks to damage other players' villages, raids to steal coins from other players' villages, and chests to unlock new cards. You can also trade cards with other players or join a clan for more benefits.

    -

    Spins are essential for progressing in the game, but they are also limited. You can only get five spins every hour, up to a maximum of 50 spins per day. You can also get some extra spins by watching ads, inviting friends, completing events, or buying them with real money. However, these methods are not enough for most players who want to play more and faster. That's why some players resort to coin master free spin apk.

    -

    What is Coin Master Free Spins APK and how does it work?

    -

    The benefits of using Coin Master Free Spins APK

    -

    Coin Master Free Spins APK is a free-to-download companion app for Coin Master that claims to provide a detailed and comprehensive guide on how to get free spins. The app also claims to offer some features such as daily links, spin rewards, coin rewards, tips and tricks, and more. The app promises to help you get unlimited spins without spending any money or waiting for hours.

    -

    The risks of using Coin Master Free Spins APK

    -

    While Coin Master Free Spins APK sounds tempting, it also comes with some risks that you should be aware of before using it. First of all, the app is not affiliated with or endorsed by Moon Active, the developer of Coin Master. Therefore, using the app may violate the terms of service of the game and result in your account being banned or suspended. Secondly, the app may contain malware or viruses that can harm your device or steal your personal information. Thirdly, the app may not work as advertised or may stop working at any time due to updates or patches from the game developer. Therefore, using coin master free spin apk is not recommended by us.

    -

    coin master free spin apk download
    -coin master free spin apk mod
    -coin master free spin apk 2021
    -coin master free spin apk latest version
    -coin master free spin apk unlimited spins
    -coin master free spin apk hack
    -coin master free spin apk android
    -coin master free spin apk ios
    -coin master free spin apk link
    -coin master free spin apk update
    -coin master free spin apk no verification
    -coin master free spin apk generator
    -coin master free spin apk online
    -coin master free spin apk 2020
    -coin master free spin apk for pc
    -coin master free spin apk without human verification
    -coin master free spin apk daily link
    -coin master free spin apk real
    -coin master free spin apk 2019
    -coin master free spin apk old version
    -coin master free spin apk reddit
    -coin master free spin apk 2018
    -coin master free spin apk no survey
    -coin master free spin apk pro
    -coin master free spin apk new version
    -coin master free spin apk today
    -coin master free spin apk original
    -coin master free spin apk 2022
    -coin master free spin apk app
    -coin master free spin apk file
    -coin master free spin apk install
    -coin master free spin apk website
    -coin master free spin apk legit
    -coin master free spin apk working
    -coin master free spin apk vip
    -coin master free spin apk premium
    -coin master free spin apk code
    -coin master free spin apk review
    -coin master free spin apk 2017
    -coin master free spin apk quora
    -coin master free spin apk blogspot
    -coin master free spin apk youtube
    -coin master free spin apk facebook
    -coin master free spin apk telegram
    -coin master free spin apk twitter
    -coin master free spin apk instagram
    -coin master free spin apk pinterest
    -coin master free spin apk tiktok
    -coin master free spin apk discord

    -

    How to download and install Coin Master Free Spins APK on your device?How to download and install Coin Master Free Spins APK on your device?

    -

    Step-by-step guide for Android users

    -

    If you have an Android device, you can follow these steps to download and install Coin Master Free Spins APK on your device:

    -
      -
    1. Go to a trusted website that offers Coin Master Free Spins APK, such as [APKMirror](^1^) or [APKPure].
    2. -
    3. Find the latest version of the app and tap on the download button.
    4. -
    5. Wait for the download to finish and then open the APK file from your notification bar or file manager.
    6. -
    7. If prompted, enable the option to install apps from unknown sources in your device settings.
    8. -
    9. Tap on install and wait for the installation to complete.
    10. -
    11. Launch the app and enjoy your free spins.
    12. -
    -

    Step-by-step guide for iOS users

    -

    If you have an iOS device, you can follow these steps to download and install Coin Master Free Spins APK on your device:

    -
      -
    1. Go to a trusted website that offers the IPA equivalent of Coin Master Free Spins APK, such as [Tweak Library](^2^) or [iOS Ninja].
    2. -
    3. Find the latest version of the app and tap on the download button.
    4. -
    5. Wait for the download to finish and then open the IPA file from your browser or file manager.
    6. -
    7. If prompted, install the app Cydia Impactor on your device. This app will allow you to sign in with your Apple ID and install the IPA file.
    8. -
    9. Connect your iOS device to your computer using a USB cable.
    10. -
    11. Launch Cydia Impactor and drag and drop the IPA file onto it.
    12. -
    13. Enter your Apple ID and password when asked. This will sign the app with your credentials.
    14. -
    15. Wait for the installation to finish and then go to your device settings. Tap on General > Profiles & Device Management. Find the profile with your Apple ID and trust it.
    16. -
    17. Launch the app and enjoy your free spins.
    18. -
    -

    How to use Coin Master Free Spins APK to get unlimited spins?

    -

    Tips and tricks for getting more spins with Coin Master Free Spins APK

    -

    Coin Master Free Spins APK claims to provide you with a detailed guide on how to get free spins in Coin Master. Some of the tips and tricks that the app suggests are:

    -
      -
    • Collect daily links from the app that give you free spins and coins.
    • -
    • Claim spin rewards from the app that are based on your level and progress.
    • -
    • Claim coin rewards from the app that are based on your coin balance and village cost.
    • -
    • Follow the tips and tricks from the app that teach you how to play smartly, such as when to bet, when to raid, when to collect cards, etc.
    • -
    • Watch ads from the app that offer you extra spins or coins.
    • -
    -

    Alternatives to Coin Master Free Spins APK

    -

    If you are not comfortable with using Coin Master Free Spins APK or if you want to try other ways to get free spins in Coin Master, you can also check out these alternatives:

    -
      -
    • Follow Coin Master on social media platforms such as Facebook, Twitter, Instagram, etc. They often post links or codes that give you free spins or coins.
    • -
    • Join Coin Master groups or forums online where other players share their links or codes for free spins or coins.
    • -
    • Invite your friends to play Coin Master using your referral link. You can get up to 40 spins for each friend who joins the game.
    • -
    • Complete events or quests in Coin Master that reward you with free spins or coins.
    • -
    • Purchase spins or coins with real money if you can afford it. This is the safest and most reliable way to get more spins in Coin Master.
    • -
    -

    Conclusion and FAQs

    -

    Coin Master is a fun and addictive game that requires you to have enough spins to play. However, getting more spins can be challenging and time-consuming. That's why some players look for coin master free spin apk, a companion app that claims to help you get unlimited spins for free. However, using this app can also be risky and illegal, as it may violate the game's terms of service, contain malware or viruses, or stop working at any time. Therefore, we do not recommend using coin master free spin apk. Instead, we suggest you try some of the alternatives we mentioned above, such as following Coin Master on social media, joining online groups or forums

    of other players, inviting your friends, completing events or quests, or buying spins or coins with real money. These methods are safer and more reliable than using coin master free spin apk.

    -

    We hope this article has helped you understand what coin master free spin apk is and how to get free spins in Coin Master. If you have any questions or comments, feel free to leave them below. We would love to hear from you. Happy spinning!

    -

    FAQs

    -

    Here are some of the frequently asked questions about coin master free spin apk:

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    QuestionAnswer
    Is coin master free spin apk safe to use?No, coin master free spin apk is not safe to use. It may contain malware or viruses that can harm your device or steal your personal information. It may also violate the game's terms of service and result in your account being banned or suspended.
    Is coin master free spin apk legal to use?No, coin master free spin apk is not legal to use. It may infringe the intellectual property rights of the game developer or the app store. It may also be considered as cheating or hacking, which is against the rules of the game.
    Does coin master free spin apk work?No, coin master free spin apk may not work as advertised or may stop working at any time due to updates or patches from the game developer. It may also fail to deliver the promised rewards or features.
    How can I get more spins in Coin Master without using coin master free spin apk?You can get more spins in Coin Master without using coin master free spin apk by following Coin Master on social media, joining online groups or forums of other players, inviting your friends, completing events or quests, or buying spins or coins with real money.
    Where can I download coin master free spin apk?You can download coin master free spin apk from various websites that offer it, such as APKMirror, APKPure, Tweak Library, or iOS Ninja. However, we do not recommend downloading or using coin master free spin apk for the reasons we explained above.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/feng2022/Time-TravelRephotography/Time_TravelRephotography/models/encoder4editing/utils/alignment.py b/spaces/feng2022/Time-TravelRephotography/Time_TravelRephotography/models/encoder4editing/utils/alignment.py deleted file mode 100644 index a02798f0f7c9fdcc319f7884a491b9e6580cc8aa..0000000000000000000000000000000000000000 --- a/spaces/feng2022/Time-TravelRephotography/Time_TravelRephotography/models/encoder4editing/utils/alignment.py +++ /dev/null @@ -1,115 +0,0 @@ -import numpy as np -import PIL -import PIL.Image -import scipy -import scipy.ndimage -import dlib - - -def get_landmark(filepath, predictor): - """get landmark with dlib - :return: np.array shape=(68, 2) - """ - detector = dlib.get_frontal_face_detector() - - img = dlib.load_rgb_image(filepath) - dets = detector(img, 1) - - for k, d in enumerate(dets): - shape = predictor(img, d) - - t = list(shape.parts()) - a = [] - for tt in t: - a.append([tt.x, tt.y]) - lm = np.array(a) - return lm - - -def align_face(filepath, predictor): - """ - :param filepath: str - :return: PIL Image - """ - - lm = get_landmark(filepath, predictor) - - lm_chin = lm[0: 17] # left-right - lm_eyebrow_left = lm[17: 22] # left-right - lm_eyebrow_right = lm[22: 27] # left-right - lm_nose = lm[27: 31] # top-down - lm_nostrils = lm[31: 36] # top-down - lm_eye_left = lm[36: 42] # left-clockwise - lm_eye_right = lm[42: 48] # left-clockwise - lm_mouth_outer = lm[48: 60] # left-clockwise - lm_mouth_inner = lm[60: 68] # left-clockwise - - # Calculate auxiliary vectors. - eye_left = np.mean(lm_eye_left, axis=0) - eye_right = np.mean(lm_eye_right, axis=0) - eye_avg = (eye_left + eye_right) * 0.5 - eye_to_eye = eye_right - eye_left - mouth_left = lm_mouth_outer[0] - mouth_right = lm_mouth_outer[6] - mouth_avg = (mouth_left + mouth_right) * 0.5 - eye_to_mouth = mouth_avg - eye_avg - - # Choose oriented crop rectangle. - x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1] - x /= np.hypot(*x) - x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8) - y = np.flipud(x) * [-1, 1] - c = eye_avg + eye_to_mouth * 0.1 - quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y]) - qsize = np.hypot(*x) * 2 - - # read image - img = PIL.Image.open(filepath) - - output_size = 256 - transform_size = 256 - enable_padding = True - - # Shrink. - shrink = int(np.floor(qsize / output_size * 0.5)) - if shrink > 1: - rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink))) - img = img.resize(rsize, PIL.Image.ANTIALIAS) - quad /= shrink - qsize /= shrink - - # Crop. - border = max(int(np.rint(qsize * 0.1)), 3) - crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))), - int(np.ceil(max(quad[:, 1])))) - crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]), - min(crop[3] + border, img.size[1])) - if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]: - img = img.crop(crop) - quad -= crop[0:2] - - # Pad. - pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))), - int(np.ceil(max(quad[:, 1])))) - pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0), - max(pad[3] - img.size[1] + border, 0)) - if enable_padding and max(pad) > border - 4: - pad = np.maximum(pad, int(np.rint(qsize * 0.3))) - img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect') - h, w, _ = img.shape - y, x, _ = np.ogrid[:h, :w, :1] - mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]), - 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3])) - blur = qsize * 0.02 - img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0) - img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0) - img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB') - quad += pad[:2] - - # Transform. - img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR) - if output_size < transform_size: - img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS) - - # Return aligned image. - return img diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Calculator Lock APK and Hide Your Private Files with Ease.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Calculator Lock APK and Hide Your Private Files with Ease.md deleted file mode 100644 index c6ca4b45eb02605c915fb8e05624d8aa9a485d23..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Calculator Lock APK and Hide Your Private Files with Ease.md +++ /dev/null @@ -1,110 +0,0 @@ -
    -

    Calculator Lock It APK Download: What Is It and How to Use It?

    -

    Do you have some private files or apps that you want to hide from prying eyes? Do you want to protect your personal data with a strong password? Do you want to enjoy your secret videos or photos without leaving any traces? If yes, then you need a calculator lock it apk download.

    -

    calculator lock it apk download


    Downloadhttps://gohhs.com/2uPo11



    -

    Calculator lock it apk is a powerful privacy lock and app hider tool that disguises itself as a normal calculator app. But behind this calculator app, there is a secret space where you can hide and lock anything you want, such as videos, photos, apps, documents, etc.

    -

    With calculator lock it apk, you can easily create your own private vault and keep your secrets safe from anyone who tries to access your device. You

    Features of Calculator Lock It APK

    -

    Calculator lock it apk is not just a simple calculator app, but a full-fledged privacy protection app that offers many amazing features. Here are some of the features that you can enjoy with calculator lock it apk:

    -
      -
    • Photo Vault: You can hide your videos and photos in a secret calculator vault that only you can access with your password. You can also view, edit, and share your hidden media files within the app. The app supports various formats, such as JPG, PNG, GIF, MP4, AVI, etc.
    • -
    • App Hider and App Locker: You can clone or hide any apps that you don't want others to see or use on your device. You can also lock them with a PIN or pattern to prevent unauthorized access. The app supports hiding and locking social apps, dating apps, games, browsers, etc.
    • -
    • Cloud Storage: You can backup and sync your hidden files and apps to cloud service, such as Google Drive, Dropbox, OneDrive, etc. This way, you can save your storage space and restore your data anytime and anywhere.
    • -
    • Private Browser and VPN Service: You can browse privately and download videos from various websites with the built-in browser and VPN service. The browser supports incognito mode, bookmarks, history, downloads, etc. The VPN service helps you access blocked websites and protect your online privacy.
    • -
    • Perfect Disguise: You can change the icon of the calculator vault and make it look like a normal calculator app. You can also use a fake notification or a fake error message to disguise it. No one will ever suspect that there is a hidden vault behind this calculator app.
    • -
    • Effective Media Management: You can manage and edit your hidden files and apps freely within the app. You can create folders, rename files, move files, delete files, etc. You can also sort your files by name, size, date, etc.
    • -
    -

    How to Download and Install Calculator Lock It APK?

    -

    If you want to download and install calculator lock it apk on your device, you can follow these simple steps:

    -
      -
    1. Step 1: Go to the official website of Calculator Lock It APK or any other trusted source and download the latest version of the app.
    2. -
    3. Step 2: Enable the installation of apps from unknown sources on your device settings. This will allow you to install the apk file that you downloaded.
    4. -
    5. Step 3: Locate the downloaded apk file and tap on it to start the installation process.
    6. -
    7. Step 4: Follow the instructions on the screen and grant the necessary permissions to the app.
    8. -
    9. Step 5: Set up a password for your calculator vault and start hiding and locking your private files and apps.
    10. -
    -

    Pros and Cons of Calculator Lock It APK

    -

    Calculator lock it apk is a great app for protecting your privacy and hiding your secrets. But like any other app, it also has some pros and cons that you should be aware of. Here are some of them:

    -

    Calculator Lock - HideX: Calculator Photo Vault, App Lock, App Hider APK
    -HideX: Calculator Lock APK for Android - Download
    -Calculator Lock APK (Android App) - Free Download - APKCombo
    -Calculator Vault - Hide Photos & Videos, App Hider APK
    -Calculator Lock - Photo Vault & Video Vault hide photos APK
    -Calculator Lock - Video Lock & Photo Vault - HideX APK
    -Calculator Lock - App Hider & Photo Vault - HideX APK
    -Calculator Lock - Hide Photos & Videos, App Locker APK
    -Calculator Lock - Photo Vault & Video Vault hide photos APK
    -Calculator Lock - HideX: Private Browser and Downloader APK
    -Calculator Lock - HideX: Secret Gallery and File Manager APK
    -Calculator Lock - HideX: VPN Service and Private Browser APK
    -Calculator Lock - HideX: Cloud Backup and Cloud Storage APK
    -Calculator Lock - HideX: Icon Changer and App Disguise APK
    -Calculator Lock - HideX: PIN Code and Pattern Lock APK
    -Download Calculator Lock - HideX: Calculator Photo Vault, App Lock, App Hider APK
    -Download HideX: Calculator Lock APK for Android - Free
    -Download Calculator Lock APK (Android App) - Latest Version
    -Download Calculator Vault - Hide Photos & Videos, App Hider APK
    -Download Calculator Lock - Photo Vault & Video Vault hide photos APK
    -Download Calculator Lock - Video Lock & Photo Vault - HideX APK
    -Download Calculator Lock - App Hider & Photo Vault - HideX APK
    -Download Calculator Lock - Hide Photos & Videos, App Locker APK
    -Download Calculator Lock - Photo Vault & Video Vault hide photos APK
    -Download Calculator Lock - HideX: Private Browser and Downloader APK
    -Download Calculator Lock - HideX: Secret Gallery and File Manager APK
    -Download Calculator Lock - HideX: VPN Service and Private Browser APK
    -Download Calculator Lock - HideX: Cloud Backup and Cloud Storage APK
    -Download Calculator Lock - HideX: Icon Changer and App Disguise APK
    -Download Calculator Lock - HideX: PIN Code and Pattern Lock APK
    -How to install Calculator Lock - HideX: Calculator Photo Vault, App Lock, App Hider APK
    -How to install HideX: Calculator Lock APK for Android
    -How to install Calculator Lock APK (Android App) on your device
    -How to install Calculator Vault - Hide Photos & Videos, App Hider APK
    -How to install Calculator Lock - Photo Vault & Video Vault hide photos APK
    -How to install Calculator Lock - Video Lock & Photo Vault - HideX APK
    -How to install Calculator Lock - App Hider & Photo Vault - HideX APK
    -How to install Calculator Lock - Hide Photos & Videos, App Locker APK
    -How to install Calculator Lock - Photo Vault & Video Vault hide photos APK
    -How to install Calculator Lock - HideX: Private Browser and Downloader APK
    -How to install Calculator Lock - HideX: Secret Gallery and File Manager APK
    -How to install Calculator Lock - HideX: VPN Service and Private Browser APK
    -How to install Calculator Lock - HideX: Cloud Backup and Cloud Storage APK
    -How to install Calculator Lock - HideX: Icon Changer and App Disguise APK
    -How to install Calculator Lock - HideX: PIN Code and Pattern Lock APK
    -Best calculator lock apps for Android in 2023
    -Best calculator photo vault apps for Android in 2023
    -Best calculator app hider apps for Android in 2023
    -Best calculator video vault apps for Android in 2023

    - - - - - - - - - - - - - - - - - -
    ProsCons
    - High security: The app uses AES encryption to secure your hidden files and apps. It also has a break-in alert feature that captures the photo of anyone who tries to enter your vault with a wrong password.- Compatibility issues: The app may not work well on some devices or Android versions. It may also cause some glitches or crashes on some hidden or cloned apps.
    - Easy operation: The app has a user-friendly interface and simple operation. You just need to enter your password on the calculator screen to access your vault. You can also use gestures or widgets to open your vault quickly.- Ads: The app contains ads that may interrupt your experience or consume your data. You can remove them by upgrading to the premium version of the app.
    - Cloud backup: The app allows you to backup and sync your hidden files and apps to cloud service. This way, you can save your storage space and restore your data anytime and anywhere.- Storage space: The app may take up some storage space on your device as it creates copies of your hidden or cloned apps. You may need to clear some space if you have too many hidden or cloned apps.
    -

    Conclusion

    -

    In conclusion, calculator lock it apk is a powerful privacy lock and app hider tool that disguises itself as a normal calculator app. It allows you to hide and lock your private files and apps in a secret vault that only you can access with your password. It also offers many amazing features, such as photo vault, app hider and app locker, cloud storage, private browser and VPN service, perfect disguise, and effective media management. However, it also has some drawbacks, such as compatibility issues, ads, and storage space. Therefore, you should weigh the pros and cons of using calculator lock it apk before downloading and installing it on your device. If you want to use calculator lock it apk effectively, here are some tips or suggestions for you: - Choose a strong and unique password for your calculator vault and do not share it with anyone. - Enable the break-in alert feature to catch any intruders who try to enter your vault with a wrong password. - Backup and sync your hidden files and apps to cloud service regularly to avoid losing them in case of any device problems. - Use the private browser and VPN service to browse privately and download videos from various websites without leaving any traces. - Change the icon of the calculator vault and use a fake notification or a fake error message to disguise it as a normal app. - Manage and edit your hidden files and apps freely within the app and delete any unwanted or unnecessary files or apps to save your storage space.

    FAQs

    -

    Here are some of the frequently asked questions about calculator lock it apk:

    -
      -
    • Q1: Is calculator lock it apk safe to use?
    • -
    • A1: Yes, calculator lock it apk is safe to use as long as you download it from a reliable source and do not share your password with anyone. The app uses AES encryption to secure your hidden files and apps and does not collect or leak any of your personal information.
    • -
    • Q2: How can I recover my password if I forget it?
    • -
    • A2: You can use the email recovery option or the security question option to reset your password if you forget it. You can also contact the customer support team for help if you have any issues with resetting your password.
    • -
    • Q3: How can I access my hidden files and apps outside the calculator vault?
    • -
    • A3: You can access your hidden files and apps outside the calculator vault by using the quick access feature or by creating shortcuts on your home screen. You can also unhide them if you want to use them normally. However, you should be careful not to expose your hidden files and apps to anyone who may access your device.
    • -
    • Q4: How can I hide the icon of the calculator vault?
    • -
    • A4: You can hide the icon of the calculator vault by changing it to another icon that looks like a normal app, such as a clock, a calendar, a music player, etc. You can also use a fake notification or a fake error message to disguise it as a normal app. To access your vault, you just need to tap on the disguised icon and enter your password on the calculator screen.
    • -
    • Q5: How can I transfer my hidden files and apps to another device?
    • -
    • A5: You can transfer your hidden files and apps to another device by using the cloud storage feature or by exporting them to an external storage device. You can also use the share function to send them via email, Bluetooth, or other apps. However, you should make sure that the other device has calculator lock it apk installed and that you have the same password for your vault.
    • -

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Plague Inc Premium APK with All Features Unlocked and No Unlimited DNA.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Plague Inc Premium APK with All Features Unlocked and No Unlimited DNA.md deleted file mode 100644 index 05ea09897d5cd1da0582727416f922945c544fed..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Download Plague Inc Premium APK with All Features Unlocked and No Unlimited DNA.md +++ /dev/null @@ -1,111 +0,0 @@ -
    -

    Plague Inc Premium Apk No Unlimited DNA: A Guide for Beginners

    -

    Have you ever wondered what it would be like to create and spread a deadly disease that could wipe out humanity? If so, you might enjoy playing Plague Inc, a strategy-simulation game that lets you do just that. Plague Inc is one of the most popular games on the iOS App Store and Google Play Store, with over 160 million downloads as of May 2021. The game is so realistic that the CDC even invited the developer to speak about the infection models in the game.

    -

    plague inc premium apk no unlimited dna


    Download Zip »»» https://gohhs.com/2uPmvL



    -

    Plague Inc is a free game, but it also offers a premium version that unlocks more features and content. For example, you can access 10 different disease types, 23 unique scenarios, speed runs, real-life scenarios, and more. However, some players may not like the fact that the premium version also comes with unlimited DNA points, which are used to evolve your disease. Unlimited DNA points can make the game too easy and boring, as you can buy any trait you want without any challenge or strategy.

    -

    If you are one of those players who prefer a more balanced and realistic gameplay experience, you may be interested in downloading Plague Inc premium apk no unlimited DNA. This is a modified version of the game that gives you all the benefits of the premium version without the unlimited DNA points. In this article, we will show you how to download Plague Inc premium apk no unlimited DNA, and give you some tips and tricks for playing the game.

    -

    How to Download Plague Inc Premium Apk No Unlimited DNA

    -

    Before you download Plague Inc premium apk no unlimited DNA, you need to make sure that your device meets the minimum requirements for running the game. You need an Android device with at least Android 4.1 or higher, and at least 100 MB of free storage space. You also need to enable unknown sources in your device settings, so that you can install apps from outside the Google Play Store.

    -

    Next, you need to find a reliable source for downloading Plague Inc premium apk no unlimited DNA. There are many websites that offer apk files for various games and apps, but not all of them are safe and trustworthy. Some of them may contain malware or viruses that can harm your device or steal your personal information. To avoid such risks, we recommend using [APKCombo](^12^), a reputable website that provides free and secure apk downloads for Android users.

    -

    plague inc full version apk without unlimited dna
    -plague inc premium mod apk no infinite dna
    -plague inc unlocked apk no unlimited dna hack
    -plague inc paid apk no unlimited dna cheat
    -plague inc premium apk download no unlimited dna
    -plague inc full unlocked apk no unlimited dna mod
    -plague inc premium cracked apk no unlimited dna
    -plague inc pro apk no unlimited dna free
    -plague inc full apk no unlimited dna latest version
    -plague inc premium hack apk no unlimited dna
    -plague inc premium free apk no unlimited dna
    -plague inc full mod apk no unlimited dna 2023
    -plague inc premium apk mod no unlimited dna android
    -plague inc full cracked apk no unlimited dna update
    -plague inc premium apk no unlimited dna reddit
    -plague inc full free apk no unlimited dna offline
    -plague inc premium modded apk no unlimited dna 2022
    -plague inc premium apk no unlimited dna ios
    -plague inc full hack apk no unlimited dna online
    -plague inc premium unlocked apk no unlimited dna 2021
    -plague inc full version mod apk no unlimited dna
    -plague inc premium apk latest version no unlimited dna
    -plague inc full version hack apk no unlimited dna
    -plague inc premium mod apk download no unlimited dna
    -plague inc full version free apk no unlimited dna
    -plague inc premium hack mod apk no unlimited dna
    -plague inc full version cracked apk no unlimited dna
    -plague inc premium cracked mod apk no unlimited dna
    -plague inc full version unlocked apk no unlimited dna
    -plague inc premium unlocked mod apk no unlimited dna
    -plague inc full version download apk no unlimited dna
    -plague inc premium download mod apk no unlimited dna
    -plague inc full version pro apk no unlimited dna
    -plague inc premium pro mod apk no unlimited dna
    -plague inc full version latest apk no unlimited dna
    -plague inc premium latest mod apk no unlimited dna
    -plague inc full version update apk no unlimited dna
    -plague inc premium update mod apk no unlimited dna
    -plague inc full version offline apk no unlimited dna
    -plague inc premium offline mod apk no unlimited dna
    -plague inc full version online apk no unlimited dna
    -plague inc premium online mod apk no unlimited dna
    -plague inc full version android apk no unlimited dna
    -plague inc premium android mod apk no unlimited dna
    -plague inc full version ios apk no unlimited dna
    -plague inc premium ios mod apk no unlimited dna
    -plague inc full version 2023 apk no unlimited dna
    -plague inc premium 2023 mod apk no unlimited dna

    -

    To download Plague Inc premium apk no unlimited DNA from APKCombo, follow these steps:

    -
      -
    1. Go to [APKCombo](^12^) on your browser.
    2. -
    3. Type "Plague Inc" in the search box and hit enter.
    4. -
    5. Select "Plague Inc" from the list of results.
    6. -
    7. Scroll down to find the latest version of Plague Inc premium apk no unlimited DNA. It should have a file size of about 82 MB.
    8. -
    9. Click on "Download APK" and wait for the download to finish.
    10. -
    -

    Once you have downloaded Plague Inc premium apk no unlimited DNA, you need to install and run it on your device. To do so, follow these steps:

    -
      -
    1. Locate the downloaded apk file on your device's file manager or downloads folder.
    2. -
    3. Tap on the apk file and confirm the installation.
    4. Allow the app to access your device's resources and permissions.
    5. -
    6. Wait for the app to finish installing and launch it.
    7. -
    -

    To verify that the apk has no unlimited DNA, you can check the game settings and see if there is an option to enable or disable unlimited DNA. If there is no such option, then you have successfully installed Plague Inc premium apk no unlimited DNA. You can now enjoy playing the game with all the premium features and content, but without the unlimited DNA points.

    -

    Tips and Tricks for Playing Plague Inc

    -

    Plague Inc is a game that requires a lot of strategy and planning. You need to create and evolve a disease that can infect and kill the entire world population, while avoiding detection and cure by the humans. The game offers different modes, difficulty levels, disease types, and scenarios to challenge your skills and creativity. Here are some tips and tricks for playing Plague Inc:

    -
      -
    • Choose a suitable disease type and starting country. Different disease types have different advantages and disadvantages, such as transmission methods, symptoms, abilities, and mutations. For example, bacteria are more resistant to antibiotics, but more vulnerable to hot and cold climates. Viruses are more prone to random mutations, but harder to cure. Fungi are more difficult to spread, but can release spores to infect new countries. You should also consider the starting country's climate, population, wealth, and health care system. For example, starting in a poor and densely populated country like India or China can help you spread faster, but also attract more attention from the authorities. Starting in a rich and isolated country like Greenland or New Zealand can help you avoid detection, but also limit your infectivity.
    • -
    • Balance infectivity, severity, and lethality. Infectivity is how easily your disease can spread from person to person. Severity is how noticeable and harmful your disease is to the infected people. Lethality is how likely your disease is to kill the infected people. You need to balance these three factors carefully, depending on your strategy and situation. Generally, you want to increase your infectivity first, so that you can reach more countries and people. Then, you want to increase your severity gradually, so that you can earn more DNA points and slow down the cure research. Finally, you want to increase your lethality sharply, so that you can kill everyone before they find a cure.
    • -
    • Adapt to different scenarios and events. Plague Inc has many scenarios and events that can affect your gameplay and outcome. Some of them are based on real-life situations, such as the COVID-19 pandemic, the Black Death, or the zombie apocalypse. Some of them are based on fictional scenarios, such as the Planet of the Apes, the vampire plague, or the necroa virus. You need to adapt your strategy and tactics according to these scenarios and events, as they can change the rules and conditions of the game. For example, in the COVID-19 scenario, you need to deal with lockdowns, social distancing, masks, vaccines, and variants. In the necroa virus scenario, you need to create zombies that can infect and kill humans.
    • -
    -

    Conclusion

    -

    Plague Inc is a fun and challenging game that lets you unleash your inner evil genius. You can create and spread a deadly disease that can wipe out humanity in various ways. You can also enjoy the premium version of the game that unlocks more features and content. However, if you don't like the unlimited DNA points that come with the premium version, you can download Plague Inc premium apk no unlimited DNA instead. This way, you can have a more balanced and realistic gameplay experience.

    -

    If you are interested in downloading Plague Inc premium apk no unlimited DNA, you can follow our guide above on how to find a reliable source, how to install and run the apk file, and how to verify that the apk has no unlimited DNA. You can also use our tips and tricks on how to play Plague Inc effectively and strategically.

    -

    We hope you found this article helpful and informative. If you have any questions or feedback, please feel free to leave a comment below. And if you want to learn more about Plague Inc or support the developer, you can visit their [official website]. Thank you for reading!

    -

    FAQs

    -
      -
    • Is Plague Inc premium apk no unlimited DNA safe?
    • -

      Yes, Plague Inc premium apk no unlimited DNA is safe if you download it from a reputable source like APKCombo. However, you should always be careful when downloading any apk file from unknown sources, as they may contain malware or viruses that can harm your device or steal your personal information.

      -
    • Is Plague Inc premium apk no unlimited DNA legal?
    • Plague Inc premium apk no unlimited DNA is not legal, as it is a modified version of the game that violates the terms and conditions of the developer and the Google Play Store. However, it is unlikely that you will face any legal consequences for downloading and using it, as long as you do not distribute it to others or use it for commercial purposes.

      -
    • What are the benefits of Plague Inc premium apk no unlimited DNA?
    • -

      Plague Inc premium apk no unlimited DNA has many benefits, such as:

      -
        -
      • You can access all the premium features and content of the game, such as 10 different disease types, 23 unique scenarios, speed runs, real-life scenarios, and more.
      • -
      • You can play the game without any ads or in-app purchases.
      • -
      • You can have a more balanced and realistic gameplay experience, as you have to earn your DNA points by infecting and killing people, rather than having unlimited DNA points.
      • -
      -
    • What are the drawbacks of Plague Inc premium apk no unlimited DNA?
    • -

      Plague Inc premium apk no unlimited DNA also has some drawbacks, such as:

      -
        -
      • You may not be able to update the game to the latest version, as the apk file may not be compatible with the new updates.
      • -
      • You may not be able to access some online features of the game, such as multiplayer mode, leaderboards, achievements, and cloud saving.
      • -
      • You may encounter some bugs or glitches in the game, as the apk file may not be optimized for your device or operating system.
      • -
      -
    • How can I get unlimited DNA points in Plague Inc?
    • -

      If you want to get unlimited DNA points in Plague Inc, you have two options:

      -
        -
      • You can buy the premium version of the game from the Google Play Store or the iOS App Store, which gives you unlimited DNA points by default.
      • -
      • You can download Plague Inc premium apk with unlimited DNA from a website like APKCombo, which gives you unlimited DNA points as a modification.
      • -
      -

      However, we do not recommend using unlimited DNA points in Plague Inc, as it can ruin the fun and challenge of the game. It can also make the game too easy and boring, as you can buy any trait you want without any strategy or difficulty.

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/fffiloni/SplitTrack2MusicGen/audiocraft/modules/conv.py b/spaces/fffiloni/SplitTrack2MusicGen/audiocraft/modules/conv.py deleted file mode 100644 index 972938ab84712eb06e1b10cea25444eee51d6637..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/SplitTrack2MusicGen/audiocraft/modules/conv.py +++ /dev/null @@ -1,245 +0,0 @@ -# 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. - -import math -import typing as tp -import warnings - -import torch -from torch import nn -from torch.nn import functional as F -from torch.nn.utils import spectral_norm, weight_norm - - -CONV_NORMALIZATIONS = frozenset(['none', 'weight_norm', 'spectral_norm', - 'time_group_norm']) - - -def apply_parametrization_norm(module: nn.Module, norm: str = 'none'): - assert norm in CONV_NORMALIZATIONS - if norm == 'weight_norm': - return weight_norm(module) - elif norm == 'spectral_norm': - return spectral_norm(module) - else: - # We already check was in CONV_NORMALIZATION, so any other choice - # doesn't need reparametrization. - return module - - -def get_norm_module(module: nn.Module, causal: bool = False, norm: str = 'none', **norm_kwargs): - """Return the proper normalization module. If causal is True, this will ensure the returned - module is causal, or return an error if the normalization doesn't support causal evaluation. - """ - assert norm in CONV_NORMALIZATIONS - if norm == 'time_group_norm': - if causal: - raise ValueError("GroupNorm doesn't support causal evaluation.") - assert isinstance(module, nn.modules.conv._ConvNd) - return nn.GroupNorm(1, module.out_channels, **norm_kwargs) - else: - return nn.Identity() - - -def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int, - padding_total: int = 0) -> int: - """See `pad_for_conv1d`. - """ - length = x.shape[-1] - n_frames = (length - kernel_size + padding_total) / stride + 1 - ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total) - return ideal_length - length - - -def pad_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int, padding_total: int = 0): - """Pad for a convolution to make sure that the last window is full. - Extra padding is added at the end. This is required to ensure that we can rebuild - an output of the same length, as otherwise, even with padding, some time steps - might get removed. - For instance, with total padding = 4, kernel size = 4, stride = 2: - 0 0 1 2 3 4 5 0 0 # (0s are padding) - 1 2 3 # (output frames of a convolution, last 0 is never used) - 0 0 1 2 3 4 5 0 # (output of tr. conv., but pos. 5 is going to get removed as padding) - 1 2 3 4 # once you removed padding, we are missing one time step ! - """ - extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total) - return F.pad(x, (0, extra_padding)) - - -def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'constant', value: float = 0.): - """Tiny wrapper around F.pad, just to allow for reflect padding on small input. - If this is the case, we insert extra 0 padding to the right before the reflection happen. - """ - length = x.shape[-1] - padding_left, padding_right = paddings - assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right) - if mode == 'reflect': - max_pad = max(padding_left, padding_right) - extra_pad = 0 - if length <= max_pad: - extra_pad = max_pad - length + 1 - x = F.pad(x, (0, extra_pad)) - padded = F.pad(x, paddings, mode, value) - end = padded.shape[-1] - extra_pad - return padded[..., :end] - else: - return F.pad(x, paddings, mode, value) - - -def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]): - """Remove padding from x, handling properly zero padding. Only for 1d! - """ - padding_left, padding_right = paddings - assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right) - assert (padding_left + padding_right) <= x.shape[-1] - end = x.shape[-1] - padding_right - return x[..., padding_left: end] - - -class NormConv1d(nn.Module): - """Wrapper around Conv1d and normalization applied to this conv - to provide a uniform interface across normalization approaches. - """ - def __init__(self, *args, causal: bool = False, norm: str = 'none', - norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs): - super().__init__() - self.conv = apply_parametrization_norm(nn.Conv1d(*args, **kwargs), norm) - self.norm = get_norm_module(self.conv, causal, norm, **norm_kwargs) - self.norm_type = norm - - def forward(self, x): - x = self.conv(x) - x = self.norm(x) - return x - - -class NormConv2d(nn.Module): - """Wrapper around Conv2d and normalization applied to this conv - to provide a uniform interface across normalization approaches. - """ - def __init__(self, *args, norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs): - super().__init__() - self.conv = apply_parametrization_norm(nn.Conv2d(*args, **kwargs), norm) - self.norm = get_norm_module(self.conv, causal=False, norm=norm, **norm_kwargs) - self.norm_type = norm - - def forward(self, x): - x = self.conv(x) - x = self.norm(x) - return x - - -class NormConvTranspose1d(nn.Module): - """Wrapper around ConvTranspose1d and normalization applied to this conv - to provide a uniform interface across normalization approaches. - """ - def __init__(self, *args, causal: bool = False, norm: str = 'none', - norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs): - super().__init__() - self.convtr = apply_parametrization_norm(nn.ConvTranspose1d(*args, **kwargs), norm) - self.norm = get_norm_module(self.convtr, causal, norm, **norm_kwargs) - self.norm_type = norm - - def forward(self, x): - x = self.convtr(x) - x = self.norm(x) - return x - - -class NormConvTranspose2d(nn.Module): - """Wrapper around ConvTranspose2d and normalization applied to this conv - to provide a uniform interface across normalization approaches. - """ - def __init__(self, *args, norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs): - super().__init__() - self.convtr = apply_parametrization_norm(nn.ConvTranspose2d(*args, **kwargs), norm) - self.norm = get_norm_module(self.convtr, causal=False, norm=norm, **norm_kwargs) - - def forward(self, x): - x = self.convtr(x) - x = self.norm(x) - return x - - -class StreamableConv1d(nn.Module): - """Conv1d with some builtin handling of asymmetric or causal padding - and normalization. - """ - def __init__(self, in_channels: int, out_channels: int, - kernel_size: int, stride: int = 1, dilation: int = 1, - groups: int = 1, bias: bool = True, causal: bool = False, - norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {}, - pad_mode: str = 'reflect'): - super().__init__() - # warn user on unusual setup between dilation and stride - if stride > 1 and dilation > 1: - warnings.warn('StreamableConv1d has been initialized with stride > 1 and dilation > 1' - f' (kernel_size={kernel_size} stride={stride}, dilation={dilation}).') - self.conv = NormConv1d(in_channels, out_channels, kernel_size, stride, - dilation=dilation, groups=groups, bias=bias, causal=causal, - norm=norm, norm_kwargs=norm_kwargs) - self.causal = causal - self.pad_mode = pad_mode - - def forward(self, x): - B, C, T = x.shape - kernel_size = self.conv.conv.kernel_size[0] - stride = self.conv.conv.stride[0] - dilation = self.conv.conv.dilation[0] - kernel_size = (kernel_size - 1) * dilation + 1 # effective kernel size with dilations - padding_total = kernel_size - stride - extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total) - if self.causal: - # Left padding for causal - x = pad1d(x, (padding_total, extra_padding), mode=self.pad_mode) - else: - # Asymmetric padding required for odd strides - padding_right = padding_total // 2 - padding_left = padding_total - padding_right - x = pad1d(x, (padding_left, padding_right + extra_padding), mode=self.pad_mode) - return self.conv(x) - - -class StreamableConvTranspose1d(nn.Module): - """ConvTranspose1d with some builtin handling of asymmetric or causal padding - and normalization. - """ - def __init__(self, in_channels: int, out_channels: int, - kernel_size: int, stride: int = 1, causal: bool = False, - norm: str = 'none', trim_right_ratio: float = 1., - norm_kwargs: tp.Dict[str, tp.Any] = {}): - super().__init__() - self.convtr = NormConvTranspose1d(in_channels, out_channels, kernel_size, stride, - causal=causal, norm=norm, norm_kwargs=norm_kwargs) - self.causal = causal - self.trim_right_ratio = trim_right_ratio - assert self.causal or self.trim_right_ratio == 1., \ - "`trim_right_ratio` != 1.0 only makes sense for causal convolutions" - assert self.trim_right_ratio >= 0. and self.trim_right_ratio <= 1. - - def forward(self, x): - kernel_size = self.convtr.convtr.kernel_size[0] - stride = self.convtr.convtr.stride[0] - padding_total = kernel_size - stride - - y = self.convtr(x) - - # We will only trim fixed padding. Extra padding from `pad_for_conv1d` would be - # removed at the very end, when keeping only the right length for the output, - # as removing it here would require also passing the length at the matching layer - # in the encoder. - if self.causal: - # Trim the padding on the right according to the specified ratio - # if trim_right_ratio = 1.0, trim everything from right - padding_right = math.ceil(padding_total * self.trim_right_ratio) - padding_left = padding_total - padding_right - y = unpad1d(y, (padding_left, padding_right)) - else: - # Asymmetric padding required for odd strides - padding_right = padding_total // 2 - padding_left = padding_total - padding_right - y = unpad1d(y, (padding_left, padding_right)) - return y diff --git a/spaces/flax-community/Multilingual-VQA/sections/references/papers.md b/spaces/flax-community/Multilingual-VQA/sections/references/papers.md deleted file mode 100644 index b8f503dfbf453c744391cc1b1fb75556ee3a8e35..0000000000000000000000000000000000000000 --- a/spaces/flax-community/Multilingual-VQA/sections/references/papers.md +++ /dev/null @@ -1,78 +0,0 @@ -``` -@inproceedings{wolf-etal-2020-transformers, - title = "Transformers: State-of-the-Art Natural Language Processing", - author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush", - booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations", - month = oct, - year = "2020", - address = "Online", - publisher = "Association for Computational Linguistics", - url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6", - pages = "38--45" -} -``` -``` -@inproceedings{changpinyo2021cc12m, - title = {{Conceptual 12M}: Pushing Web-Scale Image-Text Pre-Training To Recognize Long-Tail Visual Concepts}, - author = {Changpinyo, Soravit and Sharma, Piyush and Ding, Nan and Soricut, Radu}, - booktitle = {CVPR}, - year = {2021}, -} -``` -``` -@InProceedings{mariannmt, - title = {Marian: Fast Neural Machine Translation in {C++}}, - author = {Junczys-Dowmunt, Marcin and Grundkiewicz, Roman and - Dwojak, Tomasz and Hoang, Hieu and Heafield, Kenneth and - Neckermann, Tom and Seide, Frank and Germann, Ulrich and - Fikri Aji, Alham and Bogoychev, Nikolay and - Martins, Andr\'{e} F. T. and Birch, Alexandra}, - booktitle = {Proceedings of ACL 2018, System Demonstrations}, - pages = {116--121}, - publisher = {Association for Computational Linguistics}, - year = {2018}, - month = {July}, - address = {Melbourne, Australia}, - url = {http://www.aclweb.org/anthology/P18-4020} -} -``` -``` -@misc{agrawal2016vqa, - title={VQA: Visual Question Answering}, - author={Aishwarya Agrawal and Jiasen Lu and Stanislaw Antol and Margaret Mitchell and C. Lawrence Zitnick and Dhruv Batra and Devi Parikh}, - year={2016}, - eprint={1505.00468}, - archivePrefix={arXiv}, - primaryClass={cs.CL} -} -``` -``` -@misc{li2019visualbert, - title={VisualBERT: A Simple and Performant Baseline for Vision and Language}, - author={Liunian Harold Li and Mark Yatskar and Da Yin and Cho-Jui Hsieh and Kai-Wei Chang}, - year={2019}, - eprint={1908.03557}, - archivePrefix={arXiv}, - primaryClass={cs.CV} -} -``` -``` -@misc{vaswani2017attention, - title={Attention Is All You Need}, - author={Ashish Vaswani and Noam Shazeer and Niki Parmar and Jakob Uszkoreit and Llion Jones and Aidan N. Gomez and Lukasz Kaiser and Illia Polosukhin}, - year={2017}, - eprint={1706.03762}, - archivePrefix={arXiv}, - primaryClass={cs.CL} -} -``` -``` -@misc{radford2021learning, - title={Learning Transferable Visual Models From Natural Language Supervision}, - author={Alec Radford and Jong Wook Kim and Chris Hallacy and Aditya Ramesh and Gabriel Goh and Sandhini Agarwal and Girish Sastry and Amanda Askell and Pamela Mishkin and Jack Clark and Gretchen Krueger and Ilya Sutskever}, - year={2021}, - eprint={2103.00020}, - archivePrefix={arXiv}, - primaryClass={cs.CV} -} -``` \ No newline at end of file diff --git a/spaces/flax-community/alberti/poems.py b/spaces/flax-community/alberti/poems.py deleted file mode 100644 index 653598bd0f86f8aeea76ef43f150c9196e4e64b7..0000000000000000000000000000000000000000 --- a/spaces/flax-community/alberti/poems.py +++ /dev/null @@ -1,181 +0,0 @@ -SAMPLE_POEMS = { - "fr_1": [ - "C'est un trou de verdure où chante une rivière", - "Accrochant follement aux herbes des haillons", - "D'argent ; où le soleil, de la montagne fière,", - "Luit : c'est un petit val qui mousse de rayons.", - "", - "Un soldat jeune, bouche ouverte, tête nue,", - "Et la nuque baignant dans le frais cresson bleu,", - "Dort ; il est étendu dans l'herbe sous la nue,", - "Pâle dans son lit vert où la lumière pleut.", - "", - "Les pieds dans les glaïeuls, il dort. Souriant comme", - "Sourirait un enfant malade, il fait un somme:", - "Nature, berce-le chaudement: il a froid.", - "", - "Les parfums ne font pas frissonner sa narine;", - "Il dort dans le soleil, la main sur sa poitrine,", - "Tranquille. Il a deux trous rouges au côté droit."], - "fr_2": [ - "Demain, dès l'aube, à l'heure où blanchit la campagne,", - "Je partirai. Vois-tu, je sais que tu m'attends.", - "J'irai par la forêt, j'irai par la montagne.", - "Je ne puis demeurer loin de toi plus longtemps.", - "", - "Je marcherai les yeux fixés sur mes pensées,", - "Sans rien voir au dehors, sans entendre aucun bruit,", - "Seul, inconnu, le dos courbé, les mains croisées,", - "Triste, et le jour pour moi sera comme la nuit.", - "", - "Je ne regarderai ni l'or du soir qui tombe,", - "Ni les voiles au loin descendant vers Harfleur,", - "Et quand j'arriverai, je mettrai sur ta tombe", - "Un bouquet de houx vert et de bruyère en fleur."], - "es_1": [ - "A través del follaje perenne", - "Que oír deja rumores extraños,", - "Y entre un mar de ondulante verdura,", - "Amorosa mansión de los pájaros,", - "Desde mis ventanas veo", - "El templo que quise tanto.", - "", - "El templo que tanto quise...", - "Pues no sé decir ya si le quiero,", - "Que en el rudo vaivén que sin tregua", - "Se agitan mis pensamientos,", - "Dudo si el rencor adusto", - "Vive unido al amor en mi pecho."], - "es_2": [ - "Es hielo abrasador, es fuego helado,", - "es herida que duele y no se siente,", - "es un soñado bien, un mal presente,", - "es un breve descanso muy cansado.", - "", - "Es un descuido que nos da cuidado,", - "un cobarde con nombre de valiente,", - "un andar solitario entre la gente,", - "un amar solamente ser amado.", - "", - "Es una libertad encarcelada,", - "que dura hasta el postrero paroxismo;", - "enfermedad que crece si es curada.", - "Éste es el niño Amor, éste es su abismo.", - "¿Mirad cuál amistad tendrá con nada", - "el que en todo es contrario de sí mismo!"], - "en_1": [ - "Two roads diverged in a yellow wood,", - "And sorry I could not travel both", - "And be one traveler, long I stood", - "And looked down one as far as I could", - "To where it bent in the undergrowth;", - "", - "Then took the other, as just as fair,", - "And having perhaps the better claim,", - "Because it was grassy and wanted wear;", - "Though as for that the passing there", - "Had worn them really about the same,", - "", - "And both that morning equally lay", - "In leaves no step had trodden black.", - "Oh, I kept the first for another day!", - "Yet knowing how way leads on to way,", - "I doubted if I should ever come back.", - "", - "I shall be telling this with a sigh", - "Somewhere ages and ages hence:", - "Two roads diverged in a wood, and I—", - "I took the one less traveled by,", - "And that has made all the difference."], - "en_2": [ - "Because I could not stop for Death -", - "He kindly stopped for me -", - "The Carriage held but just Ourselves -", - "And Immortality.", - "", - "We slowly drove - He knew no haste", - "And I had put away", - "My labor and my leisure too,", - "For His Civility -", - "", - "We passed the School, where Children strove", - "At Recess - in the Ring -", - "We passed the Fields of Gazing Grain -", - "We passed the Setting Sun -", - "", - "Or rather - He passed Us -", - "The Dews drew quivering and Chill -", - "For only Gossamer, my Gown -", - "My Tippet - only Tulle -", - "", - "We paused before a House that seemed", - "A Swelling of the Ground -", - "The Roof was scarcely visible -", - "The Cornice - in the Ground -", - "", - "Since then - 'tis Centuries - and yet", - "Feels shorter than the Day", - "I first surmised the Horses' Heads", - "Were toward Eternity -"], - "de_1": [ - "Der du von dem Himmel bist,", - "Alles Leid und Schmerzen stillest,", - "Den, der doppelt elend ist,", - "Doppelt mit Erquickung füllest;", - "Ach, ich bin des Treibens müde!", - "Was soll all der Schmerz und Lust?", - "Süßer Friede,", - "Komm, ach komm in meine Brust!"], - "de_2": [ - "Wieder duftet der Wald. ", - "Es heben die schwebenden Lerchen", - "mit sich den Himmel empor, der unseren Schultern schwer war; ", - "zwar sah man noch durch die Äste den Tag, wie er leer war,- ", - "aber nach langen, regnenden Nachmittagen ", - "kommen die goldübersonnten ", - "neueren Stunden, ", - "vor denen flüchtend an fernen Häuserfronten ", - "alle die wunden Fenster furchtsam mit Flügeln schlagen. ", - "Dann wird es still. Sogar der Regen geht leiser", - "über der Steine ruhig dunkelnden Glanz.", - "Alle Geräusche ducken sich ganz", - "in die glänzenden Knospen der Reiser."], - "zh_1": [ - "春眠不觉晓,", - "处处闻啼鸟。", - "", - "夜来风雨声,", - "花落知多少"], - "zh_2": [ - "关关雎鸠,在河之洲。", - "窈窕淑女,君子好逑。", - "", - "参差荇菜,左右流之。", - "窈窕淑女,寤寐求之。", - "", - "求之不得,寤寐思服。", - "悠哉悠哉,辗转反侧。", - "", - "参差荇菜,左右采之。", - "窈窕淑女,琴瑟友之。", - "", - "参差荇菜,左右毛之。", - "窈窕淑女,钟鼓乐之。"], - "ar_1": [ - "داب نعشق لأليمه نجيمه", - "من يحبك ويموت فيك", - "إن قتلت عاد يكون بيك", - "لو قدر قلبي يخليك", - "لم يدبّر ذا النُّغيمة", - "يا مطرنَنِ شِلِباطُ (يا مذهول)", - "تُن حزين تنِ بناطُ (إنك مكروب)", - "ترى اليوم وَشْطاطُ (ضائعاً)", - "لم تذقي فيه غير لقيمة"], - "ar_2": [ - "حَيّوا تُماضِرَ وَاِربَعوا صَحبي\t\tوَقِفوا فَإِنَّ وُقوفَكُم حَسبي", - "أَخُناسُ قَد هامَ الفُؤادُ بِكُم\t\tوَأَصابَهُ تَبَلٌ مِنَ الحُبِّ", - "ما إِن رَأَيتُ وَلا سَمِعتُ بِهِ\t\tكَاليَومِ طالي أَينُقٍ جُربِ", - "مُتَبَذِّلاً تَبدو مَحاسِنُهُ\t\tضَعُ الهِناءَ مَواضِعَ النُقبِ", - "مُتَحَسِّراً نَضَحَ الهِناءَ بِهِ\t\tضحَ العَبيرِ بِرَيطَةِ العَصبِ", - "فَسَليهُمُ عَنّي خُناسُ إِذا\t\tعَضَّ الجَميعَ الخَطبُ ما خَطبي"] -} \ No newline at end of file diff --git a/spaces/florim/MedGPT/tests/context.py b/spaces/florim/MedGPT/tests/context.py deleted file mode 100644 index cef969db69ab189109b935bba9ed06696cf5337a..0000000000000000000000000000000000000000 --- a/spaces/florim/MedGPT/tests/context.py +++ /dev/null @@ -1,6 +0,0 @@ -import os -import sys - -sys.path.insert( - 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../scripts")) -) diff --git a/spaces/fracapuano/NebulOS/src/__init__.py b/spaces/fracapuano/NebulOS/src/__init__.py deleted file mode 100644 index 793ea119520df48448c151fbca581fab7f43a5ab..0000000000000000000000000000000000000000 --- a/spaces/fracapuano/NebulOS/src/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .hw_nats_fast_interface import * -from .genetics import * -from .utils import * \ No newline at end of file diff --git a/spaces/freddyaboulton/all_demos_3/demos/interface_random_slider/run.py b/spaces/freddyaboulton/all_demos_3/demos/interface_random_slider/run.py deleted file mode 100644 index 9965e1f35ac6df15fedb5205aaecfe3d46b09209..0000000000000000000000000000000000000000 --- a/spaces/freddyaboulton/all_demos_3/demos/interface_random_slider/run.py +++ /dev/null @@ -1,23 +0,0 @@ -import gradio as gr - - -def func(slider_1, slider_2): - return slider_1 + slider_2 * 5 - - -demo = gr.Interface( - func, - [ - gr.Slider(minimum=1.5, maximum=250000.89, randomize=True, label="Random Big Range"), - gr.Slider(minimum=-1, maximum=1, randomize=True, step=0.05, label="Random only multiple of 0.05 allowed"), - gr.Slider(minimum=0, maximum=1, randomize=True, step=0.25, label="Random only multiples of 0.25 allowed"), - gr.Slider(minimum=-100, maximum=100, randomize=True, step=3, label="Random between -100 and 100 step 3"), - gr.Slider(minimum=-100, maximum=100, randomize=True, label="Random between -100 and 100"), - gr.Slider(value=0.25, minimum=5, maximum=30, step=-1), - ], - "number", - interpretation="default" -) - -if __name__ == "__main__": - demo.launch() diff --git a/spaces/fun-research/FC-CLIP/fcclip/evaluation/instance_evaluation.py b/spaces/fun-research/FC-CLIP/fcclip/evaluation/instance_evaluation.py deleted file mode 100644 index 1dfb821dd248a0c8202c4f50b0a85d6adb53f8d5..0000000000000000000000000000000000000000 --- a/spaces/fun-research/FC-CLIP/fcclip/evaluation/instance_evaluation.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import contextlib -import copy -import io -import itertools -import json -import logging -import numpy as np -import os -import pickle -from collections import OrderedDict -import pycocotools.mask as mask_util -import torch -from pycocotools.coco import COCO -from pycocotools.cocoeval import COCOeval -from tabulate import tabulate - -import detectron2.utils.comm as comm -from detectron2.config import CfgNode -from detectron2.data import MetadataCatalog -from detectron2.data.datasets.coco import convert_to_coco_json -from detectron2.evaluation.coco_evaluation import COCOEvaluator, _evaluate_predictions_on_coco -from detectron2.evaluation.fast_eval_api import COCOeval_opt -from detectron2.structures import Boxes, BoxMode, pairwise_iou -from detectron2.utils.file_io import PathManager -from detectron2.utils.logger import create_small_table - - -# modified from COCOEvaluator for instance segmetnat -class InstanceSegEvaluator(COCOEvaluator): - """ - Evaluate AR for object proposals, AP for instance detection/segmentation, AP - for keypoint detection outputs using COCO's metrics. - See http://cocodataset.org/#detection-eval and - http://cocodataset.org/#keypoints-eval to understand its metrics. - The metrics range from 0 to 100 (instead of 0 to 1), where a -1 or NaN means - the metric cannot be computed (e.g. due to no predictions made). - - In addition to COCO, this evaluator is able to support any bounding box detection, - instance segmentation, or keypoint detection dataset. - """ - - def _eval_predictions(self, predictions, img_ids=None): - """ - Evaluate predictions. Fill self._results with the metrics of the tasks. - """ - self._logger.info("Preparing results for COCO format ...") - coco_results = list(itertools.chain(*[x["instances"] for x in predictions])) - tasks = self._tasks or self._tasks_from_predictions(coco_results) - - # unmap the category ids for COCO - if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"): - dataset_id_to_contiguous_id = self._metadata.thing_dataset_id_to_contiguous_id - # all_contiguous_ids = list(dataset_id_to_contiguous_id.values()) - # num_classes = len(all_contiguous_ids) - # assert min(all_contiguous_ids) == 0 and max(all_contiguous_ids) == num_classes - 1 - - reverse_id_mapping = {v: k for k, v in dataset_id_to_contiguous_id.items()} - for result in coco_results: - category_id = result["category_id"] - # assert category_id < num_classes, ( - # f"A prediction has class={category_id}, " - # f"but the dataset only has {num_classes} classes and " - # f"predicted class id should be in [0, {num_classes - 1}]." - # ) - assert category_id in reverse_id_mapping, ( - f"A prediction has class={category_id}, " - f"but the dataset only has class ids in {dataset_id_to_contiguous_id}." - ) - result["category_id"] = reverse_id_mapping[category_id] - - if self._output_dir: - file_path = os.path.join(self._output_dir, "coco_instances_results.json") - self._logger.info("Saving results to {}".format(file_path)) - with PathManager.open(file_path, "w") as f: - f.write(json.dumps(coco_results)) - f.flush() - - if not self._do_evaluation: - self._logger.info("Annotations are not available for evaluation.") - return - - self._logger.info( - "Evaluating predictions with {} COCO API...".format( - "unofficial" if self._use_fast_impl else "official" - ) - ) - for task in sorted(tasks): - assert task in {"bbox", "segm", "keypoints"}, f"Got unknown task: {task}!" - coco_eval = ( - _evaluate_predictions_on_coco( - self._coco_api, - coco_results, - task, - kpt_oks_sigmas=self._kpt_oks_sigmas, - #use_fast_impl=self._use_fast_impl, - img_ids=img_ids, - max_dets_per_image=self._max_dets_per_image, - ) - if len(coco_results) > 0 - else None # cocoapi does not handle empty results very well - ) - - res = self._derive_coco_results( - coco_eval, task, class_names=self._metadata.get("thing_classes") - ) - self._results[task] = res diff --git a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/configs/_base_/models/fcn_unet_s5-d16.py b/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/configs/_base_/models/fcn_unet_s5-d16.py deleted file mode 100644 index a33e7972877f902d0e7d18401ca675e3e4e60a18..0000000000000000000000000000000000000000 --- a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/configs/_base_/models/fcn_unet_s5-d16.py +++ /dev/null @@ -1,51 +0,0 @@ -# model settings -norm_cfg = dict(type='SyncBN', requires_grad=True) -model = dict( - type='EncoderDecoder', - pretrained=None, - backbone=dict( - type='UNet', - in_channels=3, - base_channels=64, - num_stages=5, - strides=(1, 1, 1, 1, 1), - enc_num_convs=(2, 2, 2, 2, 2), - dec_num_convs=(2, 2, 2, 2), - downsamples=(True, True, True, True), - enc_dilations=(1, 1, 1, 1, 1), - dec_dilations=(1, 1, 1, 1), - with_cp=False, - conv_cfg=None, - norm_cfg=norm_cfg, - act_cfg=dict(type='ReLU'), - upsample_cfg=dict(type='InterpConv'), - norm_eval=False), - decode_head=dict( - type='FCNHead', - in_channels=64, - in_index=4, - channels=64, - num_convs=1, - concat_input=False, - dropout_ratio=0.1, - num_classes=2, - norm_cfg=norm_cfg, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), - auxiliary_head=dict( - type='FCNHead', - in_channels=128, - in_index=3, - channels=64, - num_convs=1, - concat_input=False, - dropout_ratio=0.1, - num_classes=2, - norm_cfg=norm_cfg, - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), - # model training and testing settings - train_cfg=dict(), - test_cfg=dict(mode='slide', crop_size=256, stride=170)) diff --git a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmseg/datasets/pipelines/compose.py b/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmseg/datasets/pipelines/compose.py deleted file mode 100644 index cbfcbb925c6d4ebf849328b9f94ef6fc24359bf5..0000000000000000000000000000000000000000 --- a/spaces/georgefen/Face-Landmark-ControlNet/annotator/uniformer/mmseg/datasets/pipelines/compose.py +++ /dev/null @@ -1,51 +0,0 @@ -import collections - -from annotator.uniformer.mmcv.utils import build_from_cfg - -from ..builder import PIPELINES - - -@PIPELINES.register_module() -class Compose(object): - """Compose multiple transforms sequentially. - - Args: - transforms (Sequence[dict | callable]): Sequence of transform object or - config dict to be composed. - """ - - def __init__(self, transforms): - assert isinstance(transforms, collections.abc.Sequence) - self.transforms = [] - for transform in transforms: - if isinstance(transform, dict): - transform = build_from_cfg(transform, PIPELINES) - self.transforms.append(transform) - elif callable(transform): - self.transforms.append(transform) - else: - raise TypeError('transform must be callable or a dict') - - def __call__(self, data): - """Call function to apply transforms sequentially. - - Args: - data (dict): A result dict contains the data to transform. - - Returns: - dict: Transformed data. - """ - - for t in self.transforms: - data = t(data) - if data is None: - return None - return data - - def __repr__(self): - format_string = self.__class__.__name__ + '(' - for t in self.transforms: - format_string += '\n' - format_string += f' {t}' - format_string += '\n)' - return format_string diff --git a/spaces/georgefen/Face-Landmark-ControlNet/ldm/modules/midas/__init__.py b/spaces/georgefen/Face-Landmark-ControlNet/ldm/modules/midas/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/gotiQspiryo/whisper-ui/examples/Mark Of Calth Pdf Download [Extra Quality].md b/spaces/gotiQspiryo/whisper-ui/examples/Mark Of Calth Pdf Download [Extra Quality].md deleted file mode 100644 index f4e1abdd188c6cf721bf53cf88fafab5c2cdc1e0..0000000000000000000000000000000000000000 --- a/spaces/gotiQspiryo/whisper-ui/examples/Mark Of Calth Pdf Download [Extra Quality].md +++ /dev/null @@ -1,6 +0,0 @@ -

      Mark Of Calth Pdf Download


      Download Zip ☆☆☆ https://urlgoal.com/2uyMLR



      -
      - aaccfb2cb3
      -
      -
      -

      diff --git a/spaces/gradio/HuBERT/examples/m2m_100/tokenizers/tokenizer_ar.sh b/spaces/gradio/HuBERT/examples/m2m_100/tokenizers/tokenizer_ar.sh deleted file mode 100644 index ad35d7adf28dc9b23d13a6a3fec0b12cb760e855..0000000000000000000000000000000000000000 --- a/spaces/gradio/HuBERT/examples/m2m_100/tokenizers/tokenizer_ar.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env sh -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. -# -# Please follow the instructions here http://alt.qcri.org/tools/arabic-normalizer/ -# to install tools needed for Arabic - -echo "Please install Arabic tools: http://alt.qcri.org/tools/arabic-normalizer/" -echo "Then update environment variables in tokenizer_ar.sh" -exit 1 - -SVMTOOL=... -GOMOSESGO=... -QCRI_ARABIC_NORMALIZER=... - -export PERL5LIB="$SVMTOOL/lib":"$GOMOSESGO/bin/MADA-3.2":$PERL5LIB - - -tempfile=$(mktemp) -cat - > $tempfile - -cd $QCRI_ARABIC_NORMALIZER - -bash qcri_normalizer_mada3.2_aramorph1.2.1.sh $tempfile -cat $tempfile.mada_norm-aramorph.europarl_tok diff --git a/spaces/gyugnsu/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/__init__.py b/spaces/gyugnsu/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/gyugnsu/DragGan-Inversion/stylegan_human/training_scripts/sg2/training/dataset.py b/spaces/gyugnsu/DragGan-Inversion/stylegan_human/training_scripts/sg2/training/dataset.py deleted file mode 100644 index cfb6ff76e18cb42a9493e2ddae1d843895acdadc..0000000000000000000000000000000000000000 --- a/spaces/gyugnsu/DragGan-Inversion/stylegan_human/training_scripts/sg2/training/dataset.py +++ /dev/null @@ -1,271 +0,0 @@ -# Copyright (c) SenseTime Research. All rights reserved. - -# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -# -# NVIDIA CORPORATION and its licensors retain all intellectual property -# and proprietary rights in and to this software, related documentation -# and any modifications thereto. Any use, reproduction, disclosure or -# distribution of this software and related documentation without an express -# license agreement from NVIDIA CORPORATION is strictly prohibited. - -import os -import numpy as np -import zipfile -import PIL.Image -import json -import torch -import dnnlib -import cv2 -from collections import Counter - - -try: - import pyspng -except ImportError: - pyspng = None - -# ---------------------------------------------------------------------------- - - -class Dataset(torch.utils.data.Dataset): - def __init__(self, - name, # Name of the dataset. - raw_shape, # Shape of the raw image data (NCHW). - # Artificially limit the size of the dataset. None = no limit. Applied before xflip. - max_size=None, - # Enable conditioning labels? False = label dimension is zero. - use_labels=False, - # Artificially double the size of the dataset via x-flips. Applied after max_size. - xflip=False, - # Random seed to use when applying max_size. - random_seed=0, - square=False, - ): - # print(' Inside Dataset ') - self._name = name - self._raw_shape = list(raw_shape) - self._use_labels = use_labels - self._raw_labels = None - self._label_shape = None - self._square = square - - # Apply max_size. - self._raw_idx = np.arange(self._raw_shape[0], dtype=np.int64) - if (max_size is not None) and (self._raw_idx.size > max_size): - np.random.RandomState(random_seed).shuffle(self._raw_idx) - self._raw_idx = np.sort(self._raw_idx[:max_size]) - - # Apply xflip. - self._xflip = np.zeros(self._raw_idx.size, dtype=np.uint8) - if xflip: - self._raw_idx = np.tile(self._raw_idx, 2) - self._xflip = np.concatenate( - [self._xflip, np.ones_like(self._xflip)]) - - def _get_raw_labels(self): - if self._raw_labels is None: - self._raw_labels = self._load_raw_labels() if self._use_labels else None - if self._raw_labels is None: - self._raw_labels = np.zeros( - [self._raw_shape[0], 0], dtype=np.float32) - assert isinstance(self._raw_labels, np.ndarray) - assert self._raw_labels.shape[0] == self._raw_shape[0] - assert self._raw_labels.dtype in [np.float32, np.int64] - if self._raw_labels.dtype == np.int64: - assert self._raw_labels.ndim == 1 - assert np.all(self._raw_labels >= 0) - return self._raw_labels - - def close(self): # to be overridden by subclass - pass - - def _load_raw_image(self, raw_idx): # to be overridden by subclass - raise NotImplementedError - - def _load_raw_labels(self): # to be overridden by subclass - raise NotImplementedError - - def __getstate__(self): - return dict(self.__dict__, _raw_labels=None) - - def __del__(self): - try: - self.close() - except: - pass - - def __len__(self): - return self._raw_idx.size - - def __getitem__(self, idx): - image = self._load_raw_image(self._raw_idx[idx]) - assert isinstance(image, np.ndarray) - assert list(image.shape) == self.image_shape - assert image.dtype == np.uint8 - if self._xflip[idx]: - assert image.ndim == 3 # CHW - image = image[:, :, ::-1] - return image.copy(), self.get_label(idx) - - def get_label(self, idx): - label = self._get_raw_labels()[self._raw_idx[idx]] - if label.dtype == np.int64: - onehot = np.zeros(self.label_shape, dtype=np.float32) - onehot[label] = 1 - label = onehot - return label.copy() - - def get_details(self, idx): - d = dnnlib.EasyDict() - d.raw_idx = int(self._raw_idx[idx]) - d.xflip = (int(self._xflip[idx]) != 0) - d.raw_label = self._get_raw_labels()[d.raw_idx].copy() - return d - - @property - def name(self): - return self._name - - @property - def image_shape(self): - return list(self._raw_shape[1:]) - - @property - def num_channels(self): - assert len(self.image_shape) == 3 # CHW - return self.image_shape[0] - - @property - def resolution(self): - assert len(self.image_shape) == 3 # CHW - if self._square: - assert self.image_shape[1] == self.image_shape[2] - else: - assert self.image_shape[1] == self.image_shape[2] * 2 - return self.image_shape[1] - - @property - def label_shape(self): - if self._label_shape is None: - raw_labels = self._get_raw_labels() - if raw_labels.dtype == np.int64: - self._label_shape = [int(np.max(raw_labels)) + 1] - else: - self._label_shape = raw_labels.shape[1:] - return list(self._label_shape) - - @property - def label_dim(self): - assert len(self.label_shape) == 1 - return self.label_shape[0] - - @property - def has_labels(self): - return any(x != 0 for x in self.label_shape) - - @property - def has_onehot_labels(self): - return self._get_raw_labels().dtype == np.int64 - -# ---------------------------------------------------------------------------- - - -class ImageFolderDataset(Dataset): - def __init__(self, - path, # Path to directory or zip. - # Ensure specific resolution, None = highest available. - resolution=None, - square=False, - # Additional arguments for the Dataset base class. - **super_kwargs, - ): - self._path = path - self._zipfile = None - self._square = square - - if os.path.isdir(self._path): - self._type = 'dir' - self._all_fnames = {os.path.relpath(os.path.join( - root, fname), start=self._path) for root, _dirs, files in os.walk(self._path) for fname in files} - elif self._file_ext(self._path) == '.zip': - self._type = 'zip' - self._all_fnames = set(self._get_zipfile().namelist()) - else: - raise IOError('Path must point to a directory or zip') - - PIL.Image.init() - self._image_fnames = sorted( - fname for fname in self._all_fnames if self._file_ext(fname) in PIL.Image.EXTENSION) - if len(self._image_fnames) == 0: - raise IOError('No image files found in the specified path') - - name = os.path.splitext(os.path.basename(self._path))[0] - raw_shape = [len(self._image_fnames)] + \ - list(self._load_raw_image(0).shape) - # if resolution is not None and (raw_shape[2] != resolution or raw_shape[3] != resolution): - # raise IOError('Image files do not match the specified resolution') - if resolution is not None: - if self._square: - raw_shape[2] = raw_shape[3] = resolution - else: - raw_shape[2] = resolution - raw_shape[3] = resolution // 2 - # print(raw_shape) - super().__init__(name=name, raw_shape=raw_shape, square=square, **super_kwargs) - - @staticmethod - def _file_ext(fname): - return os.path.splitext(fname)[1].lower() - - def _get_zipfile(self): - assert self._type == 'zip' - if self._zipfile is None: - self._zipfile = zipfile.ZipFile(self._path) - return self._zipfile - - def _open_file(self, fname): - if self._type == 'dir': - return open(os.path.join(self._path, fname), 'rb') - if self._type == 'zip': - return self._get_zipfile().open(fname, 'r') - return None - - def close(self): - try: - if self._zipfile is not None: - self._zipfile.close() - finally: - self._zipfile = None - - def __getstate__(self): - return dict(super().__getstate__(), _zipfile=None) - - def _load_raw_image(self, raw_idx): # load single image - fname = self._image_fnames[raw_idx] - with self._open_file(fname) as f: - if pyspng is not None and self._file_ext(fname) == '.png': - image = pyspng.load(f.read()) - else: - image = np.array(PIL.Image.open(f)) - if image.ndim == 2: - image = image[:, :, np.newaxis] # HW => HWC - image = image.transpose(2, 0, 1) # HWC => CHW - return image - - def _load_raw_labels(self): - fname = 'dataset.json' - if fname not in self._all_fnames: - return None - with self._open_file(fname) as f: - labels = json.load(f)['labels'] - if labels is None: - return None - labels = dict(labels) - labels = [labels[fname.replace('\\', '/')] - for fname in self._image_fnames] - labels = np.array(labels) - labels = labels.astype({1: np.int64, 2: np.float32}[labels.ndim]) - return labels - - -# ---------------------------------------------------------------------------- diff --git a/spaces/hamzapehlivan/StyleRes/editings/styleclip.py b/spaces/hamzapehlivan/StyleRes/editings/styleclip.py deleted file mode 100644 index 0353b6a5b41dcaa0660c2da6391d0d56ad16ebaf..0000000000000000000000000000000000000000 --- a/spaces/hamzapehlivan/StyleRes/editings/styleclip.py +++ /dev/null @@ -1,49 +0,0 @@ - -from editings.styleclip_directions.styleclip_mapper_network import LevelsMapper -import torch -import csv -from options import Settings -import os - -class Options(): - def __init__(self, no_coarse_mapper, no_medium_mapper, no_fine_mapper) -> None: - self.no_coarse_mapper = no_coarse_mapper - self.no_medium_mapper = no_medium_mapper - self.no_fine_mapper = no_fine_mapper - -class StyleClip(): - def __init__(self) -> None: - self.styleclip_mapping_configs = {} - - with open(os.path.join(Settings.styleclip_settings, 'styleclip_mapping_configs.csv'), "r") as f: - reader = csv.reader(f) - for row in reader: - key = row.pop(0) - self.styleclip_mapping_configs[key] = list(map(lambda x: True if x == "True" else False, row)) - - def edit(self, latent, cfg): - with torch.no_grad(): - if cfg.type == 'mapper': - mapper = self.build_mapper(cfg.edit) - return latent + cfg.strength * mapper(latent) - if cfg.type == 'global': - - return latent + 10 * torch.load(os.path.join(Settings.styleclip_global_directions, 'makeup.pt')) - - # def load_global_direction(self, editname): - # pass - - def build_mapper(self, editname): - try: # Check if loaded - mapper = getattr(self, f"{editname}_mapper") - except: - opts = Options(*self.styleclip_mapping_configs[editname]) - mapper = LevelsMapper(opts) - ckpt = torch.load(os.path.join(Settings.styleclip_mapper_directions, f'{editname}.pt')) - mapper.load_state_dict(ckpt, strict=True) - mapper.to(device=Settings.device) - for param in mapper.parameters(): - param.requires_grad = False - mapper.eval() - setattr(self, f"{editname}_mapper", mapper) - return mapper \ No newline at end of file diff --git a/spaces/hao007/Image-Caption/README.md b/spaces/hao007/Image-Caption/README.md deleted file mode 100644 index 90513b8fa94d9b34c1ad6c762e74c7bb0223b863..0000000000000000000000000000000000000000 --- a/spaces/hao007/Image-Caption/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Image Caption -emoji: 📈 -colorFrom: green -colorTo: purple -sdk: streamlit -sdk_version: 1.21.0 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/hca97/Mosquito-Detection/my_models/torch_hub_cache/yolov5/utils/loggers/clearml/clearml_utils.py b/spaces/hca97/Mosquito-Detection/my_models/torch_hub_cache/yolov5/utils/loggers/clearml/clearml_utils.py deleted file mode 100644 index 4e999bfee5dbf03fbb0a826ee458315912af4d7e..0000000000000000000000000000000000000000 --- a/spaces/hca97/Mosquito-Detection/my_models/torch_hub_cache/yolov5/utils/loggers/clearml/clearml_utils.py +++ /dev/null @@ -1,163 +0,0 @@ -"""Main Logger class for ClearML experiment tracking.""" -import glob -import re -from pathlib import Path - -import numpy as np -import yaml -from ultralytics.utils.plotting import Annotator, colors - -try: - import clearml - from clearml import Dataset, Task - - assert hasattr(clearml, '__version__') # verify package import not local dir -except (ImportError, AssertionError): - clearml = None - - -def construct_dataset(clearml_info_string): - """Load in a clearml dataset and fill the internal data_dict with its contents. - """ - dataset_id = clearml_info_string.replace('clearml://', '') - dataset = Dataset.get(dataset_id=dataset_id) - dataset_root_path = Path(dataset.get_local_copy()) - - # We'll search for the yaml file definition in the dataset - yaml_filenames = list(glob.glob(str(dataset_root_path / '*.yaml')) + glob.glob(str(dataset_root_path / '*.yml'))) - if len(yaml_filenames) > 1: - raise ValueError('More than one yaml file was found in the dataset root, cannot determine which one contains ' - 'the dataset definition this way.') - elif len(yaml_filenames) == 0: - raise ValueError('No yaml definition found in dataset root path, check that there is a correct yaml file ' - 'inside the dataset root path.') - with open(yaml_filenames[0]) as f: - dataset_definition = yaml.safe_load(f) - - assert set(dataset_definition.keys()).issuperset( - {'train', 'test', 'val', 'nc', 'names'} - ), "The right keys were not found in the yaml file, make sure it at least has the following keys: ('train', 'test', 'val', 'nc', 'names')" - - data_dict = dict() - data_dict['train'] = str( - (dataset_root_path / dataset_definition['train']).resolve()) if dataset_definition['train'] else None - data_dict['test'] = str( - (dataset_root_path / dataset_definition['test']).resolve()) if dataset_definition['test'] else None - data_dict['val'] = str( - (dataset_root_path / dataset_definition['val']).resolve()) if dataset_definition['val'] else None - data_dict['nc'] = dataset_definition['nc'] - data_dict['names'] = dataset_definition['names'] - - return data_dict - - -class ClearmlLogger: - """Log training runs, datasets, models, and predictions to ClearML. - - This logger sends information to ClearML at app.clear.ml or to your own hosted server. By default, - this information includes hyperparameters, system configuration and metrics, model metrics, code information and - basic data metrics and analyses. - - By providing additional command line arguments to train.py, datasets, - models and predictions can also be logged. - """ - - def __init__(self, opt, hyp): - """ - - Initialize ClearML Task, this object will capture the experiment - - Upload dataset version to ClearML Data if opt.upload_dataset is True - - arguments: - opt (namespace) -- Commandline arguments for this run - hyp (dict) -- Hyperparameters for this run - - """ - self.current_epoch = 0 - # Keep tracked of amount of logged images to enforce a limit - self.current_epoch_logged_images = set() - # Maximum number of images to log to clearML per epoch - self.max_imgs_to_log_per_epoch = 16 - # Get the interval of epochs when bounding box images should be logged - self.bbox_interval = opt.bbox_interval - self.clearml = clearml - self.task = None - self.data_dict = None - if self.clearml: - self.task = Task.init( - project_name=opt.project if opt.project != 'runs/train' else 'YOLOv5', - task_name=opt.name if opt.name != 'exp' else 'Training', - tags=['YOLOv5'], - output_uri=True, - reuse_last_task_id=opt.exist_ok, - auto_connect_frameworks={'pytorch': False} - # We disconnect pytorch auto-detection, because we added manual model save points in the code - ) - # ClearML's hooks will already grab all general parameters - # Only the hyperparameters coming from the yaml config file - # will have to be added manually! - self.task.connect(hyp, name='Hyperparameters') - self.task.connect(opt, name='Args') - - # Make sure the code is easily remotely runnable by setting the docker image to use by the remote agent - self.task.set_base_docker('ultralytics/yolov5:latest', - docker_arguments='--ipc=host -e="CLEARML_AGENT_SKIP_PYTHON_ENV_INSTALL=1"', - docker_setup_bash_script='pip install clearml') - - # Get ClearML Dataset Version if requested - if opt.data.startswith('clearml://'): - # data_dict should have the following keys: - # names, nc (number of classes), test, train, val (all three relative paths to ../datasets) - self.data_dict = construct_dataset(opt.data) - # Set data to data_dict because wandb will crash without this information and opt is the best way - # to give it to them - opt.data = self.data_dict - - def log_debug_samples(self, files, title='Debug Samples'): - """ - Log files (images) as debug samples in the ClearML task. - - arguments: - files (List(PosixPath)) a list of file paths in PosixPath format - title (str) A title that groups together images with the same values - """ - for f in files: - if f.exists(): - it = re.search(r'_batch(\d+)', f.name) - iteration = int(it.groups()[0]) if it else 0 - self.task.get_logger().report_image(title=title, - series=f.name.replace(it.group(), ''), - local_path=str(f), - iteration=iteration) - - def log_image_with_boxes(self, image_path, boxes, class_names, image, conf_threshold=0.25): - """ - Draw the bounding boxes on a single image and report the result as a ClearML debug sample. - - arguments: - image_path (PosixPath) the path the original image file - boxes (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class] - class_names (dict): dict containing mapping of class int to class name - image (Tensor): A torch tensor containing the actual image data - """ - if len(self.current_epoch_logged_images) < self.max_imgs_to_log_per_epoch and self.current_epoch >= 0: - # Log every bbox_interval times and deduplicate for any intermittend extra eval runs - if self.current_epoch % self.bbox_interval == 0 and image_path not in self.current_epoch_logged_images: - im = np.ascontiguousarray(np.moveaxis(image.mul(255).clamp(0, 255).byte().cpu().numpy(), 0, 2)) - annotator = Annotator(im=im, pil=True) - for i, (conf, class_nr, box) in enumerate(zip(boxes[:, 4], boxes[:, 5], boxes[:, :4])): - color = colors(i) - - class_name = class_names[int(class_nr)] - confidence_percentage = round(float(conf) * 100, 2) - label = f'{class_name}: {confidence_percentage}%' - - if conf > conf_threshold: - annotator.rectangle(box.cpu().numpy(), outline=color) - annotator.box_label(box.cpu().numpy(), label=label, color=color) - - annotated_image = annotator.result() - self.task.get_logger().report_image(title='Bounding Boxes', - series=image_path.name, - iteration=self.current_epoch, - image=annotated_image) - self.current_epoch_logged_images.add(image_path) diff --git a/spaces/hezhaoqia/vits-simple-api/gunicorn_config.py b/spaces/hezhaoqia/vits-simple-api/gunicorn_config.py deleted file mode 100644 index 08c634ecbdf320e2dcdd69c999d24ae40e8c3248..0000000000000000000000000000000000000000 --- a/spaces/hezhaoqia/vits-simple-api/gunicorn_config.py +++ /dev/null @@ -1,4 +0,0 @@ -import multiprocessing - -bind = "0.0.0.0:23456" -workers = multiprocessing.cpu_count() diff --git a/spaces/hhalim/DAvaViz-graph/app.py b/spaces/hhalim/DAvaViz-graph/app.py deleted file mode 100644 index 2269db8d939a14ea82be9ecbb76908861c9106cf..0000000000000000000000000000000000000000 --- a/spaces/hhalim/DAvaViz-graph/app.py +++ /dev/null @@ -1,509 +0,0 @@ -import streamlit as st -import graphviz as graphviz -import pandas as pd -import numpy as np - -st.title('Graphviz Gallery: https://graphviz.org/gallery/') - -# Using code: - -# Create a graphlib graph object -graph = graphviz.Digraph() -graph.edge('Grandpa', 'Ancestors') -graph.edge('Grandma', 'Ancestors') -graph.edge('Uncle', 'Grandma') -graph.edge('Aunt', 'Grandma') -graph.edge('Mom', 'Grandma') -graph.edge('Cousin Bob', 'Aunt') -graph.edge('Cousin Sue', 'Aunt') -graph.edge('Brother', 'Mom') -graph.edge('Sister', 'Mom') -st.graphviz_chart(graph) - - -st.graphviz_chart(''' -digraph G2 { - node [shape=plaintext]; - struct1 [label=< - - -
      caption
      >]; -} -''') - - - -st.title('Graphviz Dot Language: https://graphviz.org/doc/info/lang.html') - -# Using graph language: -st.graphviz_chart(''' -digraph G { - rankdir=LR - node [shape=plaintext] - a [ - label=< - - - -
      class
      qualifier
      > - ] - b [shape=ellipse style=filled - label=< - - - - - - - - - - - - -
      elephanttwo
      - - - - -
      corn
      c
      f
      -
      penguin
      4
      > - ] - c [ - label=line 2
      line 3
      > - ] - subgraph { rank=same b c } - a:here -> b:there [dir=both arrowtail=diamond] - c -> b - d [shape=triangle] - d -> c [label=< - - - - - - -
      Edge labels
      also
      > - ] -} -''') - -st.graphviz_chart(''' -digraph R { - rankdir=LR - node [style=rounded] - node1 [shape=box] - node2 [fillcolor=yellow, style="rounded,filled", shape=diamond] - node3 [shape=record, label="{ a | b | c }"] - node1 -> node2 -> node3 -} -''') - -st.title('Vega Lite Example: https://docs.streamlit.io/library/api-reference/charts/st.vega_lite_chart ') -df = pd.DataFrame( - np.random.randn(200, 3), - columns=['a', 'b', 'c']) - -st.vega_lite_chart(df, { - 'mark': {'type': 'circle', 'tooltip': True}, - 'encoding': { - 'x': {'field': 'a', 'type': 'quantitative'}, - 'y': {'field': 'b', 'type': 'quantitative'}, - 'size': {'field': 'c', 'type': 'quantitative'}, - 'color': {'field': 'c', 'type': 'quantitative'}, - }, - }) - -# More graph examples - -st.graphviz_chart(''' -digraph structs { - node [shape=record]; - struct1 [label=" left| mid\ dle| right"]; - struct2 [label=" one| two"]; - struct3 [label="hello\nworld |{ b |{c| d|e}| f}| g | h"]; - struct1:f1 -> struct2:f0; - struct1:f2 -> struct3:here; -} -''') - -st.graphviz_chart(''' -graph G { - fontname="Helvetica,Arial,sans-serif" - node [fontname="Helvetica,Arial,sans-serif"] - edge [fontname="Helvetica,Arial,sans-serif"] - layout=fdp - e - subgraph clusterA { - a -- b; - subgraph clusterC { - C -- D; - } - } - subgraph clusterB { - d -- f - } - d -- D - e -- clusterB - clusterC -- clusterB -} -''') - -st.graphviz_chart(''' -graph Transparency { - layout=neato - start=11 // empiric value to set orientation - bgcolor="#0000ff11" - node [shape=circle width=2.22 label="" style=filled] - 5 [color="#0000ff80"] - 6 [color="#ee00ee80"] - 1 [color="#ff000080"] - 2 [color="#eeee0080"] - 3 [color="#00ff0080"] - 4 [color="#00eeee80"] - 1 -- 2 -- 3 -- 4 -- 5 -- 6 -- 1 - } -''') - -st.graphviz_chart(''' -digraph UML_Class_diagram { - fontname="Helvetica,Arial,sans-serif" - node [fontname="Helvetica,Arial,sans-serif"] - edge [fontname="Helvetica,Arial,sans-serif"] - labelloc="t" - label="UML Class diagram demo" - graph [splines=false] - node [shape=record style=filled fillcolor=gray95] - edge [arrowhead=vee style=dashed] - Client -> Interface1 [xlabel=dependency] - Client -> Interface2 - edge [dir=back arrowtail=empty style=""] - Interface1 -> Class1 [xlabel=inheritance] - Interface2 -> Class1 [dir=none] - Interface2 [label="" xlabel="Simple\ninterface" shape=circle] - Interface1[label = <{«interface» I/O | + property
      ...
      |+ method
      ...
      }>] - Class1[label = <{I/O class | + property
      ...
      |+ method
      ...
      }>] - edge [dir=back arrowtail=empty style=dashed] - Class1 -> System_1 [xlabel=implementation] - System_1 [label = <{System | + property
      ...
      |+ method
      ...
      }>] - "Shared resource" [label = <{Shared resource | + property
      ...
      |+ method
      ...
      }>] - edge [dir=back arrowtail=diamond] - "System_1" -> Subsystem_1 [xlabel="composition"] - Subsystem_1[label = <{Subsystem 1 | + property
      ...
      |+ method
      ...
      }>] - Subsystem_2[label = <{Subsystem 2 | + property
      ...
      |+ method
      ...
      }>] - Subsystem_3[label = <{Subsystem 3 | + property
      ...
      |+ method
      ...
      }>] - "System_1" -> Subsystem_2 - "System_1" -> Subsystem_3 - edge [xdir=back arrowtail=odiamond] - Subsystem_1 -> "Shared resource" [xlabel=aggregation] - {Subsystem_2 Subsystem_3 } -> "Shared resource" -} -''') - - - -st.graphviz_chart(''' -digraph G { - fontname="Helvetica,Arial,sans-serif" - node [fontname="Helvetica,Arial,sans-serif"] - edge [fontname="Helvetica,Arial,sans-serif"] - subgraph cluster_1 { - node [ style=filled,shape="box",fillcolor="antiquewhite:aquamarine" ]n5; - node [ shape="ellipse",fillcolor="bisque4:blue2" ]n4; - node [ shape="circle",fillcolor="cadetblue1:chocolate1" ]n3; - node [ shape="diamond",fillcolor="crimson:cyan4" ]n2; - node [ shape="triangle",fillcolor="deepskyblue2:firebrick" ]n1; - node [ shape="pentagon",fillcolor="gray24:gray88" ]n0; - label = "X11 Colors"; - } - subgraph cluster_2 { - node [ style=filled,shape="box",fillcolor="bisque:brown" ]n11; - node [ shape="ellipse",fillcolor="green:darkorchid" ]n10; - node [ shape="circle",fillcolor="deepskyblue:gold" ]n9; - node [ shape="diamond",fillcolor="lightseagreen:orangered" ]n8; - node [ shape="triangle",fillcolor="turquoise:salmon" ]n7; - node [ shape="pentagon",fillcolor="snow:black" ]n6; - label = "SVG Colors"; - } - subgraph cluster_3 { - node [ style=filled,shape="box",fillcolor="/accent3/1:/accent3/3" ]n17; - node [ shape="ellipse",fillcolor="/accent4/1:/accent4/4" ]n16; - node [ shape="circle",fillcolor="/accent5/1:/accent5/5" ]n15; - node [ shape="diamond",fillcolor="/accent6/1:/accent6/6" ]n14; - node [ shape="triangle",fillcolor="/accent7/1:/accent7/7" ]n13; - node [ shape="pentagon",fillcolor="/accent8/1:/accent8/8" ]n12; - label = "Brewer - accent"; - } - subgraph cluster_4 { - node [ style=filled,shape="box",fillcolor="/blues3/1:/blues3/2" ]n23; - node [ shape="ellipse",fillcolor="/blues4/1:/blues4/3" ]n22; - node [ shape="circle",fillcolor="/blues5/1:/blues5/4" ]n21; - node [ shape="diamond",fillcolor="/blues6/1:/blues6/5" ]n20; - node [ shape="triangle",fillcolor="/blues7/1:/blues7/6" ]n19; - node [ shape="pentagon",fillcolor="/blues8/1:/blues8/7" ]n18; - label = "Brewer - blues"; - } -n3 -> n9 -> n15 -> n21; -} -''') - -st.graphviz_chart(''' -digraph G {bgcolor="#0000FF44:#FF000044" gradientangle=90 - fontname="Helvetica,Arial,sans-serif" - node [fontname="Helvetica,Arial,sans-serif"] - edge [fontname="Helvetica,Arial,sans-serif"] - subgraph cluster_0 { - style=filled; - color=lightgrey; - fillcolor="darkgray:gold"; - gradientangle=0 - node [fillcolor="yellow:green" style=filled gradientangle=270] a0; - node [fillcolor="lightgreen:red"] a1; - node [fillcolor="lightskyblue:darkcyan"] a2; - node [fillcolor="cyan:lightslateblue"] a3; - a0 -> a1 -> a2 -> a3; - label = "process #1"; - } - subgraph cluster_1 { - node [fillcolor="yellow:magenta" - style=filled gradientangle=270] b0; - node [fillcolor="violet:darkcyan"] b1; - node [fillcolor="peachpuff:red"] b2; - node [fillcolor="mediumpurple:purple"] b3; - b0 -> b1 -> b2 -> b3; - label = "process #2"; - color=blue - fillcolor="darkgray:gold"; - gradientangle=0 - style=filled; - } - start -> a0; - start -> b0; - a1 -> b3; - b2 -> a3; - a3 -> a0; - a3 -> end; - b3 -> end; - start [shape=Mdiamond , - fillcolor="pink:red", - gradientangle=90, - style=radial]; - end [shape=Msquare, - fillcolor="lightyellow:orange", - style=radial, - gradientangle=90]; -} -''') - -st.graphviz_chart(''' -graph Color_wheel { - graph [ - layout = neato - label = "Color wheel, 33 colors.\nNeato layout" - labelloc = b - fontname = "Helvetica,Arial,sans-serif" - start = regular - normalize = 0 - ] - node [ - shape = circle - style = filled - color = "#00000088" - fontname = "Helvetica,Arial,sans-serif" - ] - edge [ - len = 2.7 - color = "#00000088" - fontname = "Helvetica,Arial,sans-serif" - ] - subgraph Dark { - node [fontcolor = white width = 1.4] - center [width = 1 style = invis shape = point] - center -- darkred [label = "0°/360°"] - darkred [fillcolor = darkred] - brown [fillcolor = brown] - brown -- center [label = "30°"] - olive [fillcolor = olive] - olive -- center [label = "60°"] - darkolivegreen [fillcolor = darkolivegreen fontsize = 10] - darkolivegreen -- center [label = "90°"] - darkgreen [fillcolor = darkgreen] - darkgreen -- center [label = "120°"] - "dark hue 0.416" [color = ".416 1 .6" fontcolor = white] - "dark hue 0.416" -- center [label = "150°"] - darkcyan [fillcolor = darkcyan] - darkcyan -- center [label = "180°"] - "dark hue 0.583" [color = ".583 1 .6" fontcolor = white] - "dark hue 0.583" -- center [label = "210°"] - darkblue [fillcolor = darkblue] - darkblue -- center [label = "240°"] - "dark hue 0.750" [color = ".750 1 .6"] - "dark hue 0.750" -- center [label = "270°"] - darkmagenta [fillcolor = darkmagenta] - darkmagenta -- center [label = "300°"] - "dark hue 0.916" [color = ".916 1 .6"] - "dark hue 0.916" -- center [label = "330°"] - } - subgraph Tue { - node [width = 1.3] - "hue 0.083" -- brown - "hue 0.083" [color = ".083 1 1"] - "hue 0.125" [color = ".125 1 1"] - "hue 0.166" -- olive - "hue 0.166" [color = ".166 1 1"] - "hue 0.208" [color = ".208 1 1"] - "hue 0.250" -- darkolivegreen - "hue 0.250" [color = ".250 1 1"] - "hue 0.291" [color = ".291 1 1"] - "hue 0.333" -- darkgreen - "hue 0.333" [color = ".333 1 1"] - "hue 0.375" [color = ".375 1 1"] - "hue 0.416" -- "dark hue 0.416" - "hue 0.416" [color = ".416 1 1"] - "hue 0.458" [color = ".458 1 1"] - "hue 0.500" -- darkcyan - "hue 0.500" [color = ".500 1 1"] - "hue 0.541" [color = ".541 1 1"] - node [fontcolor = white] - "hue 0.000" [color = ".000 1 1"] - "hue 0.000" -- darkred - "hue 0.041" [color = ".041 1 1"] - "hue 0.583" -- "dark hue 0.583" - "hue 0.583" [color = ".583 1 1"] - "hue 0.625" [color = ".625 1 1"] - "hue 0.666" -- darkblue - "hue 0.666" [color = ".666 1 1"] - "hue 0.708" [color = ".708 1 1"] - "hue 0.750" -- "dark hue 0.750" - "hue 0.750" [color = ".750 1 1"] - "hue 0.791" [color = ".791 1 1"] - "hue 0.833" -- darkmagenta - "hue 0.833" [color = ".833 1 1"] - "hue 0.875" [color = ".875 1 1"] - "hue 0.916" -- "dark hue 0.916" - "hue 0.916" [color = ".916 1 1"] - "hue 0.958" [color = ".958 1 1"] - edge [len = 1] - "hue 0.000" -- "hue 0.041" -- "hue 0.083" -- "hue 0.125" -- "hue 0.166" -- "hue 0.208" - "hue 0.208" -- "hue 0.250" -- "hue 0.291" -- "hue 0.333" -- "hue 0.375" -- "hue 0.416" - "hue 0.416" -- "hue 0.458" -- "hue 0.500" --"hue 0.541" -- "hue 0.583" -- "hue 0.625" - "hue 0.625" -- "hue 0.666" -- "hue 0.708" -- "hue 0.750" -- "hue 0.791" -- "hue 0.833" - "hue 0.833" -- "hue 0.875" -- "hue 0.916" -- "hue 0.958" -- "hue 0.000" - } - subgraph Main_colors { - node [width = 2 fontsize = 20] - red [fillcolor = red fontcolor = white] - orangered [fillcolor = orangered] - orange [fillcolor = orange] - gold [fillcolor = gold] - yellow [fillcolor = yellow] - yellowgreen [fillcolor = yellowgreen] - deeppink [fillcolor = deeppink fontcolor = white] - fuchsia [label = "fuchsia\nmagenta" fillcolor = fuchsia fontcolor = white] - purple [fillcolor = purple fontcolor = white] - blue [fillcolor = blue fontcolor = white] - cornflowerblue [fillcolor = cornflowerblue] - deepskyblue [fillcolor = deepskyblue] - aqua [fillcolor = aqua label = "aqua\ncyan"] - springgreen [fillcolor = springgreen] - green [fillcolor = green] - purple -- fuchsia -- deeppink -- red - cornflowerblue -- blue -- purple - cornflowerblue -- deepskyblue -- aqua [len = 1.7] - aqua -- springgreen -- green -- yellowgreen -- yellow - yellow -- gold -- orange -- orangered -- red [len = 1.6] - orange -- "hue 0.083" - deeppink -- "hue 0.916" - deeppink -- "hue 0.875" - red -- "hue 0.000" - yellowgreen -- "hue 0.250" - blue -- "hue 0.666" - yellow -- "hue 0.166" - gold -- "hue 0.125" - green -- "hue 0.333" - springgreen -- "hue 0.416" - aqua -- "hue 0.500" - cornflowerblue -- "hue 0.583" - deepskyblue -- "hue 0.541" - purple -- "hue 0.791" - purple -- "hue 0.750" - fuchsia -- "hue 0.833" - } - subgraph Light_colors { - node [width = 2 fontsize = 20] - node [shape = circle width = 1.8] - edge [len = 2.1] - pink [fillcolor = pink] - pink -- red - lightyellow [fillcolor = lightyellow] - lightyellow -- yellow - mediumpurple [fillcolor = mediumpurple] - mediumpurple -- purple - violet [fillcolor = violet] - violet -- fuchsia - hotpink [fillcolor = hotpink] - hotpink -- deeppink - "light hue 0.250" [color = ".250 .2 1"] - "light hue 0.250" -- yellowgreen - lightcyan [fillcolor = lightcyan] - lightcyan -- aqua - lightslateblue [fillcolor = lightslateblue] - lightslateblue -- blue - lightgreen [fillcolor = lightgreen] - lightgreen -- green - lightskyblue [fillcolor = lightskyblue] - lightskyblue -- deepskyblue - peachpuff [fillcolor = peachpuff] - peachpuff -- orange - "light hue 0.416" [color = ".416 .2 1"] - "light hue 0.416" -- springgreen - } - subgraph Tints { - node [width = 1] - edge [len = 2.4] - "hue 0 tint" -- pink - "hue 0 tint" [color = "0 .1 1"] - "hue 0.041 tint" [color = ".041 .1 1"] - "hue 0.083 tint" -- peachpuff - "hue 0.083 tint" [color = ".083 .1 1"] - "hue 0.125 tint" [color = ".125 .1 1"] - "hue 0.166 tint" -- lightyellow - "hue 0.166 tint" [color = ".166 .1 1"] - "hue 0.208 tint" [color = ".208 .1 1"] - "hue 0.250 tint" -- "light hue 0.250" - "hue 0.250 tint" [color = ".250 .1 1"] - "hue 0.291 tint" [color = ".291 .1 1"] - "hue 0.333 tint" -- lightgreen - "hue 0.333 tint" [color = ".333 .1 1"] - "hue 0.375 tint" [color = ".375 .1 1"] - "hue 0.416 tint" -- "light hue 0.416" - "hue 0.416 tint" [color = ".416 .1 1"] - "hue 0.458 tint" [color = ".458 .1 1"] - "hue 0.5 tint" -- lightcyan - "hue 0.5 tint" [color = ".5 .1 1"] - "hue 0.541 tint" -- lightskyblue - "hue 0.541 tint" [color = ".541 .1 1"] - "hue 0.583 tint" [color = ".583 .1 1"] - "hue 0.625 tint" [color = ".625 .1 1"] - "hue 0.666 tint" -- lightslateblue - "hue 0.666 tint" [color = ".666 .1 1"] - "hue 0.708 tint" [color = ".708 .1 1"] - "hue 0.750 tint" -- mediumpurple - "hue 0.750 tint" [color = ".750 .1 1"] - "hue 0.791 tint" [color = ".791 .1 1"] - "hue 0.833 tint" -- violet - "hue 0.833 tint" [color = ".833 .1 1"] - "hue 0.875 tint" [color = ".875 .1 1"] - "hue 0.916 tint" -- hotpink - "hue 0.916 tint" [color = ".916 .1 1"] - "hue 0.958 tint" [color = ".958 .1 1"] - edge [len = 2] - "hue 0 tint" -- "hue 0.041 tint" -- "hue 0.083 tint" -- "hue 0.125 tint" -- "hue 0.166 tint" -- "hue 0.208 tint" - "hue 0.208 tint" -- "hue 0.250 tint" -- "hue 0.291 tint" -- "hue 0.333 tint" -- "hue 0.375 tint" -- "hue 0.416 tint" - "hue 0.416 tint" -- "hue 0.458 tint" -- "hue 0.5 tint" --"hue 0.541 tint" -- "hue 0.583 tint" -- "hue 0.625 tint" - "hue 0.625 tint" -- "hue 0.666 tint" -- "hue 0.708 tint" -- "hue 0.750 tint" -- "hue 0.791 tint" -- "hue 0.833 tint" - "hue 0.833 tint" -- "hue 0.875 tint" -- "hue 0.916 tint" -- "hue 0.958 tint" -- "hue 0 tint" - } - } -''') \ No newline at end of file diff --git a/spaces/ho11laqe/nnUNet_calvingfront_detection/create_plots_new/canny_edge.py b/spaces/ho11laqe/nnUNet_calvingfront_detection/create_plots_new/canny_edge.py deleted file mode 100644 index 12d7db95b50f42414078cb1f83b8c1fd1d90b357..0000000000000000000000000000000000000000 --- a/spaces/ho11laqe/nnUNet_calvingfront_detection/create_plots_new/canny_edge.py +++ /dev/null @@ -1,157 +0,0 @@ -from scipy import ndimage -from scipy.ndimage.filters import convolve - -from scipy import misc -import numpy as np -import cv2 - - -class cannyEdgeDetector: - def __init__(self, imgs, sigma=5, kernel_size=10, weak_pixel=75, strong_pixel=255, lowthreshold=0.05, - highthreshold=0.15): - self.imgs = imgs - self.imgs_final = [] - self.img_smoothed = None - self.gradientMat = None - self.thetaMat = None - self.nonMaxImg = None - self.thresholdImg = None - self.weak_pixel = weak_pixel - self.strong_pixel = strong_pixel - self.sigma = sigma - self.kernel_size = kernel_size - self.lowThreshold = lowthreshold - self.highThreshold = highthreshold - return - - def gaussian_kernel(self, size, sigma=1): - size = int(size) // 2 - x, y = np.mgrid[-size:size + 1, -size:size + 1] - normal = 1 / (2.0 * np.pi * sigma ** 2) - g = np.exp(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2))) * normal - return g - - def sobel_filters(self, img): - Kx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float32) - Ky = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], np.float32) - - Ix = ndimage.filters.convolve(img, Kx) - Iy = ndimage.filters.convolve(img, Ky) - - G = np.hypot(Ix, Iy) - G = G / G.max() * 255 - theta = np.arctan2(Iy, Ix) - return (G, theta, Ix, Iy) - - def non_max_suppression(self, img, D): - M, N = img.shape - Z = np.zeros((M, N), dtype=np.int32) - angle = D * 180. / np.pi - angle[angle < 0] += 180 - - for i in range(1, M - 1): - for j in range(1, N - 1): - try: - q = 255 - r = 255 - - # angle 0 - if (0 <= angle[i, j] < 22.5) or (157.5 <= angle[i, j] <= 180): - q = img[i, j + 1] - r = img[i, j - 1] - # angle 45 - elif (22.5 <= angle[i, j] < 67.5): - q = img[i + 1, j - 1] - r = img[i - 1, j + 1] - # angle 90 - elif (67.5 <= angle[i, j] < 112.5): - q = img[i + 1, j] - r = img[i - 1, j] - # angle 135 - elif (112.5 <= angle[i, j] < 157.5): - q = img[i - 1, j - 1] - r = img[i + 1, j + 1] - - if (img[i, j] >= q) and (img[i, j] >= r): - Z[i, j] = img[i, j] - else: - Z[i, j] = 0 - - - except IndexError as e: - pass - - return Z - - def threshold(self, img): - - highThreshold = img.max() * self.highThreshold; - lowThreshold = highThreshold * self.lowThreshold; - - M, N = img.shape - res = np.zeros((M, N), dtype=np.int32) - - weak = np.int32(self.weak_pixel) - strong = np.int32(self.strong_pixel) - - strong_i, strong_j = np.where(img >= highThreshold) - zeros_i, zeros_j = np.where(img < lowThreshold) - - weak_i, weak_j = np.where((img <= highThreshold) & (img >= lowThreshold)) - - res[strong_i, strong_j] = strong - res[weak_i, weak_j] = weak - - return (res) - - def hysteresis(self, img): - - M, N = img.shape - weak = self.weak_pixel - strong = self.strong_pixel - - for i in range(1, M - 1): - for j in range(1, N - 1): - if (img[i, j] == weak): - try: - if ((img[i + 1, j - 1] == strong) or (img[i + 1, j] == strong) or (img[i + 1, j + 1] == strong) - or (img[i, j - 1] == strong) or (img[i, j + 1] == strong) - or (img[i - 1, j - 1] == strong) or (img[i - 1, j] == strong) or ( - img[i - 1, j + 1] == strong)): - img[i, j] = strong - else: - img[i, j] = 0 - except IndexError as e: - pass - - return img - - def detect(self): - imgs_final = [] - for i, img in enumerate(self.imgs): - cv2.imwrite('output/0img.png', img) - self.img_smoothed = convolve(img, self.gaussian_kernel(self.kernel_size, self.sigma)) - self.img_smoothed = self.img_smoothed/np.max(self.img_smoothed)*255 - cv2.imwrite('output/1smoothed.png', self.img_smoothed) - self.gradientMat, self.thetaMat, Ix, Iy = self.sobel_filters(self.img_smoothed) - cv2.imwrite('output/2Ix.png', Ix) - cv2.imwrite('output/2Iy.png', Iy) - cv2.imwrite('output/4deltaI.png', self.gradientMat.astype(float)) - cv2.imwrite('output/5theta.png', self.thetaMat.astype(float) / np.max(self.thetaMat) * 255) - self.nonMaxImg = self.non_max_suppression(self.gradientMat, self.thetaMat) - cv2.imwrite('output/6nonmax.png', self.nonMaxImg) - self.thresholdImg = self.threshold(self.nonMaxImg) - cv2.imwrite('output/7threshold.png', self.thresholdImg) - img_final = self.hysteresis(self.thresholdImg) - self.imgs_final.append(img_final) - - return self.imgs_final - -if __name__ == '__main__': - image_path = '/home/ho11laqe/PycharmProjects/data_raw/sar_images/test/Mapple_2011-06-02_TSX_7_1_110.png' - - img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)[:1000,-1000:].astype(np.float32) - detector = cannyEdgeDetector([img], sigma=20) - edge = detector.detect() - cv2.imwrite('output/8edge.png', edge[0]) - diff --git a/spaces/ho11laqe/nnUNet_calvingfront_detection/nnunet/training/network_training/nnUNet_variants/data_augmentation/nnUNetTrainerV2_noMirroring.py b/spaces/ho11laqe/nnUNet_calvingfront_detection/nnunet/training/network_training/nnUNet_variants/data_augmentation/nnUNetTrainerV2_noMirroring.py deleted file mode 100644 index b0baa522d8732edf196e39c86528db9ba96c65f6..0000000000000000000000000000000000000000 --- a/spaces/ho11laqe/nnUNet_calvingfront_detection/nnunet/training/network_training/nnUNet_variants/data_augmentation/nnUNetTrainerV2_noMirroring.py +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from nnunet.training.network_training.nnUNetTrainerV2 import nnUNetTrainerV2 - - -class nnUNetTrainerV2_noMirroring(nnUNetTrainerV2): - def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, - step_size: float = 0.5, save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True, - validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False, - segmentation_export_kwargs: dict = None, run_postprocessing_on_folds: bool = True): - """ - We need to wrap this because we need to enforce self.network.do_ds = False for prediction - """ - ds = self.network.do_ds - if do_mirroring: - print("WARNING! do_mirroring was True but we cannot do that because we trained without mirroring. " - "do_mirroring was set to False") - do_mirroring = False - self.network.do_ds = False - ret = super().validate(do_mirroring=do_mirroring, use_sliding_window=use_sliding_window, step_size=step_size, - save_softmax=save_softmax, use_gaussian=use_gaussian, - overwrite=overwrite, validation_folder_name=validation_folder_name, debug=debug, - all_in_gpu=all_in_gpu, segmentation_export_kwargs=segmentation_export_kwargs, - run_postprocessing_on_folds=run_postprocessing_on_folds) - self.network.do_ds = ds - return ret - - def setup_DA_params(self): - super().setup_DA_params() - self.data_aug_params["do_mirror"] = False diff --git a/spaces/housexu123/bingo-2.0/src/components/button-scroll-to-bottom.tsx b/spaces/housexu123/bingo-2.0/src/components/button-scroll-to-bottom.tsx deleted file mode 100644 index b68ab9c0e48320c356e51a52d11b9ca63909e6c5..0000000000000000000000000000000000000000 --- a/spaces/housexu123/bingo-2.0/src/components/button-scroll-to-bottom.tsx +++ /dev/null @@ -1,34 +0,0 @@ -'use client' - -import * as React from 'react' - -import { cn } from '@/lib/utils' -import { useAtBottom } from '@/lib/hooks/use-at-bottom' -import { Button, type ButtonProps } from '@/components/ui/button' -import { IconArrowDown } from '@/components/ui/icons' - -export function ButtonScrollToBottom({ className, ...props }: ButtonProps) { - const isAtBottom = useAtBottom() - - return ( - - ) -} diff --git a/spaces/hugginglearners/image-style-transfer/README.md b/spaces/hugginglearners/image-style-transfer/README.md deleted file mode 100644 index 1f35aa40e5c5ffcbbbee3d35dc157e038649a84b..0000000000000000000000000000000000000000 --- a/spaces/hugginglearners/image-style-transfer/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Image Style Transfer -emoji: 📊 -colorFrom: yellow -colorTo: gray -sdk: gradio -sdk_version: 3.0.24 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/imseldrith/FaceSwap/roop/processors/frame/face_swapper.py b/spaces/imseldrith/FaceSwap/roop/processors/frame/face_swapper.py deleted file mode 100644 index b8072076f11bd3dc836b66afb5ebc7619bdce424..0000000000000000000000000000000000000000 --- a/spaces/imseldrith/FaceSwap/roop/processors/frame/face_swapper.py +++ /dev/null @@ -1,100 +0,0 @@ -from typing import Any, List, Callable -import cv2 -import insightface -import threading - -import roop.globals -import roop.processors.frame.core -from roop.core import update_status -from roop.face_analyser import get_one_face, get_many_faces, find_similar_face -from roop.face_reference import get_face_reference, set_face_reference, clear_face_reference -from roop.typing import Face, Frame -from roop.utilities import conditional_download, resolve_relative_path, is_image, is_video - -FACE_SWAPPER = None -THREAD_LOCK = threading.Lock() -NAME = 'ROOP.FACE-SWAPPER' - - -def get_face_swapper() -> Any: - global FACE_SWAPPER - - with THREAD_LOCK: - if FACE_SWAPPER is None: - model_path = resolve_relative_path('../models/inswapper_128.onnx') - FACE_SWAPPER = insightface.model_zoo.get_model(model_path, providers=roop.globals.execution_providers) - return FACE_SWAPPER - - -def clear_face_swapper() -> None: - global FACE_SWAPPER - - FACE_SWAPPER = None - - -def pre_check() -> bool: - download_directory_path = resolve_relative_path('../models') - conditional_download(download_directory_path, ['https://huggingface.co/henryruhs/roop/resolve/main/inswapper_128.onnx']) - return True - - -def pre_start() -> bool: - if not is_image(roop.globals.source_path): - update_status('Select an image for source path.', NAME) - return False - elif not get_one_face(cv2.imread(roop.globals.source_path)): - update_status('No face in source path detected.', NAME) - return False - if not is_image(roop.globals.target_path) and not is_video(roop.globals.target_path): - update_status('Select an image or video for target path.', NAME) - return False - return True - - -def post_process() -> None: - clear_face_swapper() - clear_face_reference() - - -def swap_face(source_face: Face, target_face: Face, temp_frame: Frame) -> Frame: - return get_face_swapper().get(temp_frame, target_face, source_face, paste_back=True) - - -def process_frame(source_face: Face, reference_face: Face, temp_frame: Frame) -> Frame: - if roop.globals.many_faces: - many_faces = get_many_faces(temp_frame) - if many_faces: - for target_face in many_faces: - temp_frame = swap_face(source_face, target_face, temp_frame) - else: - target_face = find_similar_face(temp_frame, reference_face) - if target_face: - temp_frame = swap_face(source_face, target_face, temp_frame) - return temp_frame - - -def process_frames(source_path: str, temp_frame_paths: List[str], update: Callable[[], None]) -> None: - source_face = get_one_face(cv2.imread(source_path)) - reference_face = None if roop.globals.many_faces else get_face_reference() - for temp_frame_path in temp_frame_paths: - temp_frame = cv2.imread(temp_frame_path) - result = process_frame(source_face, reference_face, temp_frame) - cv2.imwrite(temp_frame_path, result) - if update: - update() - - -def process_image(source_path: str, target_path: str, output_path: str) -> None: - source_face = get_one_face(cv2.imread(source_path)) - target_frame = cv2.imread(target_path) - reference_face = None if roop.globals.many_faces else get_one_face(target_frame, roop.globals.reference_face_position) - result = process_frame(source_face, reference_face, target_frame) - cv2.imwrite(output_path, result) - - -def process_video(source_path: str, temp_frame_paths: List[str]) -> None: - if not roop.globals.many_faces and not get_face_reference(): - reference_frame = cv2.imread(temp_frame_paths[roop.globals.reference_frame_number]) - reference_face = get_one_face(reference_frame, roop.globals.reference_face_position) - set_face_reference(reference_face) - roop.processors.frame.core.process_video(source_path, temp_frame_paths, process_frames) diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Lumion 25 Pro Crack Only.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Lumion 25 Pro Crack Only.md deleted file mode 100644 index ffbef357f9351284dc001f5b689b51f4e7b909c9..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Lumion 25 Pro Crack Only.md +++ /dev/null @@ -1,27 +0,0 @@ - -```html -

      Lumion 25 Pro Crack Only: How to Download and Install It for Free

      -

      Lumion 25 Pro is a powerful and easy-to-use 3D rendering software that allows you to create stunning visuals for architecture, interior design, landscape design, and more. With Lumion 25 Pro, you can turn your CAD models into realistic images and videos in minutes, without any prior experience or training.

      -

      However, Lumion 25 Pro is not a cheap software. It costs $3,499 for a single license, which is a lot of money for most users. That's why some people look for ways to get Lumion 25 Pro crack only, which is a hacked version of the software that bypasses the activation process and lets you use it for free.

      -

      Lumion 25 Pro Crack Only


      Download Ziphttps://urlin.us/2uEywp



      -

      But is Lumion 25 Pro crack only a good idea? Is it safe and legal to download and install it? What are the risks and consequences of using it? In this article, we will answer these questions and give you some alternatives to Lumion 25 Pro crack only.

      -

      Is Lumion 25 Pro Crack Only Safe?

      -

      The short answer is no. Lumion 25 Pro crack only is not safe to download and install on your computer. There are several reasons why:

      -
        -
      • Lumion 25 Pro crack only is not an official version of the software. It is modified by unknown hackers who may have malicious intentions. They may insert viruses, malware, spyware, or ransomware into the crack file, which can harm your computer and compromise your personal data.
      • -
      • Lumion 25 Pro crack only may not work properly or at all. Since it is not updated or supported by the developers, it may have bugs, errors, glitches, or compatibility issues that can affect the quality and performance of your projects. You may also miss out on the latest features and improvements that come with the official updates.
      • -
      • Lumion 25 Pro crack only may cause legal problems. Using Lumion 25 Pro crack only is a violation of the software's license agreement and intellectual property rights. You may face legal actions from the developers or their partners if they detect that you are using a cracked version of their software. You may also face fines or penalties from your local authorities if they find out that you are using pirated software.
      • -
      -

      What Are the Alternatives to Lumion 25 Pro Crack Only?

      -

      If you want to use Lumion 25 Pro but you don't want to pay for it or risk using a cracked version, there are some alternatives that you can consider:

      -
        -
      • Lumion Trial Version: You can download and install the trial version of Lumion 25 Pro from the official website. The trial version gives you access to all the features and content of Lumion 25 Pro for 14 days, without any limitations or watermarks. You can use it to test the software and see if it meets your needs and expectations.
      • -
      • Lumion Student Version: If you are a student or an educator at an accredited academic institution, you can apply for a free Lumion student license from the official website. The student version gives you access to most of the features and content of Lumion 25 Pro for one year, with a watermark on the output. You can use it to learn and practice Lumion for your educational purposes.
      • -
      • Lumion Alternatives: If you are looking for other 3D rendering software that are similar to Lumion but cheaper or free, you can check out some of these options: SketchUp, Blender, Unreal Engine, Unity, Twinmotion, Enscape, etc. These software have different features, capabilities, and learning curves, so you may need to do some research and comparison before choosing one that suits your needs and preferences.
      • -
      -

      Conclusion

      -

      Lumion 25 Pro is a great software for creating stunning 3D visuals for various design projects. However, it is not a good idea to use Lumion 25 Pro crack only, as it can be unsafe, unreliable, and illegal. Instead, you should use the official version of Lumion 25 Pro or one of its alternatives that we have mentioned above. This way, you can enjoy the benefits of Lumion without compromising your computer, data, or reputation.

      -```

      -

      d5da3c52bf
      -
      -
      \ No newline at end of file diff --git a/spaces/inreVtussa/clothingai/Examples/3d Optical Mouse Rating 5v 100ma Driver __HOT__ Download.md b/spaces/inreVtussa/clothingai/Examples/3d Optical Mouse Rating 5v 100ma Driver __HOT__ Download.md deleted file mode 100644 index a3621fb1eb9ed07d3a583203b696ce582a9b1c79..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/3d Optical Mouse Rating 5v 100ma Driver __HOT__ Download.md +++ /dev/null @@ -1,9 +0,0 @@ -
      -

      g204 is designed to work seamlessly in any system, but if youre looking to fine-tune controls, free-to-download customization software is easy to use and set up. logitech g hub software is a complete customization suite that, lets you personalize lighting, sensitivity, and button commands on your g204 mouse. advanced features require logitech g hub software. download free at logitechg.com/downloads.

      -

      3d Optical Mouse Rating 5v 100ma Driver Download


      Download Zip > https://tiurll.com/2uCirn



      -

      stay productive longer with the comfortable, contoured shape that follows the natural curve of your hand. compact and wireless, the mouse fits easily with your laptop in a bagso you can take it anywhere you work. the mouse has a flexible, lightweight, and slim body and light-weight body with rubberized grips and comfortably contoured shape to fit all laptops. its ultra-low-profile design helps keep cables out of the way, so you can easily move the mouse without getting tangled in cables. the mouse is designed for a variety of users, so you can easily adjust the sensitivity to work best for your personal preferences.

      -

      m276 wireless is designed to work seamlessly in any system, but if youre looking to fine-tune controls, free-to-download customization software is easy to use and set up. logitech g hub software is a complete customization suite that, lets you personalize lighting, sensitivity, and button commands on your g301 mouse. advanced features require logitech g hub software. download free at logitechg.com/downloads.

      -

      g301 wireless mouse is designed to work seamlessly in any system, but if youre looking to fine-tune controls, free-to-download customization software is easy to use and set up. logitech g hub software is a complete customization suite that, lets you personalize lighting, sensitivity, and button commands on your g301 mouse. advanced features require logitech g hub software. download free at logitechg.com/downloads.

      -

      899543212b
      -
      -
      \ No newline at end of file diff --git a/spaces/inreVtussa/clothingai/Examples/Adeko 9 Crack 56 VERIFIED.md b/spaces/inreVtussa/clothingai/Examples/Adeko 9 Crack 56 VERIFIED.md deleted file mode 100644 index 22ea475132ea3ca175449fb4b57120f3d96ad0d7..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/Adeko 9 Crack 56 VERIFIED.md +++ /dev/null @@ -1,5 +0,0 @@ - -

      Trey Wae Flood-E APK Full Version, Download Torrent, Torrent Search Torrent Downloader (TSDT) 1.9.4 Crack.GatorTorrent Gator Download Source Code For Iphone 7 326 Download Crack Torrent Downloader (TSDT) 1.9.4 Crack.GatorTorrent Gator Download Source Code For Iphone 7 326 Download Torrent Downloader (TSDT) 1.9.4 Crack.GatorTorrent Gator Download Source Code For Iphone 7 326 Download Torrent Downloader (TSDT) 1.9.4 Crack.GatorTorrent Gator Download Source Code For Iphone 7 326 Download Torrent Download.en: Download Gator Torrent For.en : GatorTorrent For.en : Download Torrent GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.en : Download GatorTorrent For.

      -

      adeko 9 crack 56


      Downloadhttps://tiurll.com/2uCjJI



      899543212b
      -
      -
      \ No newline at end of file diff --git a/spaces/inreVtussa/clothingai/Examples/Adobe Acrobat XI Pro 11.0.20 FINAL Crack [TechTools] Crack.md b/spaces/inreVtussa/clothingai/Examples/Adobe Acrobat XI Pro 11.0.20 FINAL Crack [TechTools] Crack.md deleted file mode 100644 index 809bc6e7f6918571ed0446c14cd5cd3a9b94afc6..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/Adobe Acrobat XI Pro 11.0.20 FINAL Crack [TechTools] Crack.md +++ /dev/null @@ -1,27 +0,0 @@ - -

      How to Install Adobe Acrobat XI Pro 11.0.20 Final with Crack [TechTools]

      -

      Adobe Acrobat XI Pro is a powerful PDF converter and editor that lets you create, edit, and share PDF files with ease. It also comes with many features such as creating and analyzing forms, customizing PDF portfolios, and standardizing routine PDF tasks. In this article, we will show you how to install Adobe Acrobat XI Pro 11.0.20 Final with Crack [TechTools], a torrent file that contains the software and the crack to activate it.

      -

      Disclaimer

      -

      This article is for educational purposes only. We do not condone or encourage any illegal or harmful activities such as cracking software. Cracking software may violate the terms of service and license agreement of the software developer, and may expose your computer to malware and viruses. Downloading and installing cracked software is at your own risk.

      -

      Adobe Acrobat XI Pro 11.0.20 FINAL Crack [TechTools] crack


      Download Ziphttps://tiurll.com/2uCjTH



      -

      Steps to Install Adobe Acrobat XI Pro 11.0.20 Final with Crack [TechTools]

      -
        -
      1. Download the torrent file from this link[^1^] or this link[^2^]. You will need a torrent client such as uTorrent or BitTorrent to download the file.
      2. -
      3. Open the torrent file with your torrent client and start downloading the file. The file size is about 780 MB.
      4. -
      5. Once the download is complete, extract the file using WinRAR or 7-Zip. You will get a folder named "Adobe Acrobat XI Pro 11.0.20 + Crack [Tech-Tools.ME]".
      6. -
      7. Open the folder and run the file "Adobe Acrobat XI Pro 11.0.20 + Crack [Tech-Tools.ME].rar". This will extract another folder named "Adobe Acrobat XI Pro 11.0.20 + Crack [Tech-Tools.ME]".
      8. -
      9. Open the folder and run the file "Adobe Acrobat XI Pro 11.0.20.exe". This will start the installation process of Adobe Acrobat XI Pro.
      10. -
      11. Follow the instructions on the screen to install Adobe Acrobat XI Pro. Choose your language and accept the license agreement. You can choose the default installation location or change it if you want.
      12. -
      13. When the installation is finished, do not launch Adobe Acrobat XI Pro yet.
      14. -
      15. Go back to the folder "Adobe Acrobat XI Pro 11.0.20 + Crack [Tech-Tools.ME]" and open the folder "Crack".
      16. -
      17. Copy the file "amtlib.dll" and paste it in the installation folder of Adobe Acrobat XI Pro, which is usually located at "C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat". Replace the existing file if prompted.
      18. -
      19. Congratulations! You have successfully installed Adobe Acrobat XI Pro 11.0.20 Final with Crack [TechTools]. You can now launch Adobe Acrobat XI Pro and enjoy its features.
      20. -
      -

      Tips and Warnings

      -
        -
      • Before installing Adobe Acrobat XI Pro 11.0.20 Final with Crack [TechTools], make sure you have uninstalled any previous versions of Adobe Acrobat from your computer.
      • -
      • After installing Adobe Acrobat XI Pro 11.0.20 Final with Crack [TechTools], do not update it or connect it to the internet, as this may cause the crack to stop working.
      • -
      • If you encounter any problems or errors during or after the installation, you can check the files "_ReadMe.txt" and "www.Tech-Tools.ME - www.ThumperDC.COM.txt" in the folder "Adobe Acrobat XI Pro 11.0.20 + Crack [Tech-Tools.ME]" for more information and support.
      • -
      • We recommend that you scan your computer with an antivirus

        d5da3c52bf
        -
        -
        \ No newline at end of file diff --git a/spaces/inreVtussa/clothingai/Examples/Avast Secureline Vpn License 56.md b/spaces/inreVtussa/clothingai/Examples/Avast Secureline Vpn License 56.md deleted file mode 100644 index 107bc73521e2e5a5d8705aba633aefa765beb678..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/Avast Secureline Vpn License 56.md +++ /dev/null @@ -1,28 +0,0 @@ -

        Avast Secureline Vpn License 56


        Download ———>>> https://tiurll.com/2uClOd



        -
        -Learn how to use our Avast Secureline VPN. - -Espionage is a BIG deal in the Russia-Ukraine-Georgia triad. It's possible that Russia has been actively pursuing cyber espionage against Ukraine and Georgia. While this may not be the only motive for Russia's aggression toward these countries, it's certainly the primary one. - -The release of Ukraine, Georgia, and other ex-Soviet countries like Estonia and Latvia are definitely one of the many reasons why Russia has aggressively increased its cyber spying. What's even more significant is that Russia is starting to take advantage of the security holes they've created. - -Russia is a world-leading cyber spook. They are not only a world leader in cyber spying, they are the world leader in cyber attack. And they are accelerating this cyber espionage agenda and threat. - -I believe it's also worth pointing out that a substantial part of Russia's cyber espionage tactics against the world is espionage conducted via their media outlets. The Russian media is a tool to get their message out to the world. - -This is why the Russian media has come to play a very important role in promoting the agenda of espionage on the world. - -Meanwhile, with all of the chaos being caused by Russia, their media is trying to get a message out to the world. They are trying to show the world that Russia is not a world power and they aren't trying to get into the West. Russia is trying to be a part of the world, but not a part of the West. - -Russia is trying to convince the world that they are not a part of the West and they are part of the world. So Russia is trying to drive a wedge between the West and Russia. - -At the same time, Russia is trying to get a message out that it's not out to get the West. If they were out to get the West, they would have attacked the West over a long period of time. Instead, they have attacked Estonia. They have attacked Georgia. - -Russia is trying to convince the world that they are not trying to take out the West. But they are also trying to convince the world that they are a part of the world. - -Russia is trying to show the world that it is not out to get the West, but that it's just trying to get a message out. Russia is trying to show the world that they are friendly to the world. - -So that is a description of what Russia is trying to do. They are trying 4fefd39f24
        -
        -
        -

        diff --git a/spaces/inreVtussa/clothingai/Examples/Bejeweled Deluxe Torrent.md b/spaces/inreVtussa/clothingai/Examples/Bejeweled Deluxe Torrent.md deleted file mode 100644 index 9e4356498207e8ae97dbe5f55d0ae398c2165ae9..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/Bejeweled Deluxe Torrent.md +++ /dev/null @@ -1,11 +0,0 @@ -
        -

        To get the Bejeweled Deluxe program for your device, youll need to visit their site and follow the simple instruction. If you have a cracked file, you will be redirected to a cracked site. So be careful.

        -

        Bejeweled Deluxe Torrent


        Download Filehttps://tiurll.com/2uCj3y



        -

        First, select the gaming application that you want, and then click on the “install” option. The program will be shown on the left side of your screen. Then, select the Bejeweled Deluxe program. Finally, click “Download”.

        -

        Bejeweled Deluxe is a Windows game where users must match jewels horizontally or vertically. Complemented by high-definition designs, the game keeps you playing with its range of engaging sounds. You can download the fun puzzle game to enjoy over 8 gaming modes, all of which will give you a fighting chance to increase your score and win up to 65 badges.

        -

        If you are a fan of Bejeweled, you must try Bejeweled 2 and Bejeweled 3. They have a comprehensive range of challenges, give you to try out other modes, and give you to keep you entertained for hours on end.

        -

        -

        Bejeweled 2 Deluxe - Das erste Spiel ist für uns mächtig cool. Es ermöglicht es, von Fernsehen, Zeitungen und Zeitzeugen in Fernsehprogrammen zu gebrauchen. Das frische, irre Formen und wiederholbare Erdbeben-Tempo sorgt für eine unerschöpfliche Anregung. Wenn die Szenarien zu unfair und unmöglich sind, kann sie sich jede Zeit ansehen. Für wen richtig so ist, kaufen Sie Bejeweled 2 Deluxe.

        -

        In this mode, you can use as few or as many tiles as you want to in order to match the set of gems. The match that occurs once the domino is set in motion has the chance to fail or succeed. If it succeeds, the other domino will be set off until it too fails and the match is over. Level How many tiles can you play with? Bejeweled 2 Deluxe FREE DOWNLOAD. Bejeweled Deluxe is a collection of upgrades that will allow your game to run smoother, add new features, and improve your final score. Download Bejeweled Deluxe Full Version game now. Bejeweled 2 Deluxe Level 5 - Brain Freeze. Bejeweled 2 Deluxe - Das erste Spiel ist für uns mächtig cool. Es ermöglicht es, von Fernsehen, Zeitungen und Zeitzeugen in Fernsehprogrammen zu gebrauchen. Das frische, irre Formen und wiederholbare Erdbeben-Tempo sorgt für eine unerschöpfliche Anregung. Wenn die Szenarien zu unfair und unmöglich sind, kann sie sich jede Zeit ansehen. Für wen richtig so ist, kaufen Sie Bejeweled 2 Deluxe.

        899543212b
        -
        -
        \ No newline at end of file diff --git a/spaces/ivanmeyer/Finetuned_Diffusion_Max/app.py b/spaces/ivanmeyer/Finetuned_Diffusion_Max/app.py deleted file mode 100644 index 60013ef381b5cb57bf4333f3de0c64eed7f66a50..0000000000000000000000000000000000000000 --- a/spaces/ivanmeyer/Finetuned_Diffusion_Max/app.py +++ /dev/null @@ -1,428 +0,0 @@ -from diffusers import AutoencoderKL, UNet2DConditionModel, StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler -import gradio as gr -import torch -from PIL import Image -import utils -import datetime -import time -import psutil -import random - - -start_time = time.time() -is_colab = utils.is_google_colab() -state = None -current_steps = 25 - -class Model: - def __init__(self, name, path="", prefix=""): - self.name = name - self.path = path - self.prefix = prefix - self.pipe_t2i = None - self.pipe_i2i = None - -models = [ - Model("Dreamlike Diffusion 1.0", "dreamlike-art/dreamlike-diffusion-1.0", "dreamlikeart "), - Model("Dreamlike Photoreal 2.0", "dreamlike-art/dreamlike-photoreal-2.0", ""), - Model("Eimis Anime 1.0", "flax/EimisAnimeDiffusion_1.0v", ""), - Model("Eimis SemiRealistic", "eimiss/EimisSemiRealistic", ""), - Model("Portrait Plus", "wavymulder/portraitplus", "portrait+ style "), - Model("Protogen 5.3 (for plain realism, a bit bland)", "darkstorm2150/Protogen_v5.3_Official_Release", ""), - Model("Protogen 5.8 (for realism, but toward fantasy)", "darkstorm2150/Protogen_v5.8_Official_Release", ""), - Model("Protogen Dragon (for fantasy)", "darkstorm2150/Protogen_Dragon_Official_Release", ""), - Model("Protogen Nova (the all in one)", "darkstorm2150/Protogen_Nova_Official_Release", ""), - Model("Seek.Art Mega", "coreco/seek.art_MEGA", ""), - Model("Uber Realistic Porn Merge","PrimaPramudya/uberRealisticPrnMer_urpMv11", ""), - Model("Vintedois 0.1", "22h/vintedois-diffusion-v0-1", ""), - Model("Analog Diffusion", "wavymulder/Analog-Diffusion", "analog style "), - Model("Anything V3", "Linaqruf/anything-v3.0", ""), - Model("Arcane", "nitrosocke/Arcane-Diffusion", "arcane style "), - Model("Archer", "nitrosocke/archer-diffusion", "archer style "), - Model("Cyberpunk Anime", "DGSpitzer/Cyberpunk-Anime-Diffusion", "dgs illustration style "), - Model("Disney, modern", "nitrosocke/mo-di-diffusion", "modern disney style "), - Model("Disney, Classic", "nitrosocke/classic-anim-diffusion", "classic disney style "), - Model("DnD Item", "stale2000/sd-dnditem", "dnditem "), - Model("Elden Ring", "nitrosocke/elden-ring-diffusion", "elden ring style "), - Model("f222 Zeipfher", "m4gnett/zeipher-f222", ""), - Model("f222 + Anything V3", "m4gnett/anything-of-f222", ""), - Model("Loving Vincent (Van Gogh)", "dallinmackay/Van-Gogh-diffusion", "lvngvncnt "), - Model("Midjourney v4 style", "prompthero/openjourney", "mdjrny-v4 style "), - Model("Pokémon", "lambdalabs/sd-pokemon-diffusers"), - Model("Pony Diffusion", "AstraliteHeart/pony-diffusion"), - Model("Redshift renderer (Cinema4D)", "nitrosocke/redshift-diffusion", "redshift style "), - Model("Robo Diffusion", "nousr/robo-diffusion"), - Model("Spider-Verse", "nitrosocke/spider-verse-diffusion", "spiderverse style "), - Model("TrinArt v2", "naclbit/trinart_stable_diffusion_v2"), - Model("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion", "trnlgcy "), - Model("Waifu", "hakurei/waifu-diffusion"), - Model("Wavyfusion", "wavymulder/wavyfusion", "wa-vy style "), - Model("Balloon Art", "Fictiverse/Stable_Diffusion_BalloonArt_Model", "BalloonArt "), - Model("Anything V3 Better-Vae", "Linaqruf/anything-v3-better-vae", ""), - Model("Anything V4", "andite/anything-v4.0", ""), - Model("Cyberpunk Anime with Genshin Characters supported", "AdamOswald1/Cyberpunk-Anime-Diffusion_with_support_for_Gen-Imp_characters", "cyberpunk style"), - Model("Dark Souls", "Guizmus/DarkSoulsDiffusion", "dark souls style"), - Model("Space Machine", "rabidgremlin/sd-db-epic-space-machine", "EpicSpaceMachine"), - Model("Spacecraft", "rabidgremlin/sd-db-epic-space-machine, Guizmus/Tardisfusion", "EpicSpaceMachine, Tardis Box style"), - Model("TARDIS", "Guizmus/Tardisfusion", "Tardis Box style"), - Model("Modern Era TARDIS Interior", "Guizmus/Tardisfusion", "Modern Tardis style"), - Model("Classic Era TARDIS Interior", "Guizmus/Tardisfusion", "Classic Tardis style"), - Model("Spacecraft Interior", "Guizmus/Tardisfusion, rabidgremlin/sd-db-epic-space-machine", "Classic Tardis style, Modern Tardis style, EpicSpaceMachine"), - Model("CLIP", "EleutherAI/clip-guided-diffusion", "CLIP"), - Model("Genshin Waifu", "crumb/genshin-stable-inversion, yuiqena/GenshinImpact, katakana/2D-Mix, Guizmus/AnimeChanStyle", "Female, female, Woman, woman, Girl, girl"), - Model("Genshin", "crumb/genshin-stable-inversion, yuiqena/GenshinImpact, katakana/2D-Mix, Guizmus/AnimeChanStyle", ""), - Model("Test", "AdamOswald1/Idk", ""), - Model("Test2", "AdamOswald1/Tester", ""), - Model("Anime", "Guizmus/AnimeChanStyle, katakana/2D-Mix", ""), - Model("Beeple", "riccardogiorato/beeple-diffusion", "beeple style "), - Model("Avatar", "riccardogiorato/avatar-diffusion", "avatartwow style "), - Model("Poolsuite", "prompthero/poolsuite", "poolsuite style "), - Model("Epic Diffusion", "johnslegers/epic-diffusion", ""), - Model("Comic Diffusion", "ogkalu/Comic-Diffusion", ""), - Model("Realistic Vision 1.2", "SG161222/Realistic_Vision_V1.2", ""), - Model("Stable Diffusion 2.1", "stabilityai/stable-diffusion-2-1", ""), - Model("OrangeMixs", "WarriorMama777/OrangeMixs", "Abyss"), - Model("Inkpunk-Diffusion", "Envvi/Inkpunk-Diffusion", "nvinkpunk"), - Model("openjourney-v2", "prompthero/openjourney-v2", ""), - Model("hassenblend 1.4", "hassanblend/hassanblend1.4", ""), - Model("Cyberpunk-Anime-Diffusion", "DGSpitzer/Cyberpunk-Anime-Diffusion", "DGS Illustration style"), - Model("Ghibli-Diffusion", "nitrosocke/Ghibli-Diffusion", "ghibli style"), - Model("Pastel-Mix", "andite/pastel-mix", "mksks style"), - Model("trinart_stable_diffusion_v2", "naclbit/trinart_stable_diffusion_v2", ""), - Model("Counterfeit-V2.0", "gsdf/Counterfeit-V2.0", ""), - Model("stable diffusion 2.1 base", "stabilityai/stable-diffusion-2-1-base", ""), - Model("Double Exposure Diffusion", "joachimsallstrom/Double-Exposure-Diffusion", "dublex style, dublex"), - Model("Yohan Diffusion", "andite/yohan-diffusion", ""), - Model("rMadArt2.5", "rmada/rMadArt2.5", ""), - Model("unico", "Cinnamomo/unico", ""), - Model("Inizio", "Cinnamomo/inizio", ""), - Model("HARDblend", "theintuitiveye/HARDblend", "photorealistic, instagram photography, shot on iphone, RAW, professional photograph"), - Model("FantasyMix-v1", "theintuitiveye/FantasyMix-v1", ""), - Model("modernartstyle", "theintuitiveye/modernartstyle", "modernartst"), - Model("paint-jpurney-v2", "FredZhang7/paint-journey-v2", "oil painting"), - Model("Sygil-Diffusion", "Sygil/Sygil-Diffusion", ""), - Model("g_yuusukeStyle", "grullborg/g_yuusukeStyle", ""), - Model("th-diffusion", "furusu/th-diffusion", "realistic"), - Model("SD_Black_Ancient_Egyptian_Style", "Akumetsu971/SD_Black_Ancient_Egyptian_Style", "Bck_Egpt"), - Model("Shortjourney", "x67/shortjourney", "sjrny-v1 style"), - Model("Kenshi", "SweetLuna/Kenshi", ""), - Model("lomo-diffusion", "wavymulder/lomo-diffusion", "lomo style"), - Model("RainerMix", "Hemlok/RainierMix", ""), - Model("GuoFeng3", "xiaolxl/GuoFeng3", ""), - Model("sketchstyle-cutesexyrobutts", "Cosk/sketchstyle-cutesexyrobutts", ""), - Model("Counterfeit-V2.5", "gsdf/Counterfeit-V2.5", ""), - Model("TriPhaze", "Lucetepolis/TriPhaze", ""), - Model("SukiyakiMix-1.0", "Vsukiyaki/SukiyakiMix-v1.0", ""), - Model("icon-diffusion-v1-1", "crumb/icon-diffusion-v1-1", ""), - Model("Strange_Dedication", "MortalSage/Strange_Dedication", ""), - Model("openjourney-v2", "prompthero/openjourney-v2", ""), - Model("Funko-Diffusion", "prompthero/funko-diffusion", "funko style"), - Model("DreamShaper", "Lykon/DreamShaper", "dreamshaper"), - Model("Realistic_Vision_V1.4", "SG161222/Realistic_Vision_V1.4", ""), - - - - - -] - -custom_model = None -if is_colab: - models.insert(0, Model("Custom model")) - custom_model = models[0] - -last_mode = "txt2img" -current_model = models[1] if is_colab else models[0] -current_model_path = current_model.path - -if is_colab: - pipe = StableDiffusionPipeline.from_pretrained( - current_model.path, - torch_dtype=torch.float16, - scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler"), - safety_checker=None - ) - -else: - pipe = StableDiffusionPipeline.from_pretrained( - current_model.path, - torch_dtype=torch.float16, - scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler") - ) - -if torch.cuda.is_available(): - pipe = pipe.to("cuda") - pipe.enable_xformers_memory_efficient_attention() - -device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶" - -def error_str(error, title="Error"): - return f"""#### {title} - {error}""" if error else "" - -def update_state(new_state): - global state - state = new_state - -def update_state_info(old_state): - if state and state != old_state: - return gr.update(value=state) - -def custom_model_changed(path): - models[0].path = path - global current_model - current_model = models[0] - -def on_model_change(model_name): - - prefix = "Enter prompt. \"" + next((m.prefix for m in models if m.name == model_name), None) + "\" is prefixed automatically" if model_name != models[0].name else "Don't forget to use the custom model prefix in the prompt!" - - return gr.update(visible = model_name == models[0].name), gr.update(placeholder=prefix) - -def on_steps_change(steps): - global current_steps - current_steps = steps - -def pipe_callback(step: int, timestep: int, latents: torch.FloatTensor): - update_state(f"{step}/{current_steps} steps")#\nTime left, sec: {timestep/100:.0f}") - -def inference(model_name, prompt, guidance, steps, n_images=1, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""): - - update_state(" ") - - print(psutil.virtual_memory()) # print memory usage - - global current_model - for model in models: - if model.name == model_name: - current_model = model - model_path = current_model.path - - # generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None - if seed == 0: - seed = random.randint(0, 2147483647) - - generator = torch.Generator('cuda').manual_seed(seed) - - try: - if img is not None: - return img_to_img(model_path, prompt, n_images, neg_prompt, img, strength, guidance, steps, width, height, generator, seed), f"Done. Seed: {seed}" - else: - return txt_to_img(model_path, prompt, n_images, neg_prompt, guidance, steps, width, height, generator, seed), f"Done. Seed: {seed}" - except Exception as e: - return None, error_str(e) - -def txt_to_img(model_path, prompt, n_images, neg_prompt, guidance, steps, width, height, generator, seed): - - print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}") - - global last_mode - global pipe - global current_model_path - if model_path != current_model_path or last_mode != "txt2img": - current_model_path = model_path - - update_state(f"Loading {current_model.name} text-to-image model...") - - if is_colab or current_model == custom_model: - pipe = StableDiffusionPipeline.from_pretrained( - current_model_path, - torch_dtype=torch.float16, - scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler"), - safety_checker=None - ) - else: - pipe = StableDiffusionPipeline.from_pretrained( - current_model_path, - torch_dtype=torch.float16, - scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler") - ) - # pipe = pipe.to("cpu") - # pipe = current_model.pipe_t2i - - if torch.cuda.is_available(): - pipe = pipe.to("cuda") - pipe.enable_xformers_memory_efficient_attention() - last_mode = "txt2img" - - prompt = current_model.prefix + prompt - result = pipe( - prompt, - negative_prompt = neg_prompt, - num_images_per_prompt=n_images, - num_inference_steps = int(steps), - guidance_scale = guidance, - width = width, - height = height, - generator = generator, - callback=pipe_callback) - - # update_state(f"Done. Seed: {seed}") - - return replace_nsfw_images(result) - -def img_to_img(model_path, prompt, n_images, neg_prompt, img, strength, guidance, steps, width, height, generator, seed): - - print(f"{datetime.datetime.now()} img_to_img, model: {model_path}") - - global last_mode - global pipe - global current_model_path - if model_path != current_model_path or last_mode != "img2img": - current_model_path = model_path - - update_state(f"Loading {current_model.name} image-to-image model...") - - if is_colab or current_model == custom_model: - pipe = StableDiffusionImg2ImgPipeline.from_pretrained( - current_model_path, - torch_dtype=torch.float16, - scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler"), - safety_checker=None - ) - else: - pipe = StableDiffusionImg2ImgPipeline.from_pretrained( - current_model_path, - torch_dtype=torch.float16, - scheduler=DPMSolverMultistepScheduler.from_pretrained(current_model.path, subfolder="scheduler") - ) - # pipe = pipe.to("cpu") - # pipe = current_model.pipe_i2i - - if torch.cuda.is_available(): - pipe = pipe.to("cuda") - pipe.enable_xformers_memory_efficient_attention() - last_mode = "img2img" - - prompt = current_model.prefix + prompt - ratio = min(height / img.height, width / img.width) - img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS) - result = pipe( - prompt, - negative_prompt = neg_prompt, - num_images_per_prompt=n_images, - image = img, - num_inference_steps = int(steps), - strength = strength, - guidance_scale = guidance, - # width = width, - # height = height, - generator = generator, - callback=pipe_callback) - - # update_state(f"Done. Seed: {seed}") - - return replace_nsfw_images(result) - -def replace_nsfw_images(results): - - if is_colab: - return results.images - - for i in range(len(results.images)): - if results.nsfw_content_detected[i]: - results.images[i] = Image.open("nsfw.png") - return results.images - -# css = """.finetuned-diffusion-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.finetuned-diffusion-div div h1{font-weight:900;margin-bottom:7px}.finetuned-diffusion-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem} -# """ -with gr.Blocks(css="style.css") as demo: - gr.HTML( - f""" -
        -
        -

        Finetuned Diffusion Max

        -
        -

        - Demo for multiple fine-tuned Stable Diffusion models, trained on different styles:
        - Arcane, Archer, Elden Ring, Spider-Verse, Modern Disney, Classic Disney, Loving Vincent (Van Gogh), Redshift renderer (Cinema4D), Midjourney v4 style, Waifu, Pokémon, Pony Diffusion, Robo Diffusion, Cyberpunk Anime, Tron Legacy, Balloon Art + in colab notebook you can load any other Diffusers 🧨 SD model hosted on HuggingFace 🤗. -

        -

        You can skip the queue and load custom models in the colab: Open In Colab

        - Running on {device}{(" in a Google Colab." if is_colab else "")} -

        -

        You can also duplicate this space and upgrade to gpu by going to settings:
        - Duplicate Space

        -
        - """ - ) - with gr.Row(): - - with gr.Column(scale=55): - with gr.Group(): - model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name) - with gr.Box(visible=False) as custom_model_group: - custom_model_path = gr.Textbox(label="Custom model path", placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion", interactive=True) - gr.HTML("
        Custom models have to be downloaded first, so give it some time.
        ") - - with gr.Row(): - prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="Enter prompt. Style applied automatically").style(container=False) - generate = gr.Button(value="Generate").style(rounded=(False, True, True, False)) - - - # image_out = gr.Image(height=512) - gallery = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery").style(grid=[2], height="auto") - - state_info = gr.Textbox(label="State", show_label=False, max_lines=2).style(container=False) - error_output = gr.Markdown() - - with gr.Column(scale=45): - with gr.Tab("Options"): - with gr.Group(): - neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image") - - n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=10, step=1) - - with gr.Row(): - guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15) - steps = gr.Slider(label="Steps", value=current_steps, minimum=2, maximum=250, step=1) - - with gr.Row(): - width = gr.Slider(label="Width", value=512, minimum=64, maximum=2048, step=8) - height = gr.Slider(label="Height", value=512, minimum=64, maximum=2048, step=8) - - seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1) - - with gr.Tab("Image to image"): - with gr.Group(): - image = gr.Image(label="Image", height=256, tool="editor", type="pil") - strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5) - - if is_colab: - model_name.change(on_model_change, inputs=model_name, outputs=[custom_model_group, prompt], queue=False) - custom_model_path.change(custom_model_changed, inputs=custom_model_path, outputs=None) - # n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery) - steps.change(on_steps_change, inputs=[steps], outputs=[], queue=False) - - inputs = [model_name, prompt, guidance, steps, n_images, width, height, seed, image, strength, neg_prompt] - outputs = [gallery, error_output] - prompt.submit(inference, inputs=inputs, outputs=outputs) - generate.click(inference, inputs=inputs, outputs=outputs) - - ex = gr.Examples([ - [models[7].name, "tiny cute and adorable kitten adventurer dressed in a warm overcoat with survival gear on a winters day", 7.5, 25], - [models[4].name, "portrait of dwayne johnson", 7.0, 35], - [models[5].name, "portrait of a beautiful alyx vance half life", 10, 25], - [models[6].name, "Aloy from Horizon: Zero Dawn, half body portrait, smooth, detailed armor, beautiful face, illustration", 7.0, 30], - [models[5].name, "fantasy portrait painting, digital art", 4.0, 20], - ], inputs=[model_name, prompt, guidance, steps], outputs=outputs, fn=inference, cache_examples=False) - - gr.HTML(""" -
        -
        -

        Models by @nitrosocke, @haruu1367, @Helixngc7293, @dal_mack, @prompthero and others. ❤️

        -

        This space uses the DPM-Solver++ sampler by Cheng Lu, et al..

        -

        Space by:
        - Twitter Follow
        - GitHub followers



        - Buy Me A Coffee

        -

        visitors

        -
        - """) - - demo.load(update_state_info, inputs=state_info, outputs=state_info, every=0.5, show_progress=False) - -print(f"Space built in {time.time() - start_time:.2f} seconds") - -# if not is_colab: -demo.queue(concurrency_count=1) -demo.launch(debug=is_colab, share=is_colab) diff --git a/spaces/ivntl/MMS/uroman/lib/JSON/backportPP/Compat5005.pm b/spaces/ivntl/MMS/uroman/lib/JSON/backportPP/Compat5005.pm deleted file mode 100644 index 139990edff0a28474e53f882d4c4efeb2ad7d701..0000000000000000000000000000000000000000 --- a/spaces/ivntl/MMS/uroman/lib/JSON/backportPP/Compat5005.pm +++ /dev/null @@ -1,131 +0,0 @@ -package # This is JSON::backportPP - JSON::backportPP5005; - -use 5.005; -use strict; - -my @properties; - -$JSON::PP5005::VERSION = '1.10'; - -BEGIN { - - sub utf8::is_utf8 { - 0; # It is considered that UTF8 flag off for Perl 5.005. - } - - sub utf8::upgrade { - } - - sub utf8::downgrade { - 1; # must always return true. - } - - sub utf8::encode { - } - - sub utf8::decode { - } - - *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii; - *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1; - *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates; - *JSON::PP::JSON_PP_decode_unicode = \&_decode_unicode; - - # missing in B module. - sub B::SVp_IOK () { 0x01000000; } - sub B::SVp_NOK () { 0x02000000; } - sub B::SVp_POK () { 0x04000000; } - - $INC{'bytes.pm'} = 1; # dummy -} - - - -sub _encode_ascii { - join('', map { $_ <= 127 ? chr($_) : sprintf('\u%04x', $_) } unpack('C*', $_[0]) ); -} - - -sub _encode_latin1 { - join('', map { chr($_) } unpack('C*', $_[0]) ); -} - - -sub _decode_surrogates { # from http://homepage1.nifty.com/nomenclator/unicode/ucs_utf.htm - my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00); # from perlunicode - my $bit = unpack('B32', pack('N', $uni)); - - if ( $bit =~ /^00000000000(...)(......)(......)(......)$/ ) { - my ($w, $x, $y, $z) = ($1, $2, $3, $4); - return pack('B*', sprintf('11110%s10%s10%s10%s', $w, $x, $y, $z)); - } - else { - Carp::croak("Invalid surrogate pair"); - } -} - - -sub _decode_unicode { - my ($u) = @_; - my ($utf8bit); - - if ( $u =~ /^00([89a-f][0-9a-f])$/i ) { # 0x80-0xff - return pack( 'H2', $1 ); - } - - my $bit = unpack("B*", pack("H*", $u)); - - if ( $bit =~ /^00000(.....)(......)$/ ) { - $utf8bit = sprintf('110%s10%s', $1, $2); - } - elsif ( $bit =~ /^(....)(......)(......)$/ ) { - $utf8bit = sprintf('1110%s10%s10%s', $1, $2, $3); - } - else { - Carp::croak("Invalid escaped unicode"); - } - - return pack('B*', $utf8bit); -} - - -sub JSON::PP::incr_text { - $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new; - - if ( $_[0]->{_incr_parser}->{incr_parsing} ) { - Carp::croak("incr_text can not be called when the incremental parser already started parsing"); - } - - $_[0]->{_incr_parser}->{incr_text} = $_[1] if ( @_ > 1 ); - $_[0]->{_incr_parser}->{incr_text}; -} - - -1; -__END__ - -=pod - -=head1 NAME - -JSON::PP5005 - Helper module in using JSON::PP in Perl 5.005 - -=head1 DESCRIPTION - -JSON::PP calls internally. - -=head1 AUTHOR - -Makamaka Hannyaharamitu, Emakamaka[at]cpan.orgE - - -=head1 COPYRIGHT AND LICENSE - -Copyright 2007-2012 by Makamaka Hannyaharamitu - -This library is free software; you can redistribute it and/or modify -it under the same terms as Perl itself. - -=cut - diff --git a/spaces/ixciel/img-to-music/README.md b/spaces/ixciel/img-to-music/README.md deleted file mode 100644 index ff1948d1b95ee1f8d7a3396aefb285c729d18687..0000000000000000000000000000000000000000 --- a/spaces/ixciel/img-to-music/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Img To Music -emoji: 🌅🎶 -colorFrom: green -colorTo: purple -sdk: gradio -sdk_version: 3.16.0 -app_file: app.py -pinned: true -duplicated_from: fffiloni/img-to-music ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/jackli888/stable-diffusion-webui/javascript/extensions.js b/spaces/jackli888/stable-diffusion-webui/javascript/extensions.js deleted file mode 100644 index 8a0580f706a9511e3391b9170e6684c2655b893a..0000000000000000000000000000000000000000 --- a/spaces/jackli888/stable-diffusion-webui/javascript/extensions.js +++ /dev/null @@ -1,49 +0,0 @@ - -function extensions_apply(_, _){ - var disable = [] - var update = [] - - gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x){ - if(x.name.startsWith("enable_") && ! x.checked) - disable.push(x.name.substr(7)) - - if(x.name.startsWith("update_") && x.checked) - update.push(x.name.substr(7)) - }) - - restart_reload() - - return [JSON.stringify(disable), JSON.stringify(update)] -} - -function extensions_check(){ - var disable = [] - - gradioApp().querySelectorAll('#extensions input[type="checkbox"]').forEach(function(x){ - if(x.name.startsWith("enable_") && ! x.checked) - disable.push(x.name.substr(7)) - }) - - gradioApp().querySelectorAll('#extensions .extension_status').forEach(function(x){ - x.innerHTML = "Loading..." - }) - - - var id = randomId() - requestProgress(id, gradioApp().getElementById('extensions_installed_top'), null, function(){ - - }) - - return [id, JSON.stringify(disable)] -} - -function install_extension_from_index(button, url){ - button.disabled = "disabled" - button.value = "Installing..." - - textarea = gradioApp().querySelector('#extension_to_install textarea') - textarea.value = url - updateInput(textarea) - - gradioApp().querySelector('#install_extension_button').click() -} diff --git a/spaces/jannisborn/paccmann/submission.py b/spaces/jannisborn/paccmann/submission.py deleted file mode 100644 index 3344329a2ebbbd6c02510e76133f9c5972ebfe5e..0000000000000000000000000000000000000000 --- a/spaces/jannisborn/paccmann/submission.py +++ /dev/null @@ -1,124 +0,0 @@ -"""Submission-related utilities.""" -import os -import json -import logging -import numpy as np -import pandas as pd -from io import StringIO -from typing import Optional -from sklearn.preprocessing import StandardScaler -from configuration import ( - GENE_EXPRESSION_DATA, - GENE_EXPRESSION_METADATA, - GENES, - GENE_STANDARDIZATION_PARAMETERS, -) -from cos import RESULTS_PREFIX, string_to_key -from forward import predict - -# from attention import upload_attention - -logger = logging.getLogger("openapi_server:submission") - - -def submission( - drug: dict, - workspace_id: str, - task_id: str, - estimate_confidence: bool = False, - omics_file: Optional[str] = None, -) -> None: - """ - Submit PaccMann prediction - - Args: - drug (dict): drug to analyse in dictionary format. - workspace_id (str): workspace identifier for the submission. - task_id (str): task identifier. - estimate_confidence (bool, optional): estimate confidence of the - prediction. Defaults to False. - omics_file (Optional[str], optional): path to file containing - expression data. Defaults to None. - """ - prefix = os.path.join(RESULTS_PREFIX, workspace_id, task_id) - logger.debug("processing omic data.") - # NOTE: this trick is used in case a single example is passed - single_example = False - result = {} - if omics_file is None: - gene_expression, gene_expression_metadata = ( - GENE_EXPRESSION_DATA, - GENE_EXPRESSION_METADATA, - ) - else: - logger.debug("parsing uploaded omic data.") - logger.debug(omics_file) - gene_expression_df = pd.read_csv(omics_file, low_memory=False) - logger.debug(gene_expression_df.columns) - to_drop = list(set(GENES) & set(gene_expression_df.columns)) - gene_expression_data, gene_expression_metadata = ( - gene_expression_df.T.reindex(GENES).fillna(0.0).T, - gene_expression_df.drop(to_drop, axis=1), - ) - logger.debug("peek parsed expression and metadata.") - logger.debug("gene_expression_data:\n{}".format(gene_expression_data.head())) - logger.debug( - "gene_expression_metadata:\n{}".format(gene_expression_metadata.head()) - ) - if gene_expression_data.shape[0] < 2: - logger.debug( - "single example, standardizing with default parameters:\n{}".format( - GENE_STANDARDIZATION_PARAMETERS - ) - ) - single_example = True - gene_expression = ( - gene_expression_data.values - GENE_STANDARDIZATION_PARAMETERS[0] - ) / GENE_STANDARDIZATION_PARAMETERS[1] - gene_expression = np.vstack(2 * [gene_expression]) - logger.debug(gene_expression.shape) - else: - gene_expression = StandardScaler().fit_transform( - gene_expression_data.values - ) - logger.debug("gene_expression:\n{}".format(gene_expression[:10])) - logger.debug("omic data prepared if present.") - prediction_dict = predict( - smiles=drug["smiles"], - gene_expression=gene_expression, - estimate_confidence=estimate_confidence, - ) - # from tensors - for key, value in prediction_dict.items(): - prediction_dict[key] = value.numpy()[:1] if single_example else value.numpy() - - result.update(prediction_dict) - # merge for single table, index is unique identifier for samples. - gene_expression_metadata["IC50 (min/max scaled)"] = prediction_dict["IC50"] - gene_expression_metadata["IC50 (log(μmol))"] = prediction_dict[ - "log_micromolar_IC50" - ] - if estimate_confidence: - gene_expression_metadata["epistemic_confidence"] = prediction_dict[ - "epistemic_confidence" - ] - gene_expression_metadata["aleatoric_confidence"] = prediction_dict[ - "aleatoric_confidence" - ] - logger.debug("uploaded predicted sensitivity table including metadata.") - # attention - # result.update( - # upload_attention( - # prefix, - # sample_names=list(map(str, gene_expression_metadata.index)), - # omic_attention=prediction_dict["gene_attention"], - # smiles_attention=prediction_dict["smiles_attention"], - # ) - # ) - logger.debug("uploaded attention for each sample.") - logger.debug("uploading drug information and sensitivity.") - # prediction (is sensitivity_json in API) - logger.debug("uploaded drug information and sensitivity.") - - # NOTE: Ordering corresponds to IDs in GEP metadata! - return result diff --git a/spaces/jbetker/tortoise/do_tts.py b/spaces/jbetker/tortoise/do_tts.py deleted file mode 100644 index fa0347e64c587786a90eeb053f7efb388f323bf9..0000000000000000000000000000000000000000 --- a/spaces/jbetker/tortoise/do_tts.py +++ /dev/null @@ -1,34 +0,0 @@ -import argparse -import os - -import torchaudio - -from api import TextToSpeech -from utils.audio import load_audio, get_voices - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('--text', type=str, help='Text to speak.', default="I am a language model that has learned to speak.") - parser.add_argument('--voice', type=str, help='Selects the voice to use for generation. See options in voices/ directory (and add your own!) ' - 'Use the & character to join two voices together. Use a comma to perform inference on multiple voices.', default='pat') - parser.add_argument('--preset', type=str, help='Which voice preset to use.', default='standard') - parser.add_argument('--voice_diversity_intelligibility_slider', type=float, - help='How to balance vocal diversity with the quality/intelligibility of the spoken text. 0 means highly diverse voice (not recommended), 1 means maximize intellibility', - default=.5) - parser.add_argument('--output_path', type=str, help='Where to store outputs.', default='results/') - args = parser.parse_args() - os.makedirs(args.output_path, exist_ok=True) - - tts = TextToSpeech() - - voices = get_voices() - selected_voices = args.voice.split(',') - for voice in selected_voices: - cond_paths = voices[voice] - conds = [] - for cond_path in cond_paths: - c = load_audio(cond_path, 22050) - conds.append(c) - gen = tts.tts_with_preset(args.text, conds, preset=args.preset, clvp_cvvp_slider=args.voice_diversity_intelligibility_slider) - torchaudio.save(os.path.join(args.output_path, f'{voice}.wav'), gen.squeeze(0).cpu(), 24000) - diff --git a/spaces/jbilcke-hf/ai-comic-factory/src/app/queries/predictWithHuggingFace.ts b/spaces/jbilcke-hf/ai-comic-factory/src/app/queries/predictWithHuggingFace.ts deleted file mode 100644 index a709c5a1deeab1fab7570f98ae0b10feb2d0ce9a..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/ai-comic-factory/src/app/queries/predictWithHuggingFace.ts +++ /dev/null @@ -1,97 +0,0 @@ -"use server" - -import { HfInference, HfInferenceEndpoint } from "@huggingface/inference" -import { LLMEngine } from "@/types" - -export async function predict(inputs: string, nbPanels: number): Promise { - const hf = new HfInference(process.env.AUTH_HF_API_TOKEN) - - const llmEngine = `${process.env.LLM_ENGINE || ""}` as LLMEngine - const inferenceEndpoint = `${process.env.LLM_HF_INFERENCE_ENDPOINT_URL || ""}` - const inferenceModel = `${process.env.LLM_HF_INFERENCE_API_MODEL || ""}` - - let hfie: HfInferenceEndpoint = hf - - // we don't require a lot of token for our task - // but to be safe, let's count ~110 tokens per panel - const nbMaxNewTokens = nbPanels * 110 - - switch (llmEngine) { - case "INFERENCE_ENDPOINT": - if (inferenceEndpoint) { - // console.log("Using a custom HF Inference Endpoint") - hfie = hf.endpoint(inferenceEndpoint) - } else { - const error = "No Inference Endpoint URL defined" - console.error(error) - throw new Error(error) - } - break; - - case "INFERENCE_API": - if (inferenceModel) { - // console.log("Using an HF Inference API Model") - } else { - const error = "No Inference API model defined" - console.error(error) - throw new Error(error) - } - break; - - default: - const error = "Please check your Hugging Face Inference API or Inference Endpoint settings" - console.error(error) - throw new Error(error) - } - - const api = llmEngine === "INFERENCE_ENDPOINT" ? hfie : hf - - let instructions = "" - try { - for await (const output of api.textGenerationStream({ - model: llmEngine === "INFERENCE_ENDPOINT" ? undefined : (inferenceModel || undefined), - inputs, - parameters: { - do_sample: true, - max_new_tokens: nbMaxNewTokens, - return_full_text: false, - } - })) { - instructions += output.token.text - process.stdout.write(output.token.text) - if ( - instructions.includes("") || - instructions.includes("") || - instructions.includes("[INST]") || - instructions.includes("[/INST]") || - instructions.includes("") || - instructions.includes("") || - instructions.includes("<|end|>") || - instructions.includes("<|assistant|>") - ) { - break - } - } - } catch (err) { - console.error(`error during generation: ${err}`) - - // a common issue with Llama-2 might be that the model receives too many requests - if (`${err}` === "Error: Model is overloaded") { - instructions = `` - } - } - - // need to do some cleanup of the garbage the LLM might have gave us - return ( - instructions - .replaceAll("<|end|>", "") - .replaceAll("", "") - .replaceAll("", "") - .replaceAll("[INST]", "") - .replaceAll("[/INST]", "") - .replaceAll("", "") - .replaceAll("", "") - .replaceAll("<|assistant|>", "") - .replaceAll('""', '"') - ) -} diff --git a/spaces/jbilcke-hf/ai-comic-factory/src/lib/utils.ts b/spaces/jbilcke-hf/ai-comic-factory/src/lib/utils.ts deleted file mode 100644 index ec79801fe9cdd7711f6dbef26678a134c634a8be..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/ai-comic-factory/src/lib/utils.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { type ClassValue, clsx } from "clsx" -import { twMerge } from "tailwind-merge" - -export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)) -} diff --git a/spaces/jeonchangbin49/De-limiter/README.md b/spaces/jeonchangbin49/De-limiter/README.md deleted file mode 100644 index cf85c266108c36a5d26188a461db461ace9c01c9..0000000000000000000000000000000000000000 --- a/spaces/jeonchangbin49/De-limiter/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: De-limiter Demo -emoji: 🎶 -colorFrom: black -colorTo: white -sdk: gradio -sdk_version: 3.39.0 -app_file: app.py -pinned: true ---- \ No newline at end of file diff --git a/spaces/jeycov/IsaTronDeteccion/app.py b/spaces/jeycov/IsaTronDeteccion/app.py deleted file mode 100644 index 430d8d1d228e91150fd9d25de54e6734ad0a4f99..0000000000000000000000000000000000000000 --- a/spaces/jeycov/IsaTronDeteccion/app.py +++ /dev/null @@ -1,50 +0,0 @@ -import gradio as gr -import numpy as np -import tensorflow -from tensorflow.keras.models import load_model -from tensorflow.keras.preprocessing import image - -MODEL_ISATRON_JEY = 'modelo_isatron_jeysshonl.h5' - -cnn_model = load_model(MODEL_ISATRON_JEY) - -def make_prediction(test_image): - test_image = test_image.name - test_image = image.load_img(test_image, target_size=(224, 224)) - test_image = image.img_to_array(test_image) / 255. - test_image = np.expand_dims(test_image, axis=0) - result = cnn_model.predict(test_image) - return {"Normal": str(result[0][0]), "Neumonia": str(result[0][1])} - - -image_input = gr.inputs.Image(type="file") - -description = " El modelo IsaTron es una Red Neuronal Convolucional (CNN) diseñada como un método de apoyo medico para el diagnóstico en imágenes radiológicas de neumonía pediátrica. Isatron arroja un porcentaje para lograr interpretar la radiografia torácica. En la parte inferior encontrará unas imágenes que pueden ser usadas para ejemplificar el funcionamiento del modelo. https://repositorio.unbosque.edu.co/handle/20.500.12495/9514" - - - -enable_queue = True -examples = [ - ['1normal.jpeg'], - ['image1_pneumonia_virus.jpeg'], - ['image1_pneumonia_bacteria.jpeg'], - ['image2_normal.jpeg'], - ['image2_pneumonia_bacteria.jpeg'], - ['image3_normal.jpeg'], - ['image4_normal.jpeg'], - ] - -article= "

        IsaTron . Jeysshon Bustos . 2022.

        " - - -interface=gr.Interface(fn=make_prediction, - inputs=image_input, - outputs='label', - title="Modelo (CNN) IsaTron ", - ##interpretation = "default", - description=description, - theme="default", - article=article, - examples=examples, - enable_queue=enable_queue ) -interface.launch(share=True) diff --git a/spaces/joao-victor-campos/netflix-recommendation-model/README.md b/spaces/joao-victor-campos/netflix-recommendation-model/README.md deleted file mode 100644 index d269e34547b0cbf1ac5dca53a0234d40dffe0a19..0000000000000000000000000000000000000000 --- a/spaces/joao-victor-campos/netflix-recommendation-model/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Netflix Recommendation App -emoji: 📈 -colorFrom: pink -colorTo: gray -sdk: gradio -sdk_version: 3.1.6 -app_file: app.py -pinned: false -license: afl-3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/PIL/ImageEnhance.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/PIL/ImageEnhance.py deleted file mode 100644 index 3b79d5c46a16ce89dfff1694f0121a743d8fa0c7..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/PIL/ImageEnhance.py +++ /dev/null @@ -1,103 +0,0 @@ -# -# The Python Imaging Library. -# $Id$ -# -# image enhancement classes -# -# For a background, see "Image Processing By Interpolation and -# Extrapolation", Paul Haeberli and Douglas Voorhies. Available -# at http://www.graficaobscura.com/interp/index.html -# -# History: -# 1996-03-23 fl Created -# 2009-06-16 fl Fixed mean calculation -# -# Copyright (c) Secret Labs AB 1997. -# Copyright (c) Fredrik Lundh 1996. -# -# See the README file for information on usage and redistribution. -# - -from . import Image, ImageFilter, ImageStat - - -class _Enhance: - def enhance(self, factor): - """ - Returns an enhanced image. - - :param factor: A floating point value controlling the enhancement. - Factor 1.0 always returns a copy of the original image, - lower factors mean less color (brightness, contrast, - etc), and higher values more. There are no restrictions - on this value. - :rtype: :py:class:`~PIL.Image.Image` - """ - return Image.blend(self.degenerate, self.image, factor) - - -class Color(_Enhance): - """Adjust image color balance. - - This class can be used to adjust the colour balance of an image, in - a manner similar to the controls on a colour TV set. An enhancement - factor of 0.0 gives a black and white image. A factor of 1.0 gives - the original image. - """ - - def __init__(self, image): - self.image = image - self.intermediate_mode = "L" - if "A" in image.getbands(): - self.intermediate_mode = "LA" - - self.degenerate = image.convert(self.intermediate_mode).convert(image.mode) - - -class Contrast(_Enhance): - """Adjust image contrast. - - This class can be used to control the contrast of an image, similar - to the contrast control on a TV set. An enhancement factor of 0.0 - gives a solid grey image. A factor of 1.0 gives the original image. - """ - - def __init__(self, image): - self.image = image - mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5) - self.degenerate = Image.new("L", image.size, mean).convert(image.mode) - - if "A" in image.getbands(): - self.degenerate.putalpha(image.getchannel("A")) - - -class Brightness(_Enhance): - """Adjust image brightness. - - This class can be used to control the brightness of an image. An - enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the - original image. - """ - - def __init__(self, image): - self.image = image - self.degenerate = Image.new(image.mode, image.size, 0) - - if "A" in image.getbands(): - self.degenerate.putalpha(image.getchannel("A")) - - -class Sharpness(_Enhance): - """Adjust image sharpness. - - This class can be used to adjust the sharpness of an image. An - enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the - original image, and a factor of 2.0 gives a sharpened image. - """ - - def __init__(self, image): - self.image = image - self.degenerate = image.filter(ImageFilter.SMOOTH) - - if "A" in image.getbands(): - self.degenerate.putalpha(image.getchannel("A")) diff --git a/spaces/johnslegers/stable-diffusion-gui-test/ui/config/on_env_start.bat b/spaces/johnslegers/stable-diffusion-gui-test/ui/config/on_env_start.bat deleted file mode 100644 index a73198ce870b40867767697ffb7d010069025413..0000000000000000000000000000000000000000 --- a/spaces/johnslegers/stable-diffusion-gui-test/ui/config/on_env_start.bat +++ /dev/null @@ -1,62 +0,0 @@ -@echo off - -@echo. & echo "Stable Diffusion UI - v2" & echo. - -set PATH=C:\Windows\System32;%PATH% - -@cd .. - -if exist "scripts\config.bat" ( - @call scripts\config.bat -) - -if "%update_branch%"=="" ( - set update_branch=main -) - -@>nul grep -c "conda_sd_ui_deps_installed" scripts\install_status.txt -@if "%ERRORLEVEL%" NEQ "0" ( - for /f "tokens=*" %%a in ('python -c "import os; parts = os.getcwd().split(os.path.sep); print(len(parts))"') do if "%%a" NEQ "2" ( - echo. & echo "!!!! WARNING !!!!" & echo. - echo "Your 'stable-diffusion-ui' folder is at %cd%" & echo. - echo "The 'stable-diffusion-ui' folder needs to be at the top of your drive, for e.g. 'C:\stable-diffusion-ui' or 'D:\stable-diffusion-ui' etc." - echo "Not placing this folder at the top of a drive can cause errors on some computers." - echo. & echo "Recommended: Please close this window and move the 'stable-diffusion-ui' folder to the top of a drive. For e.g. 'C:\stable-diffusion-ui'. Then run the installer again." & echo. - echo "Not Recommended: If you're sure that you want to install at the current location, please press any key to continue." & echo. - - pause - ) -) - -@>nul grep -c "sd_ui_git_cloned" scripts\install_status.txt -@if "%ERRORLEVEL%" EQU "0" ( - @echo "Stable Diffusion UI's git repository was already installed. Updating from %update_branch%.." - - @cd sd-ui-files - - @call git reset --hard - @call git checkout "%update_branch%" - @call git pull - - @cd .. -) else ( - @echo. & echo "Downloading Stable Diffusion UI.." & echo. - @echo "Using the %update_branch% channel" & echo. - - @call git clone -b "%update_branch%" https://github.com/cmdr2/stable-diffusion-ui.git sd-ui-files && ( - @echo sd_ui_git_cloned >> scripts\install_status.txt - ) || ( - @echo "Error downloading Stable Diffusion UI. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" - pause - @exit /b - ) -) - -@xcopy sd-ui-files\ui ui /s /i /Y -@copy sd-ui-files\scripts\on_sd_start.bat scripts\ /Y -@copy "sd-ui-files\scripts\Start Stable Diffusion UI.cmd" . /Y -@copy "sd-ui-files\scripts\Developer Console.cmd" . /Y - -@call scripts\on_sd_start.bat - -@pause \ No newline at end of file diff --git a/spaces/joshen/gpt-academic/crazy_functions/test_project/cpp/longcode/prod_cons.h b/spaces/joshen/gpt-academic/crazy_functions/test_project/cpp/longcode/prod_cons.h deleted file mode 100644 index c9004bb8043a12e32814436baa6262a00c8ef68e..0000000000000000000000000000000000000000 --- a/spaces/joshen/gpt-academic/crazy_functions/test_project/cpp/longcode/prod_cons.h +++ /dev/null @@ -1,433 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "libipc/def.h" - -#include "libipc/platform/detail.h" -#include "libipc/circ/elem_def.h" -#include "libipc/utility/log.h" -#include "libipc/utility/utility.h" - -namespace ipc { - -//////////////////////////////////////////////////////////////// -/// producer-consumer implementation -//////////////////////////////////////////////////////////////// - -template -struct prod_cons_impl; - -template <> -struct prod_cons_impl> { - - template - struct elem_t { - std::aligned_storage_t data_ {}; - }; - - alignas(cache_line_size) std::atomic rd_; // read index - alignas(cache_line_size) std::atomic wt_; // write index - - constexpr circ::u2_t cursor() const noexcept { - return 0; - } - - template - bool push(W* /*wrapper*/, F&& f, E* elems) { - auto cur_wt = circ::index_of(wt_.load(std::memory_order_relaxed)); - if (cur_wt == circ::index_of(rd_.load(std::memory_order_acquire) - 1)) { - return false; // full - } - std::forward(f)(&(elems[cur_wt].data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - /** - * In single-single-unicast, 'force_push' means 'no reader' or 'the only one reader is dead'. - * So we could just disconnect all connections of receiver, and return false. - */ - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(~static_cast(0u)); - return false; - } - - template - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - auto cur_rd = circ::index_of(rd_.load(std::memory_order_relaxed)); - if (cur_rd == circ::index_of(wt_.load(std::memory_order_acquire))) { - return false; // empty - } - std::forward(f)(&(elems[cur_rd].data_)); - std::forward(out)(true); - rd_.fetch_add(1, std::memory_order_release); - return true; - } -}; - -template <> -struct prod_cons_impl> - : prod_cons_impl> { - - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(1); - return false; - } - - template class E, std::size_t DS, std::size_t AS> - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - byte_t buff[DS]; - for (unsigned k = 0;;) { - auto cur_rd = rd_.load(std::memory_order_relaxed); - if (circ::index_of(cur_rd) == - circ::index_of(wt_.load(std::memory_order_acquire))) { - return false; // empty - } - std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff)); - if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) { - std::forward(f)(buff); - std::forward(out)(true); - return true; - } - ipc::yield(k); - } - } -}; - -template <> -struct prod_cons_impl> - : prod_cons_impl> { - - using flag_t = std::uint64_t; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic f_ct_ { 0 }; // commit flag - }; - - alignas(cache_line_size) std::atomic ct_; // commit index - - template - bool push(W* /*wrapper*/, F&& f, E* elems) { - circ::u2_t cur_ct, nxt_ct; - for (unsigned k = 0;;) { - cur_ct = ct_.load(std::memory_order_relaxed); - if (circ::index_of(nxt_ct = cur_ct + 1) == - circ::index_of(rd_.load(std::memory_order_acquire))) { - return false; // full - } - if (ct_.compare_exchange_weak(cur_ct, nxt_ct, std::memory_order_acq_rel)) { - break; - } - ipc::yield(k); - } - auto* el = elems + circ::index_of(cur_ct); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - while (1) { - auto cac_ct = el->f_ct_.load(std::memory_order_acquire); - if (cur_ct != wt_.load(std::memory_order_relaxed)) { - return true; - } - if ((~cac_ct) != cur_ct) { - return true; - } - if (!el->f_ct_.compare_exchange_strong(cac_ct, 0, std::memory_order_relaxed)) { - return true; - } - wt_.store(nxt_ct, std::memory_order_release); - cur_ct = nxt_ct; - nxt_ct = cur_ct + 1; - el = elems + circ::index_of(cur_ct); - } - return true; - } - - template - bool force_push(W* wrapper, F&&, E*) { - wrapper->elems()->disconnect_receiver(1); - return false; - } - - template class E, std::size_t DS, std::size_t AS> - bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) { - byte_t buff[DS]; - for (unsigned k = 0;;) { - auto cur_rd = rd_.load(std::memory_order_relaxed); - auto cur_wt = wt_.load(std::memory_order_acquire); - auto id_rd = circ::index_of(cur_rd); - auto id_wt = circ::index_of(cur_wt); - if (id_rd == id_wt) { - auto* el = elems + id_wt; - auto cac_ct = el->f_ct_.load(std::memory_order_acquire); - if ((~cac_ct) != cur_wt) { - return false; // empty - } - if (el->f_ct_.compare_exchange_weak(cac_ct, 0, std::memory_order_relaxed)) { - wt_.store(cur_wt + 1, std::memory_order_release); - } - k = 0; - } - else { - std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff)); - if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) { - std::forward(f)(buff); - std::forward(out)(true); - return true; - } - ipc::yield(k); - } - } - } -}; - -template <> -struct prod_cons_impl> { - - using rc_t = std::uint64_t; - - enum : rc_t { - ep_mask = 0x00000000ffffffffull, - ep_incr = 0x0000000100000000ull - }; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic rc_ { 0 }; // read-counter - }; - - alignas(cache_line_size) std::atomic wt_; // write index - alignas(cache_line_size) rc_t epoch_ { 0 }; // only one writer - - circ::u2_t cursor() const noexcept { - return wt_.load(std::memory_order_acquire); - } - - template - bool push(W* wrapper, F&& f, E* elems) { - E* el; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(wt_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & ep_mask; - if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch_)) { - return false; // has not finished yet - } - // consider rem_cc to be 0 here - if (el->rc_.compare_exchange_weak( - cur_rc, epoch_ | static_cast(cc), std::memory_order_release)) { - break; - } - ipc::yield(k); - } - std::forward(f)(&(el->data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - template - bool force_push(W* wrapper, F&& f, E* elems) { - E* el; - epoch_ += ep_incr; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(wt_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & ep_mask; - if (cc & rem_cc) { - ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc); - cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers - if (cc == 0) return false; // no reader - } - // just compare & exchange - if (el->rc_.compare_exchange_weak( - cur_rc, epoch_ | static_cast(cc), std::memory_order_release)) { - break; - } - ipc::yield(k); - } - std::forward(f)(&(el->data_)); - wt_.fetch_add(1, std::memory_order_release); - return true; - } - - template - bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E* elems) { - if (cur == cursor()) return false; // acquire - auto* el = elems + circ::index_of(cur++); - std::forward(f)(&(el->data_)); - for (unsigned k = 0;;) { - auto cur_rc = el->rc_.load(std::memory_order_acquire); - if ((cur_rc & ep_mask) == 0) { - std::forward(out)(true); - return true; - } - auto nxt_rc = cur_rc & ~static_cast(wrapper->connected_id()); - if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) { - std::forward(out)((nxt_rc & ep_mask) == 0); - return true; - } - ipc::yield(k); - } - } -}; - -template <> -struct prod_cons_impl> { - - using rc_t = std::uint64_t; - using flag_t = std::uint64_t; - - enum : rc_t { - rc_mask = 0x00000000ffffffffull, - ep_mask = 0x00ffffffffffffffull, - ep_incr = 0x0100000000000000ull, - ic_mask = 0xff000000ffffffffull, - ic_incr = 0x0000000100000000ull - }; - - template - struct elem_t { - std::aligned_storage_t data_ {}; - std::atomic rc_ { 0 }; // read-counter - std::atomic f_ct_ { 0 }; // commit flag - }; - - alignas(cache_line_size) std::atomic ct_; // commit index - alignas(cache_line_size) std::atomic epoch_ { 0 }; - - circ::u2_t cursor() const noexcept { - return ct_.load(std::memory_order_acquire); - } - - constexpr static rc_t inc_rc(rc_t rc) noexcept { - return (rc & ic_mask) | ((rc + ic_incr) & ~ic_mask); - } - - constexpr static rc_t inc_mask(rc_t rc) noexcept { - return inc_rc(rc) & ~rc_mask; - } - - template - bool push(W* wrapper, F&& f, E* elems) { - E* el; - circ::u2_t cur_ct; - rc_t epoch = epoch_.load(std::memory_order_acquire); - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_relaxed); - circ::cc_t rem_cc = cur_rc & rc_mask; - if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch)) { - return false; // has not finished yet - } - else if (!rem_cc) { - auto cur_fl = el->f_ct_.load(std::memory_order_acquire); - if ((cur_fl != cur_ct) && cur_fl) { - return false; // full - } - } - // consider rem_cc to be 0 here - if (el->rc_.compare_exchange_weak( - cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast(cc), std::memory_order_relaxed) && - epoch_.compare_exchange_weak(epoch, epoch, std::memory_order_acq_rel)) { - break; - } - ipc::yield(k); - } - // only one thread/process would touch here at one time - ct_.store(cur_ct + 1, std::memory_order_release); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - return true; - } - - template - bool force_push(W* wrapper, F&& f, E* elems) { - E* el; - circ::u2_t cur_ct; - rc_t epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr; - for (unsigned k = 0;;) { - circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed); - if (cc == 0) return false; // no reader - el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed)); - // check all consumers have finished reading this element - auto cur_rc = el->rc_.load(std::memory_order_acquire); - circ::cc_t rem_cc = cur_rc & rc_mask; - if (cc & rem_cc) { - ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc); - cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers - if (cc == 0) return false; // no reader - } - // just compare & exchange - if (el->rc_.compare_exchange_weak( - cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast(cc), std::memory_order_relaxed)) { - if (epoch == epoch_.load(std::memory_order_acquire)) { - break; - } - else if (push(wrapper, std::forward(f), elems)) { - return true; - } - epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr; - } - ipc::yield(k); - } - // only one thread/process would touch here at one time - ct_.store(cur_ct + 1, std::memory_order_release); - std::forward(f)(&(el->data_)); - // set flag & try update wt - el->f_ct_.store(~static_cast(cur_ct), std::memory_order_release); - return true; - } - - template - bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E(& elems)[N]) { - auto* el = elems + circ::index_of(cur); - auto cur_fl = el->f_ct_.load(std::memory_order_acquire); - if (cur_fl != ~static_cast(cur)) { - return false; // empty - } - ++cur; - std::forward(f)(&(el->data_)); - for (unsigned k = 0;;) { - auto cur_rc = el->rc_.load(std::memory_order_acquire); - if ((cur_rc & rc_mask) == 0) { - std::forward(out)(true); - el->f_ct_.store(cur + N - 1, std::memory_order_release); - return true; - } - auto nxt_rc = inc_rc(cur_rc) & ~static_cast(wrapper->connected_id()); - bool last_one = false; - if ((last_one = (nxt_rc & rc_mask) == 0)) { - el->f_ct_.store(cur + N - 1, std::memory_order_release); - } - if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) { - std::forward(out)(last_one); - return true; - } - ipc::yield(k); - } - } -}; - -} // namespace ipc diff --git a/spaces/jungealexander/uspppm-demo/README.md b/spaces/jungealexander/uspppm-demo/README.md deleted file mode 100644 index 1451410597ee3a4ad76627d7766b4219bf9b94e9..0000000000000000000000000000000000000000 --- a/spaces/jungealexander/uspppm-demo/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: U.S. Patent Phrase to Phrase Matching Demo -emoji: 📜 -colorFrom: gray -colorTo: purple -sdk: gradio -python_version: 3.9.9 -sdk_version: 2.9.4 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/kcagle/AutoGPT/autogpt/configurator.py b/spaces/kcagle/AutoGPT/autogpt/configurator.py deleted file mode 100644 index 1dc3be124f638b8859eb459bcb2d46696f62e2b7..0000000000000000000000000000000000000000 --- a/spaces/kcagle/AutoGPT/autogpt/configurator.py +++ /dev/null @@ -1,134 +0,0 @@ -"""Configurator module.""" -import click -from colorama import Back, Fore, Style - -from autogpt import utils -from autogpt.config import Config -from autogpt.logs import logger -from autogpt.memory import get_supported_memory_backends - -CFG = Config() - - -def create_config( - continuous: bool, - continuous_limit: int, - ai_settings_file: str, - skip_reprompt: bool, - speak: bool, - debug: bool, - gpt3only: bool, - gpt4only: bool, - memory_type: str, - browser_name: str, - allow_downloads: bool, - skip_news: bool, -) -> None: - """Updates the config object with the given arguments. - - Args: - continuous (bool): Whether to run in continuous mode - continuous_limit (int): The number of times to run in continuous mode - ai_settings_file (str): The path to the ai_settings.yaml file - skip_reprompt (bool): Whether to skip the re-prompting messages at the beginning of the script - speak (bool): Whether to enable speak mode - debug (bool): Whether to enable debug mode - gpt3only (bool): Whether to enable GPT3.5 only mode - gpt4only (bool): Whether to enable GPT4 only mode - memory_type (str): The type of memory backend to use - browser_name (str): The name of the browser to use when using selenium to scrape the web - allow_downloads (bool): Whether to allow Auto-GPT to download files natively - skips_news (bool): Whether to suppress the output of latest news on startup - """ - CFG.set_debug_mode(False) - CFG.set_continuous_mode(False) - CFG.set_speak_mode(False) - - if debug: - logger.typewriter_log("Debug Mode: ", Fore.GREEN, "ENABLED") - CFG.set_debug_mode(True) - - if continuous: - logger.typewriter_log("Continuous Mode: ", Fore.RED, "ENABLED") - logger.typewriter_log( - "WARNING: ", - Fore.RED, - "Continuous mode is not recommended. It is potentially dangerous and may" - " cause your AI to run forever or carry out actions you would not usually" - " authorise. Use at your own risk.", - ) - CFG.set_continuous_mode(True) - - if continuous_limit: - logger.typewriter_log( - "Continuous Limit: ", Fore.GREEN, f"{continuous_limit}" - ) - CFG.set_continuous_limit(continuous_limit) - - # Check if continuous limit is used without continuous mode - if continuous_limit and not continuous: - raise click.UsageError("--continuous-limit can only be used with --continuous") - - if speak: - logger.typewriter_log("Speak Mode: ", Fore.GREEN, "ENABLED") - CFG.set_speak_mode(True) - - if gpt3only: - logger.typewriter_log("GPT3.5 Only Mode: ", Fore.GREEN, "ENABLED") - CFG.set_smart_llm_model(CFG.fast_llm_model) - - if gpt4only: - logger.typewriter_log("GPT4 Only Mode: ", Fore.GREEN, "ENABLED") - CFG.set_fast_llm_model(CFG.smart_llm_model) - - if memory_type: - supported_memory = get_supported_memory_backends() - chosen = memory_type - if chosen not in supported_memory: - logger.typewriter_log( - "ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", - Fore.RED, - f"{supported_memory}", - ) - logger.typewriter_log("Defaulting to: ", Fore.YELLOW, CFG.memory_backend) - else: - CFG.memory_backend = chosen - - if skip_reprompt: - logger.typewriter_log("Skip Re-prompt: ", Fore.GREEN, "ENABLED") - CFG.skip_reprompt = True - - if ai_settings_file: - file = ai_settings_file - - # Validate file - (validated, message) = utils.validate_yaml_file(file) - if not validated: - logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message) - logger.double_check() - exit(1) - - logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file) - CFG.ai_settings_file = file - CFG.skip_reprompt = True - - if allow_downloads: - logger.typewriter_log("Native Downloading:", Fore.GREEN, "ENABLED") - logger.typewriter_log( - "WARNING: ", - Fore.YELLOW, - f"{Back.LIGHTYELLOW_EX}Auto-GPT will now be able to download and save files to your machine.{Back.RESET} " - + "It is recommended that you monitor any files it downloads carefully.", - ) - logger.typewriter_log( - "WARNING: ", - Fore.YELLOW, - f"{Back.RED + Style.BRIGHT}ALWAYS REMEMBER TO NEVER OPEN FILES YOU AREN'T SURE OF!{Style.RESET_ALL}", - ) - CFG.allow_downloads = True - - if skip_news: - CFG.skip_news = True - - if browser_name: - CFG.selenium_web_browser = browser_name diff --git a/spaces/kcagle/AutoGPT/run.sh b/spaces/kcagle/AutoGPT/run.sh deleted file mode 100644 index edcbc44155b9ca9df83e283fdf976472c13e6492..0000000000000000000000000000000000000000 --- a/spaces/kcagle/AutoGPT/run.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -python scripts/check_requirements.py requirements.txt -if [ $? -eq 1 ] -then - echo Installing missing packages... - pip install -r requirements.txt -fi -python -m autogpt $@ -read -p "Press any key to continue..." diff --git a/spaces/kevinwang676/Bark-with-Voice-Cloning/util/helper.py b/spaces/kevinwang676/Bark-with-Voice-Cloning/util/helper.py deleted file mode 100644 index 185613661a2f450e55a5d2add1a1e75bc08f5c19..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/Bark-with-Voice-Cloning/util/helper.py +++ /dev/null @@ -1,35 +0,0 @@ -import os -from datetime import datetime -from mutagen.wave import WAVE -from mutagen.id3._frames import * - -def create_filename(path, seed, name, extension): - now = datetime.now() - date_str =now.strftime("%m-%d-%Y") - outputs_folder = os.path.join(os.getcwd(), path) - if not os.path.exists(outputs_folder): - os.makedirs(outputs_folder) - - sub_folder = os.path.join(outputs_folder, date_str) - if not os.path.exists(sub_folder): - os.makedirs(sub_folder) - - time_str = now.strftime("%H-%M-%S") - if seed == None: - file_name = f"{name}_{time_str}{extension}" - else: - file_name = f"{name}_{time_str}_s{seed}{extension}" - return os.path.join(sub_folder, file_name) - - -def add_id3_tag(filename, text, speakername, seed): - audio = WAVE(filename) - if speakername == None: - speakername = "Unconditional" - - # write id3 tag with text truncated to 60 chars, as a precaution... - audio["TIT2"] = TIT2(encoding=3, text=text[:60]) - audio["TPE1"] = TPE1(encoding=3, text=f"Voice {speakername} using Seed={seed}") - audio["TPUB"] = TPUB(encoding=3, text="Bark by Suno AI") - audio["COMMENT"] = COMM(encoding=3, text="Generated with Bark GUI - Text-Prompted Generative Audio Model. Visit https://github.com/C0untFloyd/bark-gui") - audio.save() diff --git a/spaces/kevinwang676/ChatGLM2-SadTalker/speaker_encoder/visualizations.py b/spaces/kevinwang676/ChatGLM2-SadTalker/speaker_encoder/visualizations.py deleted file mode 100644 index ec00fc64d6e9fda2bb8e613531066ac824df1451..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/ChatGLM2-SadTalker/speaker_encoder/visualizations.py +++ /dev/null @@ -1,178 +0,0 @@ -from speaker_encoder.data_objects.speaker_verification_dataset import SpeakerVerificationDataset -from datetime import datetime -from time import perf_counter as timer -import matplotlib.pyplot as plt -import numpy as np -# import webbrowser -import visdom -import umap - -colormap = np.array([ - [76, 255, 0], - [0, 127, 70], - [255, 0, 0], - [255, 217, 38], - [0, 135, 255], - [165, 0, 165], - [255, 167, 255], - [0, 255, 255], - [255, 96, 38], - [142, 76, 0], - [33, 0, 127], - [0, 0, 0], - [183, 183, 183], -], dtype=np.float) / 255 - - -class Visualizations: - def __init__(self, env_name=None, update_every=10, server="http://localhost", disabled=False): - # Tracking data - self.last_update_timestamp = timer() - self.update_every = update_every - self.step_times = [] - self.losses = [] - self.eers = [] - print("Updating the visualizations every %d steps." % update_every) - - # If visdom is disabled TODO: use a better paradigm for that - self.disabled = disabled - if self.disabled: - return - - # Set the environment name - now = str(datetime.now().strftime("%d-%m %Hh%M")) - if env_name is None: - self.env_name = now - else: - self.env_name = "%s (%s)" % (env_name, now) - - # Connect to visdom and open the corresponding window in the browser - try: - self.vis = visdom.Visdom(server, env=self.env_name, raise_exceptions=True) - except ConnectionError: - raise Exception("No visdom server detected. Run the command \"visdom\" in your CLI to " - "start it.") - # webbrowser.open("http://localhost:8097/env/" + self.env_name) - - # Create the windows - self.loss_win = None - self.eer_win = None - # self.lr_win = None - self.implementation_win = None - self.projection_win = None - self.implementation_string = "" - - def log_params(self): - if self.disabled: - return - from speaker_encoder import params_data - from speaker_encoder import params_model - param_string = "Model parameters:
        " - for param_name in (p for p in dir(params_model) if not p.startswith("__")): - value = getattr(params_model, param_name) - param_string += "\t%s: %s
        " % (param_name, value) - param_string += "Data parameters:
        " - for param_name in (p for p in dir(params_data) if not p.startswith("__")): - value = getattr(params_data, param_name) - param_string += "\t%s: %s
        " % (param_name, value) - self.vis.text(param_string, opts={"title": "Parameters"}) - - def log_dataset(self, dataset: SpeakerVerificationDataset): - if self.disabled: - return - dataset_string = "" - dataset_string += "Speakers: %s\n" % len(dataset.speakers) - dataset_string += "\n" + dataset.get_logs() - dataset_string = dataset_string.replace("\n", "
        ") - self.vis.text(dataset_string, opts={"title": "Dataset"}) - - def log_implementation(self, params): - if self.disabled: - return - implementation_string = "" - for param, value in params.items(): - implementation_string += "%s: %s\n" % (param, value) - implementation_string = implementation_string.replace("\n", "
        ") - self.implementation_string = implementation_string - self.implementation_win = self.vis.text( - implementation_string, - opts={"title": "Training implementation"} - ) - - def update(self, loss, eer, step): - # Update the tracking data - now = timer() - self.step_times.append(1000 * (now - self.last_update_timestamp)) - self.last_update_timestamp = now - self.losses.append(loss) - self.eers.append(eer) - print(".", end="") - - # Update the plots every steps - if step % self.update_every != 0: - return - time_string = "Step time: mean: %5dms std: %5dms" % \ - (int(np.mean(self.step_times)), int(np.std(self.step_times))) - print("\nStep %6d Loss: %.4f EER: %.4f %s" % - (step, np.mean(self.losses), np.mean(self.eers), time_string)) - if not self.disabled: - self.loss_win = self.vis.line( - [np.mean(self.losses)], - [step], - win=self.loss_win, - update="append" if self.loss_win else None, - opts=dict( - legend=["Avg. loss"], - xlabel="Step", - ylabel="Loss", - title="Loss", - ) - ) - self.eer_win = self.vis.line( - [np.mean(self.eers)], - [step], - win=self.eer_win, - update="append" if self.eer_win else None, - opts=dict( - legend=["Avg. EER"], - xlabel="Step", - ylabel="EER", - title="Equal error rate" - ) - ) - if self.implementation_win is not None: - self.vis.text( - self.implementation_string + ("%s" % time_string), - win=self.implementation_win, - opts={"title": "Training implementation"}, - ) - - # Reset the tracking - self.losses.clear() - self.eers.clear() - self.step_times.clear() - - def draw_projections(self, embeds, utterances_per_speaker, step, out_fpath=None, - max_speakers=10): - max_speakers = min(max_speakers, len(colormap)) - embeds = embeds[:max_speakers * utterances_per_speaker] - - n_speakers = len(embeds) // utterances_per_speaker - ground_truth = np.repeat(np.arange(n_speakers), utterances_per_speaker) - colors = [colormap[i] for i in ground_truth] - - reducer = umap.UMAP() - projected = reducer.fit_transform(embeds) - plt.scatter(projected[:, 0], projected[:, 1], c=colors) - plt.gca().set_aspect("equal", "datalim") - plt.title("UMAP projection (step %d)" % step) - if not self.disabled: - self.projection_win = self.vis.matplot(plt, win=self.projection_win) - if out_fpath is not None: - plt.savefig(out_fpath) - plt.clf() - - def save(self): - if not self.disabled: - self.vis.save([self.env_name]) - \ No newline at end of file diff --git a/spaces/kevinwang676/SadTalker/src/face3d/models/bfm.py b/spaces/kevinwang676/SadTalker/src/face3d/models/bfm.py deleted file mode 100644 index a75db682f02dd1979d4a7de1d11dd3aa5cdf5279..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/SadTalker/src/face3d/models/bfm.py +++ /dev/null @@ -1,331 +0,0 @@ -"""This script defines the parametric 3d face model for Deep3DFaceRecon_pytorch -""" - -import numpy as np -import torch -import torch.nn.functional as F -from scipy.io import loadmat -from src.face3d.util.load_mats import transferBFM09 -import os - -def perspective_projection(focal, center): - # return p.T (N, 3) @ (3, 3) - return np.array([ - focal, 0, center, - 0, focal, center, - 0, 0, 1 - ]).reshape([3, 3]).astype(np.float32).transpose() - -class SH: - def __init__(self): - self.a = [np.pi, 2 * np.pi / np.sqrt(3.), 2 * np.pi / np.sqrt(8.)] - self.c = [1/np.sqrt(4 * np.pi), np.sqrt(3.) / np.sqrt(4 * np.pi), 3 * np.sqrt(5.) / np.sqrt(12 * np.pi)] - - - -class ParametricFaceModel: - def __init__(self, - bfm_folder='./BFM', - recenter=True, - camera_distance=10., - init_lit=np.array([ - 0.8, 0, 0, 0, 0, 0, 0, 0, 0 - ]), - focal=1015., - center=112., - is_train=True, - default_name='BFM_model_front.mat'): - - if not os.path.isfile(os.path.join(bfm_folder, default_name)): - transferBFM09(bfm_folder) - - model = loadmat(os.path.join(bfm_folder, default_name)) - # mean face shape. [3*N,1] - self.mean_shape = model['meanshape'].astype(np.float32) - # identity basis. [3*N,80] - self.id_base = model['idBase'].astype(np.float32) - # expression basis. [3*N,64] - self.exp_base = model['exBase'].astype(np.float32) - # mean face texture. [3*N,1] (0-255) - self.mean_tex = model['meantex'].astype(np.float32) - # texture basis. [3*N,80] - self.tex_base = model['texBase'].astype(np.float32) - # face indices for each vertex that lies in. starts from 0. [N,8] - self.point_buf = model['point_buf'].astype(np.int64) - 1 - # vertex indices for each face. starts from 0. [F,3] - self.face_buf = model['tri'].astype(np.int64) - 1 - # vertex indices for 68 landmarks. starts from 0. [68,1] - self.keypoints = np.squeeze(model['keypoints']).astype(np.int64) - 1 - - if is_train: - # vertex indices for small face region to compute photometric error. starts from 0. - self.front_mask = np.squeeze(model['frontmask2_idx']).astype(np.int64) - 1 - # vertex indices for each face from small face region. starts from 0. [f,3] - self.front_face_buf = model['tri_mask2'].astype(np.int64) - 1 - # vertex indices for pre-defined skin region to compute reflectance loss - self.skin_mask = np.squeeze(model['skinmask']) - - if recenter: - mean_shape = self.mean_shape.reshape([-1, 3]) - mean_shape = mean_shape - np.mean(mean_shape, axis=0, keepdims=True) - self.mean_shape = mean_shape.reshape([-1, 1]) - - self.persc_proj = perspective_projection(focal, center) - self.device = 'cpu' - self.camera_distance = camera_distance - self.SH = SH() - self.init_lit = init_lit.reshape([1, 1, -1]).astype(np.float32) - - - def to(self, device): - self.device = device - for key, value in self.__dict__.items(): - if type(value).__module__ == np.__name__: - setattr(self, key, torch.tensor(value).to(device)) - - - def compute_shape(self, id_coeff, exp_coeff): - """ - Return: - face_shape -- torch.tensor, size (B, N, 3) - - Parameters: - id_coeff -- torch.tensor, size (B, 80), identity coeffs - exp_coeff -- torch.tensor, size (B, 64), expression coeffs - """ - batch_size = id_coeff.shape[0] - id_part = torch.einsum('ij,aj->ai', self.id_base, id_coeff) - exp_part = torch.einsum('ij,aj->ai', self.exp_base, exp_coeff) - face_shape = id_part + exp_part + self.mean_shape.reshape([1, -1]) - return face_shape.reshape([batch_size, -1, 3]) - - - def compute_texture(self, tex_coeff, normalize=True): - """ - Return: - face_texture -- torch.tensor, size (B, N, 3), in RGB order, range (0, 1.) - - Parameters: - tex_coeff -- torch.tensor, size (B, 80) - """ - batch_size = tex_coeff.shape[0] - face_texture = torch.einsum('ij,aj->ai', self.tex_base, tex_coeff) + self.mean_tex - if normalize: - face_texture = face_texture / 255. - return face_texture.reshape([batch_size, -1, 3]) - - - def compute_norm(self, face_shape): - """ - Return: - vertex_norm -- torch.tensor, size (B, N, 3) - - Parameters: - face_shape -- torch.tensor, size (B, N, 3) - """ - - v1 = face_shape[:, self.face_buf[:, 0]] - v2 = face_shape[:, self.face_buf[:, 1]] - v3 = face_shape[:, self.face_buf[:, 2]] - e1 = v1 - v2 - e2 = v2 - v3 - face_norm = torch.cross(e1, e2, dim=-1) - face_norm = F.normalize(face_norm, dim=-1, p=2) - face_norm = torch.cat([face_norm, torch.zeros(face_norm.shape[0], 1, 3).to(self.device)], dim=1) - - vertex_norm = torch.sum(face_norm[:, self.point_buf], dim=2) - vertex_norm = F.normalize(vertex_norm, dim=-1, p=2) - return vertex_norm - - - def compute_color(self, face_texture, face_norm, gamma): - """ - Return: - face_color -- torch.tensor, size (B, N, 3), range (0, 1.) - - Parameters: - face_texture -- torch.tensor, size (B, N, 3), from texture model, range (0, 1.) - face_norm -- torch.tensor, size (B, N, 3), rotated face normal - gamma -- torch.tensor, size (B, 27), SH coeffs - """ - batch_size = gamma.shape[0] - v_num = face_texture.shape[1] - a, c = self.SH.a, self.SH.c - gamma = gamma.reshape([batch_size, 3, 9]) - gamma = gamma + self.init_lit - gamma = gamma.permute(0, 2, 1) - Y = torch.cat([ - a[0] * c[0] * torch.ones_like(face_norm[..., :1]).to(self.device), - -a[1] * c[1] * face_norm[..., 1:2], - a[1] * c[1] * face_norm[..., 2:], - -a[1] * c[1] * face_norm[..., :1], - a[2] * c[2] * face_norm[..., :1] * face_norm[..., 1:2], - -a[2] * c[2] * face_norm[..., 1:2] * face_norm[..., 2:], - 0.5 * a[2] * c[2] / np.sqrt(3.) * (3 * face_norm[..., 2:] ** 2 - 1), - -a[2] * c[2] * face_norm[..., :1] * face_norm[..., 2:], - 0.5 * a[2] * c[2] * (face_norm[..., :1] ** 2 - face_norm[..., 1:2] ** 2) - ], dim=-1) - r = Y @ gamma[..., :1] - g = Y @ gamma[..., 1:2] - b = Y @ gamma[..., 2:] - face_color = torch.cat([r, g, b], dim=-1) * face_texture - return face_color - - - def compute_rotation(self, angles): - """ - Return: - rot -- torch.tensor, size (B, 3, 3) pts @ trans_mat - - Parameters: - angles -- torch.tensor, size (B, 3), radian - """ - - batch_size = angles.shape[0] - ones = torch.ones([batch_size, 1]).to(self.device) - zeros = torch.zeros([batch_size, 1]).to(self.device) - x, y, z = angles[:, :1], angles[:, 1:2], angles[:, 2:], - - rot_x = torch.cat([ - ones, zeros, zeros, - zeros, torch.cos(x), -torch.sin(x), - zeros, torch.sin(x), torch.cos(x) - ], dim=1).reshape([batch_size, 3, 3]) - - rot_y = torch.cat([ - torch.cos(y), zeros, torch.sin(y), - zeros, ones, zeros, - -torch.sin(y), zeros, torch.cos(y) - ], dim=1).reshape([batch_size, 3, 3]) - - rot_z = torch.cat([ - torch.cos(z), -torch.sin(z), zeros, - torch.sin(z), torch.cos(z), zeros, - zeros, zeros, ones - ], dim=1).reshape([batch_size, 3, 3]) - - rot = rot_z @ rot_y @ rot_x - return rot.permute(0, 2, 1) - - - def to_camera(self, face_shape): - face_shape[..., -1] = self.camera_distance - face_shape[..., -1] - return face_shape - - def to_image(self, face_shape): - """ - Return: - face_proj -- torch.tensor, size (B, N, 2), y direction is opposite to v direction - - Parameters: - face_shape -- torch.tensor, size (B, N, 3) - """ - # to image_plane - face_proj = face_shape @ self.persc_proj - face_proj = face_proj[..., :2] / face_proj[..., 2:] - - return face_proj - - - def transform(self, face_shape, rot, trans): - """ - Return: - face_shape -- torch.tensor, size (B, N, 3) pts @ rot + trans - - Parameters: - face_shape -- torch.tensor, size (B, N, 3) - rot -- torch.tensor, size (B, 3, 3) - trans -- torch.tensor, size (B, 3) - """ - return face_shape @ rot + trans.unsqueeze(1) - - - def get_landmarks(self, face_proj): - """ - Return: - face_lms -- torch.tensor, size (B, 68, 2) - - Parameters: - face_proj -- torch.tensor, size (B, N, 2) - """ - return face_proj[:, self.keypoints] - - def split_coeff(self, coeffs): - """ - Return: - coeffs_dict -- a dict of torch.tensors - - Parameters: - coeffs -- torch.tensor, size (B, 256) - """ - id_coeffs = coeffs[:, :80] - exp_coeffs = coeffs[:, 80: 144] - tex_coeffs = coeffs[:, 144: 224] - angles = coeffs[:, 224: 227] - gammas = coeffs[:, 227: 254] - translations = coeffs[:, 254:] - return { - 'id': id_coeffs, - 'exp': exp_coeffs, - 'tex': tex_coeffs, - 'angle': angles, - 'gamma': gammas, - 'trans': translations - } - def compute_for_render(self, coeffs): - """ - Return: - face_vertex -- torch.tensor, size (B, N, 3), in camera coordinate - face_color -- torch.tensor, size (B, N, 3), in RGB order - landmark -- torch.tensor, size (B, 68, 2), y direction is opposite to v direction - Parameters: - coeffs -- torch.tensor, size (B, 257) - """ - coef_dict = self.split_coeff(coeffs) - face_shape = self.compute_shape(coef_dict['id'], coef_dict['exp']) - rotation = self.compute_rotation(coef_dict['angle']) - - - face_shape_transformed = self.transform(face_shape, rotation, coef_dict['trans']) - face_vertex = self.to_camera(face_shape_transformed) - - face_proj = self.to_image(face_vertex) - landmark = self.get_landmarks(face_proj) - - face_texture = self.compute_texture(coef_dict['tex']) - face_norm = self.compute_norm(face_shape) - face_norm_roted = face_norm @ rotation - face_color = self.compute_color(face_texture, face_norm_roted, coef_dict['gamma']) - - return face_vertex, face_texture, face_color, landmark - - def compute_for_render_woRotation(self, coeffs): - """ - Return: - face_vertex -- torch.tensor, size (B, N, 3), in camera coordinate - face_color -- torch.tensor, size (B, N, 3), in RGB order - landmark -- torch.tensor, size (B, 68, 2), y direction is opposite to v direction - Parameters: - coeffs -- torch.tensor, size (B, 257) - """ - coef_dict = self.split_coeff(coeffs) - face_shape = self.compute_shape(coef_dict['id'], coef_dict['exp']) - #rotation = self.compute_rotation(coef_dict['angle']) - - - #face_shape_transformed = self.transform(face_shape, rotation, coef_dict['trans']) - face_vertex = self.to_camera(face_shape) - - face_proj = self.to_image(face_vertex) - landmark = self.get_landmarks(face_proj) - - face_texture = self.compute_texture(coef_dict['tex']) - face_norm = self.compute_norm(face_shape) - face_norm_roted = face_norm # @ rotation - face_color = self.compute_color(face_texture, face_norm_roted, coef_dict['gamma']) - - return face_vertex, face_texture, face_color, landmark - - -if __name__ == '__main__': - transferBFM09() \ No newline at end of file diff --git a/spaces/kevinwang676/VoiceChanger/src/face3d/models/bfm.py b/spaces/kevinwang676/VoiceChanger/src/face3d/models/bfm.py deleted file mode 100644 index a75db682f02dd1979d4a7de1d11dd3aa5cdf5279..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VoiceChanger/src/face3d/models/bfm.py +++ /dev/null @@ -1,331 +0,0 @@ -"""This script defines the parametric 3d face model for Deep3DFaceRecon_pytorch -""" - -import numpy as np -import torch -import torch.nn.functional as F -from scipy.io import loadmat -from src.face3d.util.load_mats import transferBFM09 -import os - -def perspective_projection(focal, center): - # return p.T (N, 3) @ (3, 3) - return np.array([ - focal, 0, center, - 0, focal, center, - 0, 0, 1 - ]).reshape([3, 3]).astype(np.float32).transpose() - -class SH: - def __init__(self): - self.a = [np.pi, 2 * np.pi / np.sqrt(3.), 2 * np.pi / np.sqrt(8.)] - self.c = [1/np.sqrt(4 * np.pi), np.sqrt(3.) / np.sqrt(4 * np.pi), 3 * np.sqrt(5.) / np.sqrt(12 * np.pi)] - - - -class ParametricFaceModel: - def __init__(self, - bfm_folder='./BFM', - recenter=True, - camera_distance=10., - init_lit=np.array([ - 0.8, 0, 0, 0, 0, 0, 0, 0, 0 - ]), - focal=1015., - center=112., - is_train=True, - default_name='BFM_model_front.mat'): - - if not os.path.isfile(os.path.join(bfm_folder, default_name)): - transferBFM09(bfm_folder) - - model = loadmat(os.path.join(bfm_folder, default_name)) - # mean face shape. [3*N,1] - self.mean_shape = model['meanshape'].astype(np.float32) - # identity basis. [3*N,80] - self.id_base = model['idBase'].astype(np.float32) - # expression basis. [3*N,64] - self.exp_base = model['exBase'].astype(np.float32) - # mean face texture. [3*N,1] (0-255) - self.mean_tex = model['meantex'].astype(np.float32) - # texture basis. [3*N,80] - self.tex_base = model['texBase'].astype(np.float32) - # face indices for each vertex that lies in. starts from 0. [N,8] - self.point_buf = model['point_buf'].astype(np.int64) - 1 - # vertex indices for each face. starts from 0. [F,3] - self.face_buf = model['tri'].astype(np.int64) - 1 - # vertex indices for 68 landmarks. starts from 0. [68,1] - self.keypoints = np.squeeze(model['keypoints']).astype(np.int64) - 1 - - if is_train: - # vertex indices for small face region to compute photometric error. starts from 0. - self.front_mask = np.squeeze(model['frontmask2_idx']).astype(np.int64) - 1 - # vertex indices for each face from small face region. starts from 0. [f,3] - self.front_face_buf = model['tri_mask2'].astype(np.int64) - 1 - # vertex indices for pre-defined skin region to compute reflectance loss - self.skin_mask = np.squeeze(model['skinmask']) - - if recenter: - mean_shape = self.mean_shape.reshape([-1, 3]) - mean_shape = mean_shape - np.mean(mean_shape, axis=0, keepdims=True) - self.mean_shape = mean_shape.reshape([-1, 1]) - - self.persc_proj = perspective_projection(focal, center) - self.device = 'cpu' - self.camera_distance = camera_distance - self.SH = SH() - self.init_lit = init_lit.reshape([1, 1, -1]).astype(np.float32) - - - def to(self, device): - self.device = device - for key, value in self.__dict__.items(): - if type(value).__module__ == np.__name__: - setattr(self, key, torch.tensor(value).to(device)) - - - def compute_shape(self, id_coeff, exp_coeff): - """ - Return: - face_shape -- torch.tensor, size (B, N, 3) - - Parameters: - id_coeff -- torch.tensor, size (B, 80), identity coeffs - exp_coeff -- torch.tensor, size (B, 64), expression coeffs - """ - batch_size = id_coeff.shape[0] - id_part = torch.einsum('ij,aj->ai', self.id_base, id_coeff) - exp_part = torch.einsum('ij,aj->ai', self.exp_base, exp_coeff) - face_shape = id_part + exp_part + self.mean_shape.reshape([1, -1]) - return face_shape.reshape([batch_size, -1, 3]) - - - def compute_texture(self, tex_coeff, normalize=True): - """ - Return: - face_texture -- torch.tensor, size (B, N, 3), in RGB order, range (0, 1.) - - Parameters: - tex_coeff -- torch.tensor, size (B, 80) - """ - batch_size = tex_coeff.shape[0] - face_texture = torch.einsum('ij,aj->ai', self.tex_base, tex_coeff) + self.mean_tex - if normalize: - face_texture = face_texture / 255. - return face_texture.reshape([batch_size, -1, 3]) - - - def compute_norm(self, face_shape): - """ - Return: - vertex_norm -- torch.tensor, size (B, N, 3) - - Parameters: - face_shape -- torch.tensor, size (B, N, 3) - """ - - v1 = face_shape[:, self.face_buf[:, 0]] - v2 = face_shape[:, self.face_buf[:, 1]] - v3 = face_shape[:, self.face_buf[:, 2]] - e1 = v1 - v2 - e2 = v2 - v3 - face_norm = torch.cross(e1, e2, dim=-1) - face_norm = F.normalize(face_norm, dim=-1, p=2) - face_norm = torch.cat([face_norm, torch.zeros(face_norm.shape[0], 1, 3).to(self.device)], dim=1) - - vertex_norm = torch.sum(face_norm[:, self.point_buf], dim=2) - vertex_norm = F.normalize(vertex_norm, dim=-1, p=2) - return vertex_norm - - - def compute_color(self, face_texture, face_norm, gamma): - """ - Return: - face_color -- torch.tensor, size (B, N, 3), range (0, 1.) - - Parameters: - face_texture -- torch.tensor, size (B, N, 3), from texture model, range (0, 1.) - face_norm -- torch.tensor, size (B, N, 3), rotated face normal - gamma -- torch.tensor, size (B, 27), SH coeffs - """ - batch_size = gamma.shape[0] - v_num = face_texture.shape[1] - a, c = self.SH.a, self.SH.c - gamma = gamma.reshape([batch_size, 3, 9]) - gamma = gamma + self.init_lit - gamma = gamma.permute(0, 2, 1) - Y = torch.cat([ - a[0] * c[0] * torch.ones_like(face_norm[..., :1]).to(self.device), - -a[1] * c[1] * face_norm[..., 1:2], - a[1] * c[1] * face_norm[..., 2:], - -a[1] * c[1] * face_norm[..., :1], - a[2] * c[2] * face_norm[..., :1] * face_norm[..., 1:2], - -a[2] * c[2] * face_norm[..., 1:2] * face_norm[..., 2:], - 0.5 * a[2] * c[2] / np.sqrt(3.) * (3 * face_norm[..., 2:] ** 2 - 1), - -a[2] * c[2] * face_norm[..., :1] * face_norm[..., 2:], - 0.5 * a[2] * c[2] * (face_norm[..., :1] ** 2 - face_norm[..., 1:2] ** 2) - ], dim=-1) - r = Y @ gamma[..., :1] - g = Y @ gamma[..., 1:2] - b = Y @ gamma[..., 2:] - face_color = torch.cat([r, g, b], dim=-1) * face_texture - return face_color - - - def compute_rotation(self, angles): - """ - Return: - rot -- torch.tensor, size (B, 3, 3) pts @ trans_mat - - Parameters: - angles -- torch.tensor, size (B, 3), radian - """ - - batch_size = angles.shape[0] - ones = torch.ones([batch_size, 1]).to(self.device) - zeros = torch.zeros([batch_size, 1]).to(self.device) - x, y, z = angles[:, :1], angles[:, 1:2], angles[:, 2:], - - rot_x = torch.cat([ - ones, zeros, zeros, - zeros, torch.cos(x), -torch.sin(x), - zeros, torch.sin(x), torch.cos(x) - ], dim=1).reshape([batch_size, 3, 3]) - - rot_y = torch.cat([ - torch.cos(y), zeros, torch.sin(y), - zeros, ones, zeros, - -torch.sin(y), zeros, torch.cos(y) - ], dim=1).reshape([batch_size, 3, 3]) - - rot_z = torch.cat([ - torch.cos(z), -torch.sin(z), zeros, - torch.sin(z), torch.cos(z), zeros, - zeros, zeros, ones - ], dim=1).reshape([batch_size, 3, 3]) - - rot = rot_z @ rot_y @ rot_x - return rot.permute(0, 2, 1) - - - def to_camera(self, face_shape): - face_shape[..., -1] = self.camera_distance - face_shape[..., -1] - return face_shape - - def to_image(self, face_shape): - """ - Return: - face_proj -- torch.tensor, size (B, N, 2), y direction is opposite to v direction - - Parameters: - face_shape -- torch.tensor, size (B, N, 3) - """ - # to image_plane - face_proj = face_shape @ self.persc_proj - face_proj = face_proj[..., :2] / face_proj[..., 2:] - - return face_proj - - - def transform(self, face_shape, rot, trans): - """ - Return: - face_shape -- torch.tensor, size (B, N, 3) pts @ rot + trans - - Parameters: - face_shape -- torch.tensor, size (B, N, 3) - rot -- torch.tensor, size (B, 3, 3) - trans -- torch.tensor, size (B, 3) - """ - return face_shape @ rot + trans.unsqueeze(1) - - - def get_landmarks(self, face_proj): - """ - Return: - face_lms -- torch.tensor, size (B, 68, 2) - - Parameters: - face_proj -- torch.tensor, size (B, N, 2) - """ - return face_proj[:, self.keypoints] - - def split_coeff(self, coeffs): - """ - Return: - coeffs_dict -- a dict of torch.tensors - - Parameters: - coeffs -- torch.tensor, size (B, 256) - """ - id_coeffs = coeffs[:, :80] - exp_coeffs = coeffs[:, 80: 144] - tex_coeffs = coeffs[:, 144: 224] - angles = coeffs[:, 224: 227] - gammas = coeffs[:, 227: 254] - translations = coeffs[:, 254:] - return { - 'id': id_coeffs, - 'exp': exp_coeffs, - 'tex': tex_coeffs, - 'angle': angles, - 'gamma': gammas, - 'trans': translations - } - def compute_for_render(self, coeffs): - """ - Return: - face_vertex -- torch.tensor, size (B, N, 3), in camera coordinate - face_color -- torch.tensor, size (B, N, 3), in RGB order - landmark -- torch.tensor, size (B, 68, 2), y direction is opposite to v direction - Parameters: - coeffs -- torch.tensor, size (B, 257) - """ - coef_dict = self.split_coeff(coeffs) - face_shape = self.compute_shape(coef_dict['id'], coef_dict['exp']) - rotation = self.compute_rotation(coef_dict['angle']) - - - face_shape_transformed = self.transform(face_shape, rotation, coef_dict['trans']) - face_vertex = self.to_camera(face_shape_transformed) - - face_proj = self.to_image(face_vertex) - landmark = self.get_landmarks(face_proj) - - face_texture = self.compute_texture(coef_dict['tex']) - face_norm = self.compute_norm(face_shape) - face_norm_roted = face_norm @ rotation - face_color = self.compute_color(face_texture, face_norm_roted, coef_dict['gamma']) - - return face_vertex, face_texture, face_color, landmark - - def compute_for_render_woRotation(self, coeffs): - """ - Return: - face_vertex -- torch.tensor, size (B, N, 3), in camera coordinate - face_color -- torch.tensor, size (B, N, 3), in RGB order - landmark -- torch.tensor, size (B, 68, 2), y direction is opposite to v direction - Parameters: - coeffs -- torch.tensor, size (B, 257) - """ - coef_dict = self.split_coeff(coeffs) - face_shape = self.compute_shape(coef_dict['id'], coef_dict['exp']) - #rotation = self.compute_rotation(coef_dict['angle']) - - - #face_shape_transformed = self.transform(face_shape, rotation, coef_dict['trans']) - face_vertex = self.to_camera(face_shape) - - face_proj = self.to_image(face_vertex) - landmark = self.get_landmarks(face_proj) - - face_texture = self.compute_texture(coef_dict['tex']) - face_norm = self.compute_norm(face_shape) - face_norm_roted = face_norm # @ rotation - face_color = self.compute_color(face_texture, face_norm_roted, coef_dict['gamma']) - - return face_vertex, face_texture, face_color, landmark - - -if __name__ == '__main__': - transferBFM09() \ No newline at end of file diff --git a/spaces/kevinwang676/VoiceChangers/src/face3d/models/arcface_torch/configs/__init__.py b/spaces/kevinwang676/VoiceChangers/src/face3d/models/arcface_torch/configs/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/kidcoconut/spcstm_omdenasaudi_liverhccxai/routes/qa/__init__.py b/spaces/kidcoconut/spcstm_omdenasaudi_liverhccxai/routes/qa/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/koajoel/PolyFormer/fairseq/examples/simultaneous_translation/models/__init__.py b/spaces/koajoel/PolyFormer/fairseq/examples/simultaneous_translation/models/__init__.py deleted file mode 100644 index 257a96593ff7af93c206c066d8db4ad795b2ae36..0000000000000000000000000000000000000000 --- a/spaces/koajoel/PolyFormer/fairseq/examples/simultaneous_translation/models/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import importlib -import os - - -for file in sorted(os.listdir(os.path.dirname(__file__))): - if file.endswith(".py") and not file.startswith("_"): - model_name = file[: file.find(".py")] - importlib.import_module( - "examples.simultaneous_translation.models." + model_name - ) diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/anyio/_core/_typedattr.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/anyio/_core/_typedattr.py deleted file mode 100644 index bf9202eeab91d263f4badade4601efd111b91523..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/anyio/_core/_typedattr.py +++ /dev/null @@ -1,83 +0,0 @@ -from __future__ import annotations - -import sys -from typing import Any, Callable, Mapping, TypeVar, overload - -from ._exceptions import TypedAttributeLookupError - -if sys.version_info >= (3, 8): - from typing import final -else: - from typing_extensions import final - -T_Attr = TypeVar("T_Attr") -T_Default = TypeVar("T_Default") -undefined = object() - - -def typed_attribute() -> Any: - """Return a unique object, used to mark typed attributes.""" - return object() - - -class TypedAttributeSet: - """ - Superclass for typed attribute collections. - - Checks that every public attribute of every subclass has a type annotation. - """ - - def __init_subclass__(cls) -> None: - annotations: dict[str, Any] = getattr(cls, "__annotations__", {}) - for attrname in dir(cls): - if not attrname.startswith("_") and attrname not in annotations: - raise TypeError( - f"Attribute {attrname!r} is missing its type annotation" - ) - - super().__init_subclass__() - - -class TypedAttributeProvider: - """Base class for classes that wish to provide typed extra attributes.""" - - @property - def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]: - """ - A mapping of the extra attributes to callables that return the corresponding values. - - If the provider wraps another provider, the attributes from that wrapper should also be - included in the returned mapping (but the wrapper may override the callables from the - wrapped instance). - - """ - return {} - - @overload - def extra(self, attribute: T_Attr) -> T_Attr: - ... - - @overload - def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: - ... - - @final - def extra(self, attribute: Any, default: object = undefined) -> object: - """ - extra(attribute, default=undefined) - - Return the value of the given typed extra attribute. - - :param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to look for - :param default: the value that should be returned if no value is found for the attribute - :raises ~anyio.TypedAttributeLookupError: if the search failed and no default value was - given - - """ - try: - return self.extra_attributes[attribute]() - except KeyError: - if default is undefined: - raise TypedAttributeLookupError("Attribute not found") from None - else: - return default diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/filelock/__init__.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/filelock/__init__.py deleted file mode 100644 index c7492ba53903e50d84ce5f3b34b193046140b7ec..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/filelock/__init__.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -A platform independent file lock that supports the with-statement. - -.. autodata:: filelock.__version__ - :no-value: - -""" -from __future__ import annotations - -import sys -import warnings -from typing import TYPE_CHECKING - -from ._api import AcquireReturnProxy, BaseFileLock -from ._error import Timeout -from ._soft import SoftFileLock -from ._unix import UnixFileLock, has_fcntl -from ._windows import WindowsFileLock -from .version import version - -#: version of the project as a string -__version__: str = version - - -if sys.platform == "win32": # pragma: win32 cover - _FileLock: type[BaseFileLock] = WindowsFileLock -else: # pragma: win32 no cover - if has_fcntl: - _FileLock: type[BaseFileLock] = UnixFileLock - else: - _FileLock = SoftFileLock - if warnings is not None: - warnings.warn("only soft file lock is available", stacklevel=2) - -if TYPE_CHECKING: - FileLock = SoftFileLock -else: - #: Alias for the lock, which should be used for the current platform. - FileLock = _FileLock - - -__all__ = [ - "__version__", - "FileLock", - "SoftFileLock", - "Timeout", - "UnixFileLock", - "WindowsFileLock", - "BaseFileLock", - "AcquireReturnProxy", -] diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/otTables.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/otTables.py deleted file mode 100644 index 5cabd4b4fcbdc0377660b387dc7ab2d3e4380bc7..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/otTables.py +++ /dev/null @@ -1,2274 +0,0 @@ -# coding: utf-8 -"""fontTools.ttLib.tables.otTables -- A collection of classes representing the various -OpenType subtables. - -Most are constructed upon import from data in otData.py, all are populated with -converter objects from otConverters.py. -""" -import copy -from enum import IntEnum -from functools import reduce -from math import radians -import itertools -from collections import defaultdict, namedtuple -from fontTools.ttLib.tables.otTraverse import dfs_base_table -from fontTools.misc.arrayTools import quantizeRect -from fontTools.misc.roundTools import otRound -from fontTools.misc.transform import Transform, Identity -from fontTools.misc.textTools import bytesjoin, pad, safeEval -from fontTools.pens.boundsPen import ControlBoundsPen -from fontTools.pens.transformPen import TransformPen -from .otBase import ( - BaseTable, - FormatSwitchingBaseTable, - ValueRecord, - CountReference, - getFormatSwitchingBaseTableClass, -) -from fontTools.feaLib.lookupDebugInfo import LookupDebugInfo, LOOKUP_DEBUG_INFO_KEY -import logging -import struct -from typing import TYPE_CHECKING, Iterator, List, Optional, Set - -if TYPE_CHECKING: - from fontTools.ttLib.ttGlyphSet import _TTGlyphSet - - -log = logging.getLogger(__name__) - - -class AATStateTable(object): - def __init__(self): - self.GlyphClasses = {} # GlyphID --> GlyphClass - self.States = [] # List of AATState, indexed by state number - self.PerGlyphLookups = [] # [{GlyphID:GlyphID}, ...] - - -class AATState(object): - def __init__(self): - self.Transitions = {} # GlyphClass --> AATAction - - -class AATAction(object): - _FLAGS = None - - @staticmethod - def compileActions(font, states): - return (None, None) - - def _writeFlagsToXML(self, xmlWriter): - flags = [f for f in self._FLAGS if self.__dict__[f]] - if flags: - xmlWriter.simpletag("Flags", value=",".join(flags)) - xmlWriter.newline() - if self.ReservedFlags != 0: - xmlWriter.simpletag("ReservedFlags", value="0x%04X" % self.ReservedFlags) - xmlWriter.newline() - - def _setFlag(self, flag): - assert flag in self._FLAGS, "unsupported flag %s" % flag - self.__dict__[flag] = True - - -class RearrangementMorphAction(AATAction): - staticSize = 4 - actionHeaderSize = 0 - _FLAGS = ["MarkFirst", "DontAdvance", "MarkLast"] - - _VERBS = { - 0: "no change", - 1: "Ax ⇒ xA", - 2: "xD ⇒ Dx", - 3: "AxD ⇒ DxA", - 4: "ABx ⇒ xAB", - 5: "ABx ⇒ xBA", - 6: "xCD ⇒ CDx", - 7: "xCD ⇒ DCx", - 8: "AxCD ⇒ CDxA", - 9: "AxCD ⇒ DCxA", - 10: "ABxD ⇒ DxAB", - 11: "ABxD ⇒ DxBA", - 12: "ABxCD ⇒ CDxAB", - 13: "ABxCD ⇒ CDxBA", - 14: "ABxCD ⇒ DCxAB", - 15: "ABxCD ⇒ DCxBA", - } - - def __init__(self): - self.NewState = 0 - self.Verb = 0 - self.MarkFirst = False - self.DontAdvance = False - self.MarkLast = False - self.ReservedFlags = 0 - - def compile(self, writer, font, actionIndex): - assert actionIndex is None - writer.writeUShort(self.NewState) - assert self.Verb >= 0 and self.Verb <= 15, self.Verb - flags = self.Verb | self.ReservedFlags - if self.MarkFirst: - flags |= 0x8000 - if self.DontAdvance: - flags |= 0x4000 - if self.MarkLast: - flags |= 0x2000 - writer.writeUShort(flags) - - def decompile(self, reader, font, actionReader): - assert actionReader is None - self.NewState = reader.readUShort() - flags = reader.readUShort() - self.Verb = flags & 0xF - self.MarkFirst = bool(flags & 0x8000) - self.DontAdvance = bool(flags & 0x4000) - self.MarkLast = bool(flags & 0x2000) - self.ReservedFlags = flags & 0x1FF0 - - def toXML(self, xmlWriter, font, attrs, name): - xmlWriter.begintag(name, **attrs) - xmlWriter.newline() - xmlWriter.simpletag("NewState", value=self.NewState) - xmlWriter.newline() - self._writeFlagsToXML(xmlWriter) - xmlWriter.simpletag("Verb", value=self.Verb) - verbComment = self._VERBS.get(self.Verb) - if verbComment is not None: - xmlWriter.comment(verbComment) - xmlWriter.newline() - xmlWriter.endtag(name) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - self.NewState = self.Verb = self.ReservedFlags = 0 - self.MarkFirst = self.DontAdvance = self.MarkLast = False - content = [t for t in content if isinstance(t, tuple)] - for eltName, eltAttrs, eltContent in content: - if eltName == "NewState": - self.NewState = safeEval(eltAttrs["value"]) - elif eltName == "Verb": - self.Verb = safeEval(eltAttrs["value"]) - elif eltName == "ReservedFlags": - self.ReservedFlags = safeEval(eltAttrs["value"]) - elif eltName == "Flags": - for flag in eltAttrs["value"].split(","): - self._setFlag(flag.strip()) - - -class ContextualMorphAction(AATAction): - staticSize = 8 - actionHeaderSize = 0 - _FLAGS = ["SetMark", "DontAdvance"] - - def __init__(self): - self.NewState = 0 - self.SetMark, self.DontAdvance = False, False - self.ReservedFlags = 0 - self.MarkIndex, self.CurrentIndex = 0xFFFF, 0xFFFF - - def compile(self, writer, font, actionIndex): - assert actionIndex is None - writer.writeUShort(self.NewState) - flags = self.ReservedFlags - if self.SetMark: - flags |= 0x8000 - if self.DontAdvance: - flags |= 0x4000 - writer.writeUShort(flags) - writer.writeUShort(self.MarkIndex) - writer.writeUShort(self.CurrentIndex) - - def decompile(self, reader, font, actionReader): - assert actionReader is None - self.NewState = reader.readUShort() - flags = reader.readUShort() - self.SetMark = bool(flags & 0x8000) - self.DontAdvance = bool(flags & 0x4000) - self.ReservedFlags = flags & 0x3FFF - self.MarkIndex = reader.readUShort() - self.CurrentIndex = reader.readUShort() - - def toXML(self, xmlWriter, font, attrs, name): - xmlWriter.begintag(name, **attrs) - xmlWriter.newline() - xmlWriter.simpletag("NewState", value=self.NewState) - xmlWriter.newline() - self._writeFlagsToXML(xmlWriter) - xmlWriter.simpletag("MarkIndex", value=self.MarkIndex) - xmlWriter.newline() - xmlWriter.simpletag("CurrentIndex", value=self.CurrentIndex) - xmlWriter.newline() - xmlWriter.endtag(name) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - self.NewState = self.ReservedFlags = 0 - self.SetMark = self.DontAdvance = False - self.MarkIndex, self.CurrentIndex = 0xFFFF, 0xFFFF - content = [t for t in content if isinstance(t, tuple)] - for eltName, eltAttrs, eltContent in content: - if eltName == "NewState": - self.NewState = safeEval(eltAttrs["value"]) - elif eltName == "Flags": - for flag in eltAttrs["value"].split(","): - self._setFlag(flag.strip()) - elif eltName == "ReservedFlags": - self.ReservedFlags = safeEval(eltAttrs["value"]) - elif eltName == "MarkIndex": - self.MarkIndex = safeEval(eltAttrs["value"]) - elif eltName == "CurrentIndex": - self.CurrentIndex = safeEval(eltAttrs["value"]) - - -class LigAction(object): - def __init__(self): - self.Store = False - # GlyphIndexDelta is a (possibly negative) delta that gets - # added to the glyph ID at the top of the AAT runtime - # execution stack. It is *not* a byte offset into the - # morx table. The result of the addition, which is performed - # at run time by the shaping engine, is an index into - # the ligature components table. See 'morx' specification. - # In the AAT specification, this field is called Offset; - # but its meaning is quite different from other offsets - # in either AAT or OpenType, so we use a different name. - self.GlyphIndexDelta = 0 - - -class LigatureMorphAction(AATAction): - staticSize = 6 - - # 4 bytes for each of {action,ligComponents,ligatures}Offset - actionHeaderSize = 12 - - _FLAGS = ["SetComponent", "DontAdvance"] - - def __init__(self): - self.NewState = 0 - self.SetComponent, self.DontAdvance = False, False - self.ReservedFlags = 0 - self.Actions = [] - - def compile(self, writer, font, actionIndex): - assert actionIndex is not None - writer.writeUShort(self.NewState) - flags = self.ReservedFlags - if self.SetComponent: - flags |= 0x8000 - if self.DontAdvance: - flags |= 0x4000 - if len(self.Actions) > 0: - flags |= 0x2000 - writer.writeUShort(flags) - if len(self.Actions) > 0: - actions = self.compileLigActions() - writer.writeUShort(actionIndex[actions]) - else: - writer.writeUShort(0) - - def decompile(self, reader, font, actionReader): - assert actionReader is not None - self.NewState = reader.readUShort() - flags = reader.readUShort() - self.SetComponent = bool(flags & 0x8000) - self.DontAdvance = bool(flags & 0x4000) - performAction = bool(flags & 0x2000) - # As of 2017-09-12, the 'morx' specification says that - # the reserved bitmask in ligature subtables is 0x3FFF. - # However, the specification also defines a flag 0x2000, - # so the reserved value should actually be 0x1FFF. - # TODO: Report this specification bug to Apple. - self.ReservedFlags = flags & 0x1FFF - actionIndex = reader.readUShort() - if performAction: - self.Actions = self._decompileLigActions(actionReader, actionIndex) - else: - self.Actions = [] - - @staticmethod - def compileActions(font, states): - result, actions, actionIndex = b"", set(), {} - for state in states: - for _glyphClass, trans in state.Transitions.items(): - actions.add(trans.compileLigActions()) - # Sort the compiled actions in decreasing order of - # length, so that the longer sequence come before the - # shorter ones. For each compiled action ABCD, its - # suffixes BCD, CD, and D do not be encoded separately - # (in case they occur); instead, we can just store an - # index that points into the middle of the longer - # sequence. Every compiled AAT ligature sequence is - # terminated with an end-of-sequence flag, which can - # only be set on the last element of the sequence. - # Therefore, it is sufficient to consider just the - # suffixes. - for a in sorted(actions, key=lambda x: (-len(x), x)): - if a not in actionIndex: - for i in range(0, len(a), 4): - suffix = a[i:] - suffixIndex = (len(result) + i) // 4 - actionIndex.setdefault(suffix, suffixIndex) - result += a - result = pad(result, 4) - return (result, actionIndex) - - def compileLigActions(self): - result = [] - for i, action in enumerate(self.Actions): - last = i == len(self.Actions) - 1 - value = action.GlyphIndexDelta & 0x3FFFFFFF - value |= 0x80000000 if last else 0 - value |= 0x40000000 if action.Store else 0 - result.append(struct.pack(">L", value)) - return bytesjoin(result) - - def _decompileLigActions(self, actionReader, actionIndex): - actions = [] - last = False - reader = actionReader.getSubReader(actionReader.pos + actionIndex * 4) - while not last: - value = reader.readULong() - last = bool(value & 0x80000000) - action = LigAction() - actions.append(action) - action.Store = bool(value & 0x40000000) - delta = value & 0x3FFFFFFF - if delta >= 0x20000000: # sign-extend 30-bit value - delta = -0x40000000 + delta - action.GlyphIndexDelta = delta - return actions - - def fromXML(self, name, attrs, content, font): - self.NewState = self.ReservedFlags = 0 - self.SetComponent = self.DontAdvance = False - self.ReservedFlags = 0 - self.Actions = [] - content = [t for t in content if isinstance(t, tuple)] - for eltName, eltAttrs, eltContent in content: - if eltName == "NewState": - self.NewState = safeEval(eltAttrs["value"]) - elif eltName == "Flags": - for flag in eltAttrs["value"].split(","): - self._setFlag(flag.strip()) - elif eltName == "ReservedFlags": - self.ReservedFlags = safeEval(eltAttrs["value"]) - elif eltName == "Action": - action = LigAction() - flags = eltAttrs.get("Flags", "").split(",") - flags = [f.strip() for f in flags] - action.Store = "Store" in flags - action.GlyphIndexDelta = safeEval(eltAttrs["GlyphIndexDelta"]) - self.Actions.append(action) - - def toXML(self, xmlWriter, font, attrs, name): - xmlWriter.begintag(name, **attrs) - xmlWriter.newline() - xmlWriter.simpletag("NewState", value=self.NewState) - xmlWriter.newline() - self._writeFlagsToXML(xmlWriter) - for action in self.Actions: - attribs = [("GlyphIndexDelta", action.GlyphIndexDelta)] - if action.Store: - attribs.append(("Flags", "Store")) - xmlWriter.simpletag("Action", attribs) - xmlWriter.newline() - xmlWriter.endtag(name) - xmlWriter.newline() - - -class InsertionMorphAction(AATAction): - staticSize = 8 - actionHeaderSize = 4 # 4 bytes for actionOffset - _FLAGS = [ - "SetMark", - "DontAdvance", - "CurrentIsKashidaLike", - "MarkedIsKashidaLike", - "CurrentInsertBefore", - "MarkedInsertBefore", - ] - - def __init__(self): - self.NewState = 0 - for flag in self._FLAGS: - setattr(self, flag, False) - self.ReservedFlags = 0 - self.CurrentInsertionAction, self.MarkedInsertionAction = [], [] - - def compile(self, writer, font, actionIndex): - assert actionIndex is not None - writer.writeUShort(self.NewState) - flags = self.ReservedFlags - if self.SetMark: - flags |= 0x8000 - if self.DontAdvance: - flags |= 0x4000 - if self.CurrentIsKashidaLike: - flags |= 0x2000 - if self.MarkedIsKashidaLike: - flags |= 0x1000 - if self.CurrentInsertBefore: - flags |= 0x0800 - if self.MarkedInsertBefore: - flags |= 0x0400 - flags |= len(self.CurrentInsertionAction) << 5 - flags |= len(self.MarkedInsertionAction) - writer.writeUShort(flags) - if len(self.CurrentInsertionAction) > 0: - currentIndex = actionIndex[tuple(self.CurrentInsertionAction)] - else: - currentIndex = 0xFFFF - writer.writeUShort(currentIndex) - if len(self.MarkedInsertionAction) > 0: - markedIndex = actionIndex[tuple(self.MarkedInsertionAction)] - else: - markedIndex = 0xFFFF - writer.writeUShort(markedIndex) - - def decompile(self, reader, font, actionReader): - assert actionReader is not None - self.NewState = reader.readUShort() - flags = reader.readUShort() - self.SetMark = bool(flags & 0x8000) - self.DontAdvance = bool(flags & 0x4000) - self.CurrentIsKashidaLike = bool(flags & 0x2000) - self.MarkedIsKashidaLike = bool(flags & 0x1000) - self.CurrentInsertBefore = bool(flags & 0x0800) - self.MarkedInsertBefore = bool(flags & 0x0400) - self.CurrentInsertionAction = self._decompileInsertionAction( - actionReader, font, index=reader.readUShort(), count=((flags & 0x03E0) >> 5) - ) - self.MarkedInsertionAction = self._decompileInsertionAction( - actionReader, font, index=reader.readUShort(), count=(flags & 0x001F) - ) - - def _decompileInsertionAction(self, actionReader, font, index, count): - if index == 0xFFFF or count == 0: - return [] - reader = actionReader.getSubReader(actionReader.pos + index * 2) - return font.getGlyphNameMany(reader.readUShortArray(count)) - - def toXML(self, xmlWriter, font, attrs, name): - xmlWriter.begintag(name, **attrs) - xmlWriter.newline() - xmlWriter.simpletag("NewState", value=self.NewState) - xmlWriter.newline() - self._writeFlagsToXML(xmlWriter) - for g in self.CurrentInsertionAction: - xmlWriter.simpletag("CurrentInsertionAction", glyph=g) - xmlWriter.newline() - for g in self.MarkedInsertionAction: - xmlWriter.simpletag("MarkedInsertionAction", glyph=g) - xmlWriter.newline() - xmlWriter.endtag(name) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - self.__init__() - content = [t for t in content if isinstance(t, tuple)] - for eltName, eltAttrs, eltContent in content: - if eltName == "NewState": - self.NewState = safeEval(eltAttrs["value"]) - elif eltName == "Flags": - for flag in eltAttrs["value"].split(","): - self._setFlag(flag.strip()) - elif eltName == "CurrentInsertionAction": - self.CurrentInsertionAction.append(eltAttrs["glyph"]) - elif eltName == "MarkedInsertionAction": - self.MarkedInsertionAction.append(eltAttrs["glyph"]) - else: - assert False, eltName - - @staticmethod - def compileActions(font, states): - actions, actionIndex, result = set(), {}, b"" - for state in states: - for _glyphClass, trans in state.Transitions.items(): - if trans.CurrentInsertionAction is not None: - actions.add(tuple(trans.CurrentInsertionAction)) - if trans.MarkedInsertionAction is not None: - actions.add(tuple(trans.MarkedInsertionAction)) - # Sort the compiled actions in decreasing order of - # length, so that the longer sequence come before the - # shorter ones. - for action in sorted(actions, key=lambda x: (-len(x), x)): - # We insert all sub-sequences of the action glyph sequence - # into actionIndex. For example, if one action triggers on - # glyph sequence [A, B, C, D, E] and another action triggers - # on [C, D], we return result=[A, B, C, D, E] (as list of - # encoded glyph IDs), and actionIndex={('A','B','C','D','E'): 0, - # ('C','D'): 2}. - if action in actionIndex: - continue - for start in range(0, len(action)): - startIndex = (len(result) // 2) + start - for limit in range(start, len(action)): - glyphs = action[start : limit + 1] - actionIndex.setdefault(glyphs, startIndex) - for glyph in action: - glyphID = font.getGlyphID(glyph) - result += struct.pack(">H", glyphID) - return result, actionIndex - - -class FeatureParams(BaseTable): - def compile(self, writer, font): - assert ( - featureParamTypes.get(writer["FeatureTag"]) == self.__class__ - ), "Wrong FeatureParams type for feature '%s': %s" % ( - writer["FeatureTag"], - self.__class__.__name__, - ) - BaseTable.compile(self, writer, font) - - def toXML(self, xmlWriter, font, attrs=None, name=None): - BaseTable.toXML(self, xmlWriter, font, attrs, name=self.__class__.__name__) - - -class FeatureParamsSize(FeatureParams): - pass - - -class FeatureParamsStylisticSet(FeatureParams): - pass - - -class FeatureParamsCharacterVariants(FeatureParams): - pass - - -class Coverage(FormatSwitchingBaseTable): - - # manual implementation to get rid of glyphID dependencies - - def populateDefaults(self, propagator=None): - if not hasattr(self, "glyphs"): - self.glyphs = [] - - def postRead(self, rawTable, font): - if self.Format == 1: - self.glyphs = rawTable["GlyphArray"] - elif self.Format == 2: - glyphs = self.glyphs = [] - ranges = rawTable["RangeRecord"] - # Some SIL fonts have coverage entries that don't have sorted - # StartCoverageIndex. If it is so, fixup and warn. We undo - # this when writing font out. - sorted_ranges = sorted(ranges, key=lambda a: a.StartCoverageIndex) - if ranges != sorted_ranges: - log.warning("GSUB/GPOS Coverage is not sorted by glyph ids.") - ranges = sorted_ranges - del sorted_ranges - for r in ranges: - start = r.Start - end = r.End - startID = font.getGlyphID(start) - endID = font.getGlyphID(end) + 1 - glyphs.extend(font.getGlyphNameMany(range(startID, endID))) - else: - self.glyphs = [] - log.warning("Unknown Coverage format: %s", self.Format) - del self.Format # Don't need this anymore - - def preWrite(self, font): - glyphs = getattr(self, "glyphs", None) - if glyphs is None: - glyphs = self.glyphs = [] - format = 1 - rawTable = {"GlyphArray": glyphs} - if glyphs: - # find out whether Format 2 is more compact or not - glyphIDs = font.getGlyphIDMany(glyphs) - brokenOrder = sorted(glyphIDs) != glyphIDs - - last = glyphIDs[0] - ranges = [[last]] - for glyphID in glyphIDs[1:]: - if glyphID != last + 1: - ranges[-1].append(last) - ranges.append([glyphID]) - last = glyphID - ranges[-1].append(last) - - if brokenOrder or len(ranges) * 3 < len(glyphs): # 3 words vs. 1 word - # Format 2 is more compact - index = 0 - for i in range(len(ranges)): - start, end = ranges[i] - r = RangeRecord() - r.StartID = start - r.Start = font.getGlyphName(start) - r.End = font.getGlyphName(end) - r.StartCoverageIndex = index - ranges[i] = r - index = index + end - start + 1 - if brokenOrder: - log.warning("GSUB/GPOS Coverage is not sorted by glyph ids.") - ranges.sort(key=lambda a: a.StartID) - for r in ranges: - del r.StartID - format = 2 - rawTable = {"RangeRecord": ranges} - # else: - # fallthrough; Format 1 is more compact - self.Format = format - return rawTable - - def toXML2(self, xmlWriter, font): - for glyphName in getattr(self, "glyphs", []): - xmlWriter.simpletag("Glyph", value=glyphName) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - glyphs = getattr(self, "glyphs", None) - if glyphs is None: - glyphs = [] - self.glyphs = glyphs - glyphs.append(attrs["value"]) - - -# The special 0xFFFFFFFF delta-set index is used to indicate that there -# is no variation data in the ItemVariationStore for a given variable field -NO_VARIATION_INDEX = 0xFFFFFFFF - - -class DeltaSetIndexMap(getFormatSwitchingBaseTableClass("uint8")): - def populateDefaults(self, propagator=None): - if not hasattr(self, "mapping"): - self.mapping = [] - - def postRead(self, rawTable, font): - assert (rawTable["EntryFormat"] & 0xFFC0) == 0 - self.mapping = rawTable["mapping"] - - @staticmethod - def getEntryFormat(mapping): - ored = 0 - for idx in mapping: - ored |= idx - - inner = ored & 0xFFFF - innerBits = 0 - while inner: - innerBits += 1 - inner >>= 1 - innerBits = max(innerBits, 1) - assert innerBits <= 16 - - ored = (ored >> (16 - innerBits)) | (ored & ((1 << innerBits) - 1)) - if ored <= 0x000000FF: - entrySize = 1 - elif ored <= 0x0000FFFF: - entrySize = 2 - elif ored <= 0x00FFFFFF: - entrySize = 3 - else: - entrySize = 4 - - return ((entrySize - 1) << 4) | (innerBits - 1) - - def preWrite(self, font): - mapping = getattr(self, "mapping", None) - if mapping is None: - mapping = self.mapping = [] - self.Format = 1 if len(mapping) > 0xFFFF else 0 - rawTable = self.__dict__.copy() - rawTable["MappingCount"] = len(mapping) - rawTable["EntryFormat"] = self.getEntryFormat(mapping) - return rawTable - - def toXML2(self, xmlWriter, font): - # Make xml dump less verbose, by omitting no-op entries like: - # - xmlWriter.comment("Omitted values default to 0xFFFF/0xFFFF (no variations)") - xmlWriter.newline() - for i, value in enumerate(getattr(self, "mapping", [])): - attrs = [("index", i)] - if value != NO_VARIATION_INDEX: - attrs.extend( - [ - ("outer", value >> 16), - ("inner", value & 0xFFFF), - ] - ) - xmlWriter.simpletag("Map", attrs) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - mapping = getattr(self, "mapping", None) - if mapping is None: - self.mapping = mapping = [] - index = safeEval(attrs["index"]) - outer = safeEval(attrs.get("outer", "0xFFFF")) - inner = safeEval(attrs.get("inner", "0xFFFF")) - assert inner <= 0xFFFF - mapping.insert(index, (outer << 16) | inner) - - -class VarIdxMap(BaseTable): - def populateDefaults(self, propagator=None): - if not hasattr(self, "mapping"): - self.mapping = {} - - def postRead(self, rawTable, font): - assert (rawTable["EntryFormat"] & 0xFFC0) == 0 - glyphOrder = font.getGlyphOrder() - mapList = rawTable["mapping"] - mapList.extend([mapList[-1]] * (len(glyphOrder) - len(mapList))) - self.mapping = dict(zip(glyphOrder, mapList)) - - def preWrite(self, font): - mapping = getattr(self, "mapping", None) - if mapping is None: - mapping = self.mapping = {} - - glyphOrder = font.getGlyphOrder() - mapping = [mapping[g] for g in glyphOrder] - while len(mapping) > 1 and mapping[-2] == mapping[-1]: - del mapping[-1] - - rawTable = {"mapping": mapping} - rawTable["MappingCount"] = len(mapping) - rawTable["EntryFormat"] = DeltaSetIndexMap.getEntryFormat(mapping) - return rawTable - - def toXML2(self, xmlWriter, font): - for glyph, value in sorted(getattr(self, "mapping", {}).items()): - attrs = ( - ("glyph", glyph), - ("outer", value >> 16), - ("inner", value & 0xFFFF), - ) - xmlWriter.simpletag("Map", attrs) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - mapping = getattr(self, "mapping", None) - if mapping is None: - mapping = {} - self.mapping = mapping - try: - glyph = attrs["glyph"] - except: # https://github.com/fonttools/fonttools/commit/21cbab8ce9ded3356fef3745122da64dcaf314e9#commitcomment-27649836 - glyph = font.getGlyphOrder()[attrs["index"]] - outer = safeEval(attrs["outer"]) - inner = safeEval(attrs["inner"]) - assert inner <= 0xFFFF - mapping[glyph] = (outer << 16) | inner - - -class VarRegionList(BaseTable): - def preWrite(self, font): - # The OT spec says VarStore.VarRegionList.RegionAxisCount should always - # be equal to the fvar.axisCount, and OTS < v8.0.0 enforces this rule - # even when the VarRegionList is empty. We can't treat RegionAxisCount - # like a normal propagated count (== len(Region[i].VarRegionAxis)), - # otherwise it would default to 0 if VarRegionList is empty. - # Thus, we force it to always be equal to fvar.axisCount. - # https://github.com/khaledhosny/ots/pull/192 - fvarTable = font.get("fvar") - if fvarTable: - self.RegionAxisCount = len(fvarTable.axes) - return { - **self.__dict__, - "RegionAxisCount": CountReference(self.__dict__, "RegionAxisCount"), - } - - -class SingleSubst(FormatSwitchingBaseTable): - def populateDefaults(self, propagator=None): - if not hasattr(self, "mapping"): - self.mapping = {} - - def postRead(self, rawTable, font): - mapping = {} - input = _getGlyphsFromCoverageTable(rawTable["Coverage"]) - if self.Format == 1: - delta = rawTable["DeltaGlyphID"] - inputGIDS = font.getGlyphIDMany(input) - outGIDS = [(glyphID + delta) % 65536 for glyphID in inputGIDS] - outNames = font.getGlyphNameMany(outGIDS) - for inp, out in zip(input, outNames): - mapping[inp] = out - elif self.Format == 2: - assert ( - len(input) == rawTable["GlyphCount"] - ), "invalid SingleSubstFormat2 table" - subst = rawTable["Substitute"] - for inp, sub in zip(input, subst): - mapping[inp] = sub - else: - assert 0, "unknown format: %s" % self.Format - self.mapping = mapping - del self.Format # Don't need this anymore - - def preWrite(self, font): - mapping = getattr(self, "mapping", None) - if mapping is None: - mapping = self.mapping = {} - items = list(mapping.items()) - getGlyphID = font.getGlyphID - gidItems = [(getGlyphID(a), getGlyphID(b)) for a, b in items] - sortableItems = sorted(zip(gidItems, items)) - - # figure out format - format = 2 - delta = None - for inID, outID in gidItems: - if delta is None: - delta = (outID - inID) % 65536 - - if (inID + delta) % 65536 != outID: - break - else: - if delta is None: - # the mapping is empty, better use format 2 - format = 2 - else: - format = 1 - - rawTable = {} - self.Format = format - cov = Coverage() - input = [item[1][0] for item in sortableItems] - subst = [item[1][1] for item in sortableItems] - cov.glyphs = input - rawTable["Coverage"] = cov - if format == 1: - assert delta is not None - rawTable["DeltaGlyphID"] = delta - else: - rawTable["Substitute"] = subst - return rawTable - - def toXML2(self, xmlWriter, font): - items = sorted(self.mapping.items()) - for inGlyph, outGlyph in items: - xmlWriter.simpletag("Substitution", [("in", inGlyph), ("out", outGlyph)]) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - mapping = getattr(self, "mapping", None) - if mapping is None: - mapping = {} - self.mapping = mapping - mapping[attrs["in"]] = attrs["out"] - - -class MultipleSubst(FormatSwitchingBaseTable): - def populateDefaults(self, propagator=None): - if not hasattr(self, "mapping"): - self.mapping = {} - - def postRead(self, rawTable, font): - mapping = {} - if self.Format == 1: - glyphs = _getGlyphsFromCoverageTable(rawTable["Coverage"]) - subst = [s.Substitute for s in rawTable["Sequence"]] - mapping = dict(zip(glyphs, subst)) - else: - assert 0, "unknown format: %s" % self.Format - self.mapping = mapping - del self.Format # Don't need this anymore - - def preWrite(self, font): - mapping = getattr(self, "mapping", None) - if mapping is None: - mapping = self.mapping = {} - cov = Coverage() - cov.glyphs = sorted(list(mapping.keys()), key=font.getGlyphID) - self.Format = 1 - rawTable = { - "Coverage": cov, - "Sequence": [self.makeSequence_(mapping[glyph]) for glyph in cov.glyphs], - } - return rawTable - - def toXML2(self, xmlWriter, font): - items = sorted(self.mapping.items()) - for inGlyph, outGlyphs in items: - out = ",".join(outGlyphs) - xmlWriter.simpletag("Substitution", [("in", inGlyph), ("out", out)]) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - mapping = getattr(self, "mapping", None) - if mapping is None: - mapping = {} - self.mapping = mapping - - # TTX v3.0 and earlier. - if name == "Coverage": - self.old_coverage_ = [] - for element in content: - if not isinstance(element, tuple): - continue - element_name, element_attrs, _ = element - if element_name == "Glyph": - self.old_coverage_.append(element_attrs["value"]) - return - if name == "Sequence": - index = int(attrs.get("index", len(mapping))) - glyph = self.old_coverage_[index] - glyph_mapping = mapping[glyph] = [] - for element in content: - if not isinstance(element, tuple): - continue - element_name, element_attrs, _ = element - if element_name == "Substitute": - glyph_mapping.append(element_attrs["value"]) - return - - # TTX v3.1 and later. - outGlyphs = attrs["out"].split(",") if attrs["out"] else [] - mapping[attrs["in"]] = [g.strip() for g in outGlyphs] - - @staticmethod - def makeSequence_(g): - seq = Sequence() - seq.Substitute = g - return seq - - -class ClassDef(FormatSwitchingBaseTable): - def populateDefaults(self, propagator=None): - if not hasattr(self, "classDefs"): - self.classDefs = {} - - def postRead(self, rawTable, font): - classDefs = {} - - if self.Format == 1: - start = rawTable["StartGlyph"] - classList = rawTable["ClassValueArray"] - startID = font.getGlyphID(start) - endID = startID + len(classList) - glyphNames = font.getGlyphNameMany(range(startID, endID)) - for glyphName, cls in zip(glyphNames, classList): - if cls: - classDefs[glyphName] = cls - - elif self.Format == 2: - records = rawTable["ClassRangeRecord"] - for rec in records: - cls = rec.Class - if not cls: - continue - start = rec.Start - end = rec.End - startID = font.getGlyphID(start) - endID = font.getGlyphID(end) + 1 - glyphNames = font.getGlyphNameMany(range(startID, endID)) - for glyphName in glyphNames: - classDefs[glyphName] = cls - else: - log.warning("Unknown ClassDef format: %s", self.Format) - self.classDefs = classDefs - del self.Format # Don't need this anymore - - def _getClassRanges(self, font): - classDefs = getattr(self, "classDefs", None) - if classDefs is None: - self.classDefs = {} - return - getGlyphID = font.getGlyphID - items = [] - for glyphName, cls in classDefs.items(): - if not cls: - continue - items.append((getGlyphID(glyphName), glyphName, cls)) - if items: - items.sort() - last, lastName, lastCls = items[0] - ranges = [[lastCls, last, lastName]] - for glyphID, glyphName, cls in items[1:]: - if glyphID != last + 1 or cls != lastCls: - ranges[-1].extend([last, lastName]) - ranges.append([cls, glyphID, glyphName]) - last = glyphID - lastName = glyphName - lastCls = cls - ranges[-1].extend([last, lastName]) - return ranges - - def preWrite(self, font): - format = 2 - rawTable = {"ClassRangeRecord": []} - ranges = self._getClassRanges(font) - if ranges: - startGlyph = ranges[0][1] - endGlyph = ranges[-1][3] - glyphCount = endGlyph - startGlyph + 1 - if len(ranges) * 3 < glyphCount + 1: - # Format 2 is more compact - for i in range(len(ranges)): - cls, start, startName, end, endName = ranges[i] - rec = ClassRangeRecord() - rec.Start = startName - rec.End = endName - rec.Class = cls - ranges[i] = rec - format = 2 - rawTable = {"ClassRangeRecord": ranges} - else: - # Format 1 is more compact - startGlyphName = ranges[0][2] - classes = [0] * glyphCount - for cls, start, startName, end, endName in ranges: - for g in range(start - startGlyph, end - startGlyph + 1): - classes[g] = cls - format = 1 - rawTable = {"StartGlyph": startGlyphName, "ClassValueArray": classes} - self.Format = format - return rawTable - - def toXML2(self, xmlWriter, font): - items = sorted(self.classDefs.items()) - for glyphName, cls in items: - xmlWriter.simpletag("ClassDef", [("glyph", glyphName), ("class", cls)]) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - classDefs = getattr(self, "classDefs", None) - if classDefs is None: - classDefs = {} - self.classDefs = classDefs - classDefs[attrs["glyph"]] = int(attrs["class"]) - - -class AlternateSubst(FormatSwitchingBaseTable): - def populateDefaults(self, propagator=None): - if not hasattr(self, "alternates"): - self.alternates = {} - - def postRead(self, rawTable, font): - alternates = {} - if self.Format == 1: - input = _getGlyphsFromCoverageTable(rawTable["Coverage"]) - alts = rawTable["AlternateSet"] - assert len(input) == len(alts) - for inp, alt in zip(input, alts): - alternates[inp] = alt.Alternate - else: - assert 0, "unknown format: %s" % self.Format - self.alternates = alternates - del self.Format # Don't need this anymore - - def preWrite(self, font): - self.Format = 1 - alternates = getattr(self, "alternates", None) - if alternates is None: - alternates = self.alternates = {} - items = list(alternates.items()) - for i in range(len(items)): - glyphName, set = items[i] - items[i] = font.getGlyphID(glyphName), glyphName, set - items.sort() - cov = Coverage() - cov.glyphs = [item[1] for item in items] - alternates = [] - setList = [item[-1] for item in items] - for set in setList: - alts = AlternateSet() - alts.Alternate = set - alternates.append(alts) - # a special case to deal with the fact that several hundred Adobe Japan1-5 - # CJK fonts will overflow an offset if the coverage table isn't pushed to the end. - # Also useful in that when splitting a sub-table because of an offset overflow - # I don't need to calculate the change in the subtable offset due to the change in the coverage table size. - # Allows packing more rules in subtable. - self.sortCoverageLast = 1 - return {"Coverage": cov, "AlternateSet": alternates} - - def toXML2(self, xmlWriter, font): - items = sorted(self.alternates.items()) - for glyphName, alternates in items: - xmlWriter.begintag("AlternateSet", glyph=glyphName) - xmlWriter.newline() - for alt in alternates: - xmlWriter.simpletag("Alternate", glyph=alt) - xmlWriter.newline() - xmlWriter.endtag("AlternateSet") - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - alternates = getattr(self, "alternates", None) - if alternates is None: - alternates = {} - self.alternates = alternates - glyphName = attrs["glyph"] - set = [] - alternates[glyphName] = set - for element in content: - if not isinstance(element, tuple): - continue - name, attrs, content = element - set.append(attrs["glyph"]) - - -class LigatureSubst(FormatSwitchingBaseTable): - def populateDefaults(self, propagator=None): - if not hasattr(self, "ligatures"): - self.ligatures = {} - - def postRead(self, rawTable, font): - ligatures = {} - if self.Format == 1: - input = _getGlyphsFromCoverageTable(rawTable["Coverage"]) - ligSets = rawTable["LigatureSet"] - assert len(input) == len(ligSets) - for i in range(len(input)): - ligatures[input[i]] = ligSets[i].Ligature - else: - assert 0, "unknown format: %s" % self.Format - self.ligatures = ligatures - del self.Format # Don't need this anymore - - def preWrite(self, font): - self.Format = 1 - ligatures = getattr(self, "ligatures", None) - if ligatures is None: - ligatures = self.ligatures = {} - - if ligatures and isinstance(next(iter(ligatures)), tuple): - # New high-level API in v3.1 and later. Note that we just support compiling this - # for now. We don't load to this API, and don't do XML with it. - - # ligatures is map from components-sequence to lig-glyph - newLigatures = dict() - for comps, lig in sorted( - ligatures.items(), key=lambda item: (-len(item[0]), item[0]) - ): - ligature = Ligature() - ligature.Component = comps[1:] - ligature.CompCount = len(comps) - ligature.LigGlyph = lig - newLigatures.setdefault(comps[0], []).append(ligature) - ligatures = newLigatures - - items = list(ligatures.items()) - for i in range(len(items)): - glyphName, set = items[i] - items[i] = font.getGlyphID(glyphName), glyphName, set - items.sort() - cov = Coverage() - cov.glyphs = [item[1] for item in items] - - ligSets = [] - setList = [item[-1] for item in items] - for set in setList: - ligSet = LigatureSet() - ligs = ligSet.Ligature = [] - for lig in set: - ligs.append(lig) - ligSets.append(ligSet) - # Useful in that when splitting a sub-table because of an offset overflow - # I don't need to calculate the change in subtabl offset due to the coverage table size. - # Allows packing more rules in subtable. - self.sortCoverageLast = 1 - return {"Coverage": cov, "LigatureSet": ligSets} - - def toXML2(self, xmlWriter, font): - items = sorted(self.ligatures.items()) - for glyphName, ligSets in items: - xmlWriter.begintag("LigatureSet", glyph=glyphName) - xmlWriter.newline() - for lig in ligSets: - xmlWriter.simpletag( - "Ligature", glyph=lig.LigGlyph, components=",".join(lig.Component) - ) - xmlWriter.newline() - xmlWriter.endtag("LigatureSet") - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - ligatures = getattr(self, "ligatures", None) - if ligatures is None: - ligatures = {} - self.ligatures = ligatures - glyphName = attrs["glyph"] - ligs = [] - ligatures[glyphName] = ligs - for element in content: - if not isinstance(element, tuple): - continue - name, attrs, content = element - lig = Ligature() - lig.LigGlyph = attrs["glyph"] - components = attrs["components"] - lig.Component = components.split(",") if components else [] - lig.CompCount = len(lig.Component) - ligs.append(lig) - - -class COLR(BaseTable): - def decompile(self, reader, font): - # COLRv0 is exceptional in that LayerRecordCount appears *after* the - # LayerRecordArray it counts, but the parser logic expects Count fields - # to always precede the arrays. Here we work around this by parsing the - # LayerRecordCount before the rest of the table, and storing it in - # the reader's local state. - subReader = reader.getSubReader(offset=0) - for conv in self.getConverters(): - if conv.name != "LayerRecordCount": - subReader.advance(conv.staticSize) - continue - reader[conv.name] = conv.read(subReader, font, tableDict={}) - break - else: - raise AssertionError("LayerRecordCount converter not found") - return BaseTable.decompile(self, reader, font) - - def preWrite(self, font): - # The writer similarly assumes Count values precede the things counted, - # thus here we pre-initialize a CountReference; the actual count value - # will be set to the lenght of the array by the time this is assembled. - self.LayerRecordCount = None - return { - **self.__dict__, - "LayerRecordCount": CountReference(self.__dict__, "LayerRecordCount"), - } - - def computeClipBoxes(self, glyphSet: "_TTGlyphSet", quantization: int = 1): - if self.Version == 0: - return - - clips = {} - for rec in self.BaseGlyphList.BaseGlyphPaintRecord: - try: - clipBox = rec.Paint.computeClipBox(self, glyphSet, quantization) - except Exception as e: - from fontTools.ttLib import TTLibError - - raise TTLibError( - f"Failed to compute COLR ClipBox for {rec.BaseGlyph!r}" - ) from e - - if clipBox is not None: - clips[rec.BaseGlyph] = clipBox - - hasClipList = hasattr(self, "ClipList") and self.ClipList is not None - if not clips: - if hasClipList: - self.ClipList = None - else: - if not hasClipList: - self.ClipList = ClipList() - self.ClipList.Format = 1 - self.ClipList.clips = clips - - -class LookupList(BaseTable): - @property - def table(self): - for l in self.Lookup: - for st in l.SubTable: - if type(st).__name__.endswith("Subst"): - return "GSUB" - if type(st).__name__.endswith("Pos"): - return "GPOS" - raise ValueError - - def toXML2(self, xmlWriter, font): - if ( - not font - or "Debg" not in font - or LOOKUP_DEBUG_INFO_KEY not in font["Debg"].data - ): - return super().toXML2(xmlWriter, font) - debugData = font["Debg"].data[LOOKUP_DEBUG_INFO_KEY][self.table] - for conv in self.getConverters(): - if conv.repeat: - value = getattr(self, conv.name, []) - for lookupIndex, item in enumerate(value): - if str(lookupIndex) in debugData: - info = LookupDebugInfo(*debugData[str(lookupIndex)]) - tag = info.location - if info.name: - tag = f"{info.name}: {tag}" - if info.feature: - script, language, feature = info.feature - tag = f"{tag} in {feature} ({script}/{language})" - xmlWriter.comment(tag) - xmlWriter.newline() - - conv.xmlWrite( - xmlWriter, font, item, conv.name, [("index", lookupIndex)] - ) - else: - if conv.aux and not eval(conv.aux, None, vars(self)): - continue - value = getattr( - self, conv.name, None - ) # TODO Handle defaults instead of defaulting to None! - conv.xmlWrite(xmlWriter, font, value, conv.name, []) - - -class BaseGlyphRecordArray(BaseTable): - def preWrite(self, font): - self.BaseGlyphRecord = sorted( - self.BaseGlyphRecord, key=lambda rec: font.getGlyphID(rec.BaseGlyph) - ) - return self.__dict__.copy() - - -class BaseGlyphList(BaseTable): - def preWrite(self, font): - self.BaseGlyphPaintRecord = sorted( - self.BaseGlyphPaintRecord, key=lambda rec: font.getGlyphID(rec.BaseGlyph) - ) - return self.__dict__.copy() - - -class ClipBoxFormat(IntEnum): - Static = 1 - Variable = 2 - - def is_variable(self): - return self is self.Variable - - def as_variable(self): - return self.Variable - - -class ClipBox(getFormatSwitchingBaseTableClass("uint8")): - formatEnum = ClipBoxFormat - - def as_tuple(self): - return tuple(getattr(self, conv.name) for conv in self.getConverters()) - - def __repr__(self): - return f"{self.__class__.__name__}{self.as_tuple()}" - - -class ClipList(getFormatSwitchingBaseTableClass("uint8")): - def populateDefaults(self, propagator=None): - if not hasattr(self, "clips"): - self.clips = {} - - def postRead(self, rawTable, font): - clips = {} - glyphOrder = font.getGlyphOrder() - for i, rec in enumerate(rawTable["ClipRecord"]): - if rec.StartGlyphID > rec.EndGlyphID: - log.warning( - "invalid ClipRecord[%i].StartGlyphID (%i) > " - "EndGlyphID (%i); skipped", - i, - rec.StartGlyphID, - rec.EndGlyphID, - ) - continue - redefinedGlyphs = [] - missingGlyphs = [] - for glyphID in range(rec.StartGlyphID, rec.EndGlyphID + 1): - try: - glyph = glyphOrder[glyphID] - except IndexError: - missingGlyphs.append(glyphID) - continue - if glyph not in clips: - clips[glyph] = copy.copy(rec.ClipBox) - else: - redefinedGlyphs.append(glyphID) - if redefinedGlyphs: - log.warning( - "ClipRecord[%i] overlaps previous records; " - "ignoring redefined clip boxes for the " - "following glyph ID range: [%i-%i]", - i, - min(redefinedGlyphs), - max(redefinedGlyphs), - ) - if missingGlyphs: - log.warning( - "ClipRecord[%i] range references missing " "glyph IDs: [%i-%i]", - i, - min(missingGlyphs), - max(missingGlyphs), - ) - self.clips = clips - - def groups(self): - glyphsByClip = defaultdict(list) - uniqueClips = {} - for glyphName, clipBox in self.clips.items(): - key = clipBox.as_tuple() - glyphsByClip[key].append(glyphName) - if key not in uniqueClips: - uniqueClips[key] = clipBox - return { - frozenset(glyphs): uniqueClips[key] for key, glyphs in glyphsByClip.items() - } - - def preWrite(self, font): - if not hasattr(self, "clips"): - self.clips = {} - clipBoxRanges = {} - glyphMap = font.getReverseGlyphMap() - for glyphs, clipBox in self.groups().items(): - glyphIDs = sorted( - glyphMap[glyphName] for glyphName in glyphs if glyphName in glyphMap - ) - if not glyphIDs: - continue - last = glyphIDs[0] - ranges = [[last]] - for glyphID in glyphIDs[1:]: - if glyphID != last + 1: - ranges[-1].append(last) - ranges.append([glyphID]) - last = glyphID - ranges[-1].append(last) - for start, end in ranges: - assert (start, end) not in clipBoxRanges - clipBoxRanges[(start, end)] = clipBox - - clipRecords = [] - for (start, end), clipBox in sorted(clipBoxRanges.items()): - record = ClipRecord() - record.StartGlyphID = start - record.EndGlyphID = end - record.ClipBox = clipBox - clipRecords.append(record) - rawTable = { - "ClipCount": len(clipRecords), - "ClipRecord": clipRecords, - } - return rawTable - - def toXML(self, xmlWriter, font, attrs=None, name=None): - tableName = name if name else self.__class__.__name__ - if attrs is None: - attrs = [] - if hasattr(self, "Format"): - attrs.append(("Format", self.Format)) - xmlWriter.begintag(tableName, attrs) - xmlWriter.newline() - # sort clips alphabetically to ensure deterministic XML dump - for glyphs, clipBox in sorted( - self.groups().items(), key=lambda item: min(item[0]) - ): - xmlWriter.begintag("Clip") - xmlWriter.newline() - for glyphName in sorted(glyphs): - xmlWriter.simpletag("Glyph", value=glyphName) - xmlWriter.newline() - xmlWriter.begintag("ClipBox", [("Format", clipBox.Format)]) - xmlWriter.newline() - clipBox.toXML2(xmlWriter, font) - xmlWriter.endtag("ClipBox") - xmlWriter.newline() - xmlWriter.endtag("Clip") - xmlWriter.newline() - xmlWriter.endtag(tableName) - xmlWriter.newline() - - def fromXML(self, name, attrs, content, font): - clips = getattr(self, "clips", None) - if clips is None: - self.clips = clips = {} - assert name == "Clip" - glyphs = [] - clipBox = None - for elem in content: - if not isinstance(elem, tuple): - continue - name, attrs, content = elem - if name == "Glyph": - glyphs.append(attrs["value"]) - elif name == "ClipBox": - clipBox = ClipBox() - clipBox.Format = safeEval(attrs["Format"]) - for elem in content: - if not isinstance(elem, tuple): - continue - name, attrs, content = elem - clipBox.fromXML(name, attrs, content, font) - if clipBox: - for glyphName in glyphs: - clips[glyphName] = clipBox - - -class ExtendMode(IntEnum): - PAD = 0 - REPEAT = 1 - REFLECT = 2 - - -# Porter-Duff modes for COLRv1 PaintComposite: -# https://github.com/googlefonts/colr-gradients-spec/tree/off_sub_1#compositemode-enumeration -class CompositeMode(IntEnum): - CLEAR = 0 - SRC = 1 - DEST = 2 - SRC_OVER = 3 - DEST_OVER = 4 - SRC_IN = 5 - DEST_IN = 6 - SRC_OUT = 7 - DEST_OUT = 8 - SRC_ATOP = 9 - DEST_ATOP = 10 - XOR = 11 - PLUS = 12 - SCREEN = 13 - OVERLAY = 14 - DARKEN = 15 - LIGHTEN = 16 - COLOR_DODGE = 17 - COLOR_BURN = 18 - HARD_LIGHT = 19 - SOFT_LIGHT = 20 - DIFFERENCE = 21 - EXCLUSION = 22 - MULTIPLY = 23 - HSL_HUE = 24 - HSL_SATURATION = 25 - HSL_COLOR = 26 - HSL_LUMINOSITY = 27 - - -class PaintFormat(IntEnum): - PaintColrLayers = 1 - PaintSolid = 2 - PaintVarSolid = (3,) - PaintLinearGradient = 4 - PaintVarLinearGradient = 5 - PaintRadialGradient = 6 - PaintVarRadialGradient = 7 - PaintSweepGradient = 8 - PaintVarSweepGradient = 9 - PaintGlyph = 10 - PaintColrGlyph = 11 - PaintTransform = 12 - PaintVarTransform = 13 - PaintTranslate = 14 - PaintVarTranslate = 15 - PaintScale = 16 - PaintVarScale = 17 - PaintScaleAroundCenter = 18 - PaintVarScaleAroundCenter = 19 - PaintScaleUniform = 20 - PaintVarScaleUniform = 21 - PaintScaleUniformAroundCenter = 22 - PaintVarScaleUniformAroundCenter = 23 - PaintRotate = 24 - PaintVarRotate = 25 - PaintRotateAroundCenter = 26 - PaintVarRotateAroundCenter = 27 - PaintSkew = 28 - PaintVarSkew = 29 - PaintSkewAroundCenter = 30 - PaintVarSkewAroundCenter = 31 - PaintComposite = 32 - - def is_variable(self): - return self.name.startswith("PaintVar") - - def as_variable(self): - if self.is_variable(): - return self - try: - return PaintFormat.__members__[f"PaintVar{self.name[5:]}"] - except KeyError: - return None - - -class Paint(getFormatSwitchingBaseTableClass("uint8")): - formatEnum = PaintFormat - - def getFormatName(self): - try: - return self.formatEnum(self.Format).name - except ValueError: - raise NotImplementedError(f"Unknown Paint format: {self.Format}") - - def toXML(self, xmlWriter, font, attrs=None, name=None): - tableName = name if name else self.__class__.__name__ - if attrs is None: - attrs = [] - attrs.append(("Format", self.Format)) - xmlWriter.begintag(tableName, attrs) - xmlWriter.comment(self.getFormatName()) - xmlWriter.newline() - self.toXML2(xmlWriter, font) - xmlWriter.endtag(tableName) - xmlWriter.newline() - - def iterPaintSubTables(self, colr: COLR) -> Iterator[BaseTable.SubTableEntry]: - if self.Format == PaintFormat.PaintColrLayers: - # https://github.com/fonttools/fonttools/issues/2438: don't die when no LayerList exists - layers = [] - if colr.LayerList is not None: - layers = colr.LayerList.Paint - yield from ( - BaseTable.SubTableEntry(name="Layers", value=v, index=i) - for i, v in enumerate( - layers[self.FirstLayerIndex : self.FirstLayerIndex + self.NumLayers] - ) - ) - return - - if self.Format == PaintFormat.PaintColrGlyph: - for record in colr.BaseGlyphList.BaseGlyphPaintRecord: - if record.BaseGlyph == self.Glyph: - yield BaseTable.SubTableEntry(name="BaseGlyph", value=record.Paint) - return - else: - raise KeyError(f"{self.Glyph!r} not in colr.BaseGlyphList") - - for conv in self.getConverters(): - if conv.tableClass is not None and issubclass(conv.tableClass, type(self)): - value = getattr(self, conv.name) - yield BaseTable.SubTableEntry(name=conv.name, value=value) - - def getChildren(self, colr) -> List["Paint"]: - # this is kept for backward compatibility (e.g. it's used by the subsetter) - return [p.value for p in self.iterPaintSubTables(colr)] - - def traverse(self, colr: COLR, callback): - """Depth-first traversal of graph rooted at self, callback on each node.""" - if not callable(callback): - raise TypeError("callback must be callable") - - for path in dfs_base_table( - self, iter_subtables_fn=lambda paint: paint.iterPaintSubTables(colr) - ): - paint = path[-1].value - callback(paint) - - def getTransform(self) -> Transform: - if self.Format == PaintFormat.PaintTransform: - t = self.Transform - return Transform(t.xx, t.yx, t.xy, t.yy, t.dx, t.dy) - elif self.Format == PaintFormat.PaintTranslate: - return Identity.translate(self.dx, self.dy) - elif self.Format == PaintFormat.PaintScale: - return Identity.scale(self.scaleX, self.scaleY) - elif self.Format == PaintFormat.PaintScaleAroundCenter: - return ( - Identity.translate(self.centerX, self.centerY) - .scale(self.scaleX, self.scaleY) - .translate(-self.centerX, -self.centerY) - ) - elif self.Format == PaintFormat.PaintScaleUniform: - return Identity.scale(self.scale) - elif self.Format == PaintFormat.PaintScaleUniformAroundCenter: - return ( - Identity.translate(self.centerX, self.centerY) - .scale(self.scale) - .translate(-self.centerX, -self.centerY) - ) - elif self.Format == PaintFormat.PaintRotate: - return Identity.rotate(radians(self.angle)) - elif self.Format == PaintFormat.PaintRotateAroundCenter: - return ( - Identity.translate(self.centerX, self.centerY) - .rotate(radians(self.angle)) - .translate(-self.centerX, -self.centerY) - ) - elif self.Format == PaintFormat.PaintSkew: - return Identity.skew(radians(-self.xSkewAngle), radians(self.ySkewAngle)) - elif self.Format == PaintFormat.PaintSkewAroundCenter: - return ( - Identity.translate(self.centerX, self.centerY) - .skew(radians(-self.xSkewAngle), radians(self.ySkewAngle)) - .translate(-self.centerX, -self.centerY) - ) - if PaintFormat(self.Format).is_variable(): - raise NotImplementedError(f"Variable Paints not supported: {self.Format}") - - return Identity - - def computeClipBox( - self, colr: COLR, glyphSet: "_TTGlyphSet", quantization: int = 1 - ) -> Optional[ClipBox]: - pen = ControlBoundsPen(glyphSet) - for path in dfs_base_table( - self, iter_subtables_fn=lambda paint: paint.iterPaintSubTables(colr) - ): - paint = path[-1].value - if paint.Format == PaintFormat.PaintGlyph: - transformation = reduce( - Transform.transform, - (st.value.getTransform() for st in path), - Identity, - ) - glyphSet[paint.Glyph].draw(TransformPen(pen, transformation)) - - if pen.bounds is None: - return None - - cb = ClipBox() - cb.Format = int(ClipBoxFormat.Static) - cb.xMin, cb.yMin, cb.xMax, cb.yMax = quantizeRect(pen.bounds, quantization) - return cb - - -# For each subtable format there is a class. However, we don't really distinguish -# between "field name" and "format name": often these are the same. Yet there's -# a whole bunch of fields with different names. The following dict is a mapping -# from "format name" to "field name". _buildClasses() uses this to create a -# subclass for each alternate field name. -# -_equivalents = { - "MarkArray": ("Mark1Array",), - "LangSys": ("DefaultLangSys",), - "Coverage": ( - "MarkCoverage", - "BaseCoverage", - "LigatureCoverage", - "Mark1Coverage", - "Mark2Coverage", - "BacktrackCoverage", - "InputCoverage", - "LookAheadCoverage", - "VertGlyphCoverage", - "HorizGlyphCoverage", - "TopAccentCoverage", - "ExtendedShapeCoverage", - "MathKernCoverage", - ), - "ClassDef": ( - "ClassDef1", - "ClassDef2", - "BacktrackClassDef", - "InputClassDef", - "LookAheadClassDef", - "GlyphClassDef", - "MarkAttachClassDef", - ), - "Anchor": ( - "EntryAnchor", - "ExitAnchor", - "BaseAnchor", - "LigatureAnchor", - "Mark2Anchor", - "MarkAnchor", - ), - "Device": ( - "XPlaDevice", - "YPlaDevice", - "XAdvDevice", - "YAdvDevice", - "XDeviceTable", - "YDeviceTable", - "DeviceTable", - ), - "Axis": ( - "HorizAxis", - "VertAxis", - ), - "MinMax": ("DefaultMinMax",), - "BaseCoord": ( - "MinCoord", - "MaxCoord", - ), - "JstfLangSys": ("DefJstfLangSys",), - "JstfGSUBModList": ( - "ShrinkageEnableGSUB", - "ShrinkageDisableGSUB", - "ExtensionEnableGSUB", - "ExtensionDisableGSUB", - ), - "JstfGPOSModList": ( - "ShrinkageEnableGPOS", - "ShrinkageDisableGPOS", - "ExtensionEnableGPOS", - "ExtensionDisableGPOS", - ), - "JstfMax": ( - "ShrinkageJstfMax", - "ExtensionJstfMax", - ), - "MathKern": ( - "TopRightMathKern", - "TopLeftMathKern", - "BottomRightMathKern", - "BottomLeftMathKern", - ), - "MathGlyphConstruction": ("VertGlyphConstruction", "HorizGlyphConstruction"), -} - -# -# OverFlow logic, to automatically create ExtensionLookups -# XXX This should probably move to otBase.py -# - - -def fixLookupOverFlows(ttf, overflowRecord): - """Either the offset from the LookupList to a lookup overflowed, or - an offset from a lookup to a subtable overflowed. - The table layout is: - GPSO/GUSB - Script List - Feature List - LookUpList - Lookup[0] and contents - SubTable offset list - SubTable[0] and contents - ... - SubTable[n] and contents - ... - Lookup[n] and contents - SubTable offset list - SubTable[0] and contents - ... - SubTable[n] and contents - If the offset to a lookup overflowed (SubTableIndex is None) - we must promote the *previous* lookup to an Extension type. - If the offset from a lookup to subtable overflowed, then we must promote it - to an Extension Lookup type. - """ - ok = 0 - lookupIndex = overflowRecord.LookupListIndex - if overflowRecord.SubTableIndex is None: - lookupIndex = lookupIndex - 1 - if lookupIndex < 0: - return ok - if overflowRecord.tableType == "GSUB": - extType = 7 - elif overflowRecord.tableType == "GPOS": - extType = 9 - - lookups = ttf[overflowRecord.tableType].table.LookupList.Lookup - lookup = lookups[lookupIndex] - # If the previous lookup is an extType, look further back. Very unlikely, but possible. - while lookup.SubTable[0].__class__.LookupType == extType: - lookupIndex = lookupIndex - 1 - if lookupIndex < 0: - return ok - lookup = lookups[lookupIndex] - - for lookupIndex in range(lookupIndex, len(lookups)): - lookup = lookups[lookupIndex] - if lookup.LookupType != extType: - lookup.LookupType = extType - for si in range(len(lookup.SubTable)): - subTable = lookup.SubTable[si] - extSubTableClass = lookupTypes[overflowRecord.tableType][extType] - extSubTable = extSubTableClass() - extSubTable.Format = 1 - extSubTable.ExtSubTable = subTable - lookup.SubTable[si] = extSubTable - ok = 1 - return ok - - -def splitMultipleSubst(oldSubTable, newSubTable, overflowRecord): - ok = 1 - oldMapping = sorted(oldSubTable.mapping.items()) - oldLen = len(oldMapping) - - if overflowRecord.itemName in ["Coverage", "RangeRecord"]: - # Coverage table is written last. Overflow is to or within the - # the coverage table. We will just cut the subtable in half. - newLen = oldLen // 2 - - elif overflowRecord.itemName == "Sequence": - # We just need to back up by two items from the overflowed - # Sequence index to make sure the offset to the Coverage table - # doesn't overflow. - newLen = overflowRecord.itemIndex - 1 - - newSubTable.mapping = {} - for i in range(newLen, oldLen): - item = oldMapping[i] - key = item[0] - newSubTable.mapping[key] = item[1] - del oldSubTable.mapping[key] - - return ok - - -def splitAlternateSubst(oldSubTable, newSubTable, overflowRecord): - ok = 1 - if hasattr(oldSubTable, "sortCoverageLast"): - newSubTable.sortCoverageLast = oldSubTable.sortCoverageLast - - oldAlts = sorted(oldSubTable.alternates.items()) - oldLen = len(oldAlts) - - if overflowRecord.itemName in ["Coverage", "RangeRecord"]: - # Coverage table is written last. overflow is to or within the - # the coverage table. We will just cut the subtable in half. - newLen = oldLen // 2 - - elif overflowRecord.itemName == "AlternateSet": - # We just need to back up by two items - # from the overflowed AlternateSet index to make sure the offset - # to the Coverage table doesn't overflow. - newLen = overflowRecord.itemIndex - 1 - - newSubTable.alternates = {} - for i in range(newLen, oldLen): - item = oldAlts[i] - key = item[0] - newSubTable.alternates[key] = item[1] - del oldSubTable.alternates[key] - - return ok - - -def splitLigatureSubst(oldSubTable, newSubTable, overflowRecord): - ok = 1 - oldLigs = sorted(oldSubTable.ligatures.items()) - oldLen = len(oldLigs) - - if overflowRecord.itemName in ["Coverage", "RangeRecord"]: - # Coverage table is written last. overflow is to or within the - # the coverage table. We will just cut the subtable in half. - newLen = oldLen // 2 - - elif overflowRecord.itemName == "LigatureSet": - # We just need to back up by two items - # from the overflowed AlternateSet index to make sure the offset - # to the Coverage table doesn't overflow. - newLen = overflowRecord.itemIndex - 1 - - newSubTable.ligatures = {} - for i in range(newLen, oldLen): - item = oldLigs[i] - key = item[0] - newSubTable.ligatures[key] = item[1] - del oldSubTable.ligatures[key] - - return ok - - -def splitPairPos(oldSubTable, newSubTable, overflowRecord): - st = oldSubTable - ok = False - newSubTable.Format = oldSubTable.Format - if oldSubTable.Format == 1 and len(oldSubTable.PairSet) > 1: - for name in "ValueFormat1", "ValueFormat2": - setattr(newSubTable, name, getattr(oldSubTable, name)) - - # Move top half of coverage to new subtable - - newSubTable.Coverage = oldSubTable.Coverage.__class__() - - coverage = oldSubTable.Coverage.glyphs - records = oldSubTable.PairSet - - oldCount = len(oldSubTable.PairSet) // 2 - - oldSubTable.Coverage.glyphs = coverage[:oldCount] - oldSubTable.PairSet = records[:oldCount] - - newSubTable.Coverage.glyphs = coverage[oldCount:] - newSubTable.PairSet = records[oldCount:] - - oldSubTable.PairSetCount = len(oldSubTable.PairSet) - newSubTable.PairSetCount = len(newSubTable.PairSet) - - ok = True - - elif oldSubTable.Format == 2 and len(oldSubTable.Class1Record) > 1: - if not hasattr(oldSubTable, "Class2Count"): - oldSubTable.Class2Count = len(oldSubTable.Class1Record[0].Class2Record) - for name in "Class2Count", "ClassDef2", "ValueFormat1", "ValueFormat2": - setattr(newSubTable, name, getattr(oldSubTable, name)) - - # The two subtables will still have the same ClassDef2 and the table - # sharing will still cause the sharing to overflow. As such, disable - # sharing on the one that is serialized second (that's oldSubTable). - oldSubTable.DontShare = True - - # Move top half of class numbers to new subtable - - newSubTable.Coverage = oldSubTable.Coverage.__class__() - newSubTable.ClassDef1 = oldSubTable.ClassDef1.__class__() - - coverage = oldSubTable.Coverage.glyphs - classDefs = oldSubTable.ClassDef1.classDefs - records = oldSubTable.Class1Record - - oldCount = len(oldSubTable.Class1Record) // 2 - newGlyphs = set(k for k, v in classDefs.items() if v >= oldCount) - - oldSubTable.Coverage.glyphs = [g for g in coverage if g not in newGlyphs] - oldSubTable.ClassDef1.classDefs = { - k: v for k, v in classDefs.items() if v < oldCount - } - oldSubTable.Class1Record = records[:oldCount] - - newSubTable.Coverage.glyphs = [g for g in coverage if g in newGlyphs] - newSubTable.ClassDef1.classDefs = { - k: (v - oldCount) for k, v in classDefs.items() if v > oldCount - } - newSubTable.Class1Record = records[oldCount:] - - oldSubTable.Class1Count = len(oldSubTable.Class1Record) - newSubTable.Class1Count = len(newSubTable.Class1Record) - - ok = True - - return ok - - -def splitMarkBasePos(oldSubTable, newSubTable, overflowRecord): - # split half of the mark classes to the new subtable - classCount = oldSubTable.ClassCount - if classCount < 2: - # oh well, not much left to split... - return False - - oldClassCount = classCount // 2 - newClassCount = classCount - oldClassCount - - oldMarkCoverage, oldMarkRecords = [], [] - newMarkCoverage, newMarkRecords = [], [] - for glyphName, markRecord in zip( - oldSubTable.MarkCoverage.glyphs, oldSubTable.MarkArray.MarkRecord - ): - if markRecord.Class < oldClassCount: - oldMarkCoverage.append(glyphName) - oldMarkRecords.append(markRecord) - else: - markRecord.Class -= oldClassCount - newMarkCoverage.append(glyphName) - newMarkRecords.append(markRecord) - - oldBaseRecords, newBaseRecords = [], [] - for rec in oldSubTable.BaseArray.BaseRecord: - oldBaseRecord, newBaseRecord = rec.__class__(), rec.__class__() - oldBaseRecord.BaseAnchor = rec.BaseAnchor[:oldClassCount] - newBaseRecord.BaseAnchor = rec.BaseAnchor[oldClassCount:] - oldBaseRecords.append(oldBaseRecord) - newBaseRecords.append(newBaseRecord) - - newSubTable.Format = oldSubTable.Format - - oldSubTable.MarkCoverage.glyphs = oldMarkCoverage - newSubTable.MarkCoverage = oldSubTable.MarkCoverage.__class__() - newSubTable.MarkCoverage.glyphs = newMarkCoverage - - # share the same BaseCoverage in both halves - newSubTable.BaseCoverage = oldSubTable.BaseCoverage - - oldSubTable.ClassCount = oldClassCount - newSubTable.ClassCount = newClassCount - - oldSubTable.MarkArray.MarkRecord = oldMarkRecords - newSubTable.MarkArray = oldSubTable.MarkArray.__class__() - newSubTable.MarkArray.MarkRecord = newMarkRecords - - oldSubTable.MarkArray.MarkCount = len(oldMarkRecords) - newSubTable.MarkArray.MarkCount = len(newMarkRecords) - - oldSubTable.BaseArray.BaseRecord = oldBaseRecords - newSubTable.BaseArray = oldSubTable.BaseArray.__class__() - newSubTable.BaseArray.BaseRecord = newBaseRecords - - oldSubTable.BaseArray.BaseCount = len(oldBaseRecords) - newSubTable.BaseArray.BaseCount = len(newBaseRecords) - - return True - - -splitTable = { - "GSUB": { - # 1: splitSingleSubst, - 2: splitMultipleSubst, - 3: splitAlternateSubst, - 4: splitLigatureSubst, - # 5: splitContextSubst, - # 6: splitChainContextSubst, - # 7: splitExtensionSubst, - # 8: splitReverseChainSingleSubst, - }, - "GPOS": { - # 1: splitSinglePos, - 2: splitPairPos, - # 3: splitCursivePos, - 4: splitMarkBasePos, - # 5: splitMarkLigPos, - # 6: splitMarkMarkPos, - # 7: splitContextPos, - # 8: splitChainContextPos, - # 9: splitExtensionPos, - }, -} - - -def fixSubTableOverFlows(ttf, overflowRecord): - """ - An offset has overflowed within a sub-table. We need to divide this subtable into smaller parts. - """ - table = ttf[overflowRecord.tableType].table - lookup = table.LookupList.Lookup[overflowRecord.LookupListIndex] - subIndex = overflowRecord.SubTableIndex - subtable = lookup.SubTable[subIndex] - - # First, try not sharing anything for this subtable... - if not hasattr(subtable, "DontShare"): - subtable.DontShare = True - return True - - if hasattr(subtable, "ExtSubTable"): - # We split the subtable of the Extension table, and add a new Extension table - # to contain the new subtable. - - subTableType = subtable.ExtSubTable.__class__.LookupType - extSubTable = subtable - subtable = extSubTable.ExtSubTable - newExtSubTableClass = lookupTypes[overflowRecord.tableType][ - extSubTable.__class__.LookupType - ] - newExtSubTable = newExtSubTableClass() - newExtSubTable.Format = extSubTable.Format - toInsert = newExtSubTable - - newSubTableClass = lookupTypes[overflowRecord.tableType][subTableType] - newSubTable = newSubTableClass() - newExtSubTable.ExtSubTable = newSubTable - else: - subTableType = subtable.__class__.LookupType - newSubTableClass = lookupTypes[overflowRecord.tableType][subTableType] - newSubTable = newSubTableClass() - toInsert = newSubTable - - if hasattr(lookup, "SubTableCount"): # may not be defined yet. - lookup.SubTableCount = lookup.SubTableCount + 1 - - try: - splitFunc = splitTable[overflowRecord.tableType][subTableType] - except KeyError: - log.error( - "Don't know how to split %s lookup type %s", - overflowRecord.tableType, - subTableType, - ) - return False - - ok = splitFunc(subtable, newSubTable, overflowRecord) - if ok: - lookup.SubTable.insert(subIndex + 1, toInsert) - return ok - - -# End of OverFlow logic - - -def _buildClasses(): - import re - from .otData import otData - - formatPat = re.compile(r"([A-Za-z0-9]+)Format(\d+)$") - namespace = globals() - - # populate module with classes - for name, table in otData: - baseClass = BaseTable - m = formatPat.match(name) - if m: - # XxxFormatN subtable, we only add the "base" table - name = m.group(1) - # the first row of a format-switching otData table describes the Format; - # the first column defines the type of the Format field. - # Currently this can be either 'uint16' or 'uint8'. - formatType = table[0][0] - baseClass = getFormatSwitchingBaseTableClass(formatType) - if name not in namespace: - # the class doesn't exist yet, so the base implementation is used. - cls = type(name, (baseClass,), {}) - if name in ("GSUB", "GPOS"): - cls.DontShare = True - namespace[name] = cls - - # link Var{Table} <-> {Table} (e.g. ColorStop <-> VarColorStop, etc.) - for name, _ in otData: - if name.startswith("Var") and len(name) > 3 and name[3:] in namespace: - varType = namespace[name] - noVarType = namespace[name[3:]] - varType.NoVarType = noVarType - noVarType.VarType = varType - - for base, alts in _equivalents.items(): - base = namespace[base] - for alt in alts: - namespace[alt] = base - - global lookupTypes - lookupTypes = { - "GSUB": { - 1: SingleSubst, - 2: MultipleSubst, - 3: AlternateSubst, - 4: LigatureSubst, - 5: ContextSubst, - 6: ChainContextSubst, - 7: ExtensionSubst, - 8: ReverseChainSingleSubst, - }, - "GPOS": { - 1: SinglePos, - 2: PairPos, - 3: CursivePos, - 4: MarkBasePos, - 5: MarkLigPos, - 6: MarkMarkPos, - 7: ContextPos, - 8: ChainContextPos, - 9: ExtensionPos, - }, - "mort": { - 4: NoncontextualMorph, - }, - "morx": { - 0: RearrangementMorph, - 1: ContextualMorph, - 2: LigatureMorph, - # 3: Reserved, - 4: NoncontextualMorph, - 5: InsertionMorph, - }, - } - lookupTypes["JSTF"] = lookupTypes["GPOS"] # JSTF contains GPOS - for lookupEnum in lookupTypes.values(): - for enum, cls in lookupEnum.items(): - cls.LookupType = enum - - global featureParamTypes - featureParamTypes = { - "size": FeatureParamsSize, - } - for i in range(1, 20 + 1): - featureParamTypes["ss%02d" % i] = FeatureParamsStylisticSet - for i in range(1, 99 + 1): - featureParamTypes["cv%02d" % i] = FeatureParamsCharacterVariants - - # add converters to classes - from .otConverters import buildConverters - - for name, table in otData: - m = formatPat.match(name) - if m: - # XxxFormatN subtable, add converter to "base" table - name, format = m.groups() - format = int(format) - cls = namespace[name] - if not hasattr(cls, "converters"): - cls.converters = {} - cls.convertersByName = {} - converters, convertersByName = buildConverters(table[1:], namespace) - cls.converters[format] = converters - cls.convertersByName[format] = convertersByName - # XXX Add staticSize? - else: - cls = namespace[name] - cls.converters, cls.convertersByName = buildConverters(table, namespace) - # XXX Add staticSize? - - -_buildClasses() - - -def _getGlyphsFromCoverageTable(coverage): - if coverage is None: - # empty coverage table - return [] - else: - return coverage.glyphs diff --git a/spaces/lambdalabs/text-to-avatar/app.py b/spaces/lambdalabs/text-to-avatar/app.py deleted file mode 100644 index 1cbce01c47ae6838071a6713769d5b79061289ab..0000000000000000000000000000000000000000 --- a/spaces/lambdalabs/text-to-avatar/app.py +++ /dev/null @@ -1,190 +0,0 @@ -from contextlib import nullcontext -import gradio as gr -import torch -from torch import autocast -from diffusers import StableDiffusionPipeline - - -device = "cuda" if torch.cuda.is_available() else "cpu" -context = autocast if device == "cuda" else nullcontext -dtype = torch.float16 if device == "cuda" else torch.float32 - -model_id = 'lambdalabs/dreambooth-avatar' -pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=dtype) -pipe = pipe.to(device) - - - -def infer(prompt, n_samples, steps, scale): - - with context("cuda"): - images = pipe(n_samples*[prompt], guidance_scale=scale, num_inference_steps=steps).images - - return images - -css = """ - a { - color: inherit; - text-decoration: underline; - } - .gradio-container { - font-family: 'IBM Plex Sans', sans-serif; - } - .gr-button { - color: white; - border-color: #9d66e5; - background: #9d66e5; - } - input[type='range'] { - accent-color: #9d66e5; - } - .dark input[type='range'] { - accent-color: #dfdfdf; - } - .container { - max-width: 730px; - margin: auto; - padding-top: 1.5rem; - } - #gallery { - min-height: 22rem; - margin-bottom: 15px; - margin-left: auto; - margin-right: auto; - border-bottom-right-radius: .5rem !important; - border-bottom-left-radius: .5rem !important; - } - #gallery>div>.h-full { - min-height: 20rem; - } - .details:hover { - text-decoration: underline; - } - .gr-button { - white-space: nowrap; - } - .gr-button:focus { - border-color: rgb(147 197 253 / var(--tw-border-opacity)); - outline: none; - box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); - --tw-border-opacity: 1; - --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); - --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color); - --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity)); - --tw-ring-opacity: .5; - } - #advanced-options { - margin-bottom: 20px; - } - .footer { - margin-bottom: 45px; - margin-top: 35px; - text-align: center; - border-bottom: 1px solid #e5e5e5; - } - .footer>p { - font-size: .8rem; - display: inline-block; - padding: 0 10px; - transform: translateY(10px); - background: white; - } - .dark .logo{ filter: invert(1); } - .dark .footer { - border-color: #303030; - } - .dark .footer>p { - background: #0b0f19; - } - .acknowledgments h4{ - margin: 1.25em 0 .25em 0; - font-weight: bold; - font-size: 115%; - } -""" - -block = gr.Blocks(css=css) - -examples = [ - [ - 'Jeff Bezos, avatarart style', - 2, - 7.5, - ], - [ - 'Elon Musk, avatarart style', - 2, - 7.5, - ], - [ - 'Bill Gates, avatarart style', - 2, - 7, - ], -] - -with block: - gr.HTML( - """ -
        -
        - -

        - Avatar text to image -

        -
        -
        - """ - ) - with gr.Group(): - with gr.Box(): - with gr.Row().style(mobile_collapse=False, equal_height=True): - text = gr.Textbox( - label="Enter your prompt", - show_label=False, - max_lines=1, - placeholder="Enter your prompt", - ).style( - border=(True, False, True, True), - rounded=(True, False, False, True), - container=False, - ) - btn = gr.Button("Generate image").style( - margin=False, - rounded=(False, True, True, False), - ) - - gallery = gr.Gallery( - label="Generated images", show_label=False, elem_id="gallery" - ).style(grid=[2], height="auto") - - - with gr.Row(elem_id="advanced-options"): - samples = gr.Slider(label="Images", minimum=1, maximum=4, value=2, step=1) - steps = gr.Slider(label="Steps", minimum=5, maximum=50, value=50, step=5) - scale = gr.Slider( - label="Guidance Scale", minimum=0, maximum=50, value=7.5, step=0.1 - ) - - - ex = gr.Examples(examples=examples, fn=infer, inputs=[text, samples, scale], outputs=gallery, cache_examples=False) - ex.dataset.headers = [""] - - - text.submit(infer, inputs=[text, samples, steps, scale], outputs=gallery) - btn.click(infer, inputs=[text, samples, steps, scale], outputs=gallery) - gr.HTML( - """ - -
        -

        Put in a text prompt and generate your own Avatar art style image! -

        Trained by Eole Cervenka at Lambda Labs.

        -
        - """ - ) - -block.launch() \ No newline at end of file diff --git a/spaces/langvision/ChatWeb/_next/static/chunks/app/page-0620aca274ab75da.js b/spaces/langvision/ChatWeb/_next/static/chunks/app/page-0620aca274ab75da.js deleted file mode 100644 index 72ba5e6bb92856af861440bbb8433c14a048c270..0000000000000000000000000000000000000000 --- a/spaces/langvision/ChatWeb/_next/static/chunks/app/page-0620aca274ab75da.js +++ /dev/null @@ -1,9 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{909:function(e,t,n){Promise.resolve().then(n.bind(n,17433))},25952:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return o}});let r=n(26927);n(86006);let l=r._(n(6353));function u(e){return{default:(null==e?void 0:e.default)||e}}function o(e,t){let n=l.default,r={loading:e=>{let{error:t,isLoading:n,pastDelay:r}=e;return null}};"function"==typeof e&&(r.loader=e),Object.assign(r,t);let o=r.loader;return n({...r,loader:()=>null!=o?o().then(u):Promise.resolve(u(()=>null))})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},90761:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{suspense:function(){return l},NoSSR:function(){return u}}),n(26927),n(86006);let r=n(98687);function l(){let e=Error(r.NEXT_DYNAMIC_NO_SSR_CODE);throw e.digest=r.NEXT_DYNAMIC_NO_SSR_CODE,e}function u(e){let{children:t}=e;return t}},6353:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return o}});let r=n(26927),l=r._(n(86006)),u=n(90761),o=function(e){let t=Object.assign({loader:null,loading:null,ssr:!0},e);function n(e){let n=t.loading,r=l.default.createElement(n,{isLoading:!0,pastDelay:!0,error:null}),o=t.ssr?l.default.Fragment:u.NoSSR,a=t.lazy;return l.default.createElement(l.default.Suspense,{fallback:r},l.default.createElement(o,null,l.default.createElement(a,e)))}return t.lazy=l.default.lazy(t.loader),n.displayName="LoadableComponent",n}},17433:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return f}});var r=n(9268),l=n(25952),u=n.n(l),o=n(31405);n(80293);let a=u()(()=>Promise.all([n.e(121),n.e(130),n.e(680),n.e(372),n.e(173),n.e(780),n.e(642)]).then(n.bind(n,77592)),{loadableGenerated:{webpack:()=>[77592]},ssr:!1});function f(){let e=(0,o.Dt)();return(0,r.jsx)("html",{lang:"en",className:e,children:(0,r.jsx)("body",{children:(0,r.jsx)(a,{})})})}},31405:function(e,t,n){"use strict";var r,l;function u(){return localStorage.getItem("themeMode")||r.Light}function o(e){localStorage.setItem("themeMode",e)}n.d(t,{Dt:function(){return u},hY:function(){return r},pQ:function(){return o}}),(l=r||(r={})).Light="light",l.Dark="dark"},80293:function(){},83177:function(e,t,n){"use strict";/** - * @license React - * react-jsx-runtime.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var r=n(86006),l=Symbol.for("react.element"),u=Symbol.for("react.fragment"),o=Object.prototype.hasOwnProperty,a=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,f={key:!0,ref:!0,__self:!0,__source:!0};function i(e,t,n){var r,u={},i=null,c=null;for(r in void 0!==n&&(i=""+n),void 0!==t.key&&(i=""+t.key),void 0!==t.ref&&(c=t.ref),t)o.call(t,r)&&!f.hasOwnProperty(r)&&(u[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===u[r]&&(u[r]=t[r]);return{$$typeof:l,type:e,key:i,ref:c,props:u,_owner:a.current}}t.Fragment=u,t.jsx=i,t.jsxs=i},9268:function(e,t,n){"use strict";e.exports=n(83177)}},function(e){e.O(0,[253,698,744],function(){return e(e.s=909)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/spaces/leilevy/bingo/src/components/ui/textarea.tsx b/spaces/leilevy/bingo/src/components/ui/textarea.tsx deleted file mode 100644 index e25af722c7a5dc1121a9ab58d6716952f9f76081..0000000000000000000000000000000000000000 --- a/spaces/leilevy/bingo/src/components/ui/textarea.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import * as React from 'react' - -import { cn } from '@/lib/utils' - -export interface TextareaProps - extends React.TextareaHTMLAttributes {} - -const Textarea = React.forwardRef( - ({ className, ...props }, ref) => { - return ( -