diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Bad Piggies 1.3.0 Crack !!TOP!! [PC] Hack Tooll.md b/spaces/1gistliPinn/ChatGPT4/Examples/Bad Piggies 1.3.0 Crack !!TOP!! [PC] Hack Tooll.md deleted file mode 100644 index 6ec74b9fb327d041f1858703c6437c2575805440..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Bad Piggies 1.3.0 Crack !!TOP!! [PC] Hack Tooll.md +++ /dev/null @@ -1,6 +0,0 @@ -

Bad Piggies 1.3.0 Crack [PC] Hack Tooll


Download File ☆☆☆☆☆ https://imgfil.com/2uxYLS



- -The Renegades Of Orion 2.0 Download For Pc [addons]l · Download Film The ... Previous · Bad Piggies 1.3.0 Crack [PC] Hack Tooll · Next. 1fdad05405
-
-
-

diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/DOWNLOAD ADOBE ILLUSTRATOR CC 2019 64-BIT 23.1 PRE-ACTIVATED High Quality.md b/spaces/1gistliPinn/ChatGPT4/Examples/DOWNLOAD ADOBE ILLUSTRATOR CC 2019 64-BIT 23.1 PRE-ACTIVATED High Quality.md deleted file mode 100644 index a07191846e261cec21658607af3a0ad036085531..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/DOWNLOAD ADOBE ILLUSTRATOR CC 2019 64-BIT 23.1 PRE-ACTIVATED High Quality.md +++ /dev/null @@ -1,90 +0,0 @@ - -

How to Download Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated

-

If you are looking for a way to download Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated, you have come to the right place. In this article, we will show you how to get this powerful vector graphics software for free, without any crack or patch needed.

-

Adobe Illustrator CC 2019 is the industry-standard vector graphics app that lets you create logos, icons, drawings, typography, and illustrations for print, web, video, and mobile. It has all the drawing tools you need to turn simple shapes and colors into sophisticated logos, icons, and graphics. It also has amazing typography features that let you create stunning text designs. You can also use Illustrator to create freehand drawings, trace and recolor imported photos, and use your illustrations anywhere.

-

DOWNLOAD ADOBE ILLUSTRATOR CC 2019 64-BIT 23.1 PRE-ACTIVATED


Download File » https://imgfil.com/2uy0NS



-

Why Download Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated?

-

There are many reasons why you might want to download Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated. Here are some of them:

- -

How to Download Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated?

-

The process of downloading Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is very simple and straightforward. Here are the steps you need to follow:

-

-
    -
  1. Click on the link below to download the software from Google Drive.
  2. -
  3. Extract the zip file using WinRAR or any other software.
  4. -
  5. Double click on the installer and wait for the installation completed notification.
  6. -
  7. The software will activate itself with built in crack, no additional cracking or patching needed.
  8. -
  9. Launch the software from the start menu or taskbar and enjoy!
  10. -
-

Download Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated

-

Conclusion

-

Adobe Illustrator CC 2019 is a great software for creating vector graphics and typography. You can download it for free from the link above and use it without any hassle. We hope this article was helpful and informative for you. If you have any questions or problems, feel free to leave a comment below or contact us through our website.

-

What are the Features of Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated?

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is not only free to download and use, but also comes with many amazing features that make it a powerful vector graphics software. Here are some of the features that you can enjoy with this version:

- -

How to Use Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated?

-

Using Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is easy and fun. You can create any kind of vector graphics and typography with this software. Here are some tips and tricks to help you get started:

-
    -
  1. Create a new document or open an existing one from the File menu.
  2. -
  3. Select a tool from the toolbar or use the touch shortcuts on your screen.
  4. -
  5. Draw, edit, and manipulate your objects on the artboard using the tool options and panels.
  6. -
  7. Add effects, styles, and text to your objects using the Appearance panel and the Type tool.
  8. -
  9. Export or save your artwork in various formats from the File menu.
  10. -
-

Conclusion

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is a great software for creating vector graphics and typography. You can download it for free from the link above and use it without any hassle. We hope this article was helpful and informative for you. If you have any questions or problems, feel free to leave a comment below or contact us through our website.

-

How to Learn Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated?

-

If you want to master Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated, you need to learn how to use its features and tools effectively. Fortunately, there are many resources available online that can help you learn Illustrator at your own pace and level. Here are some of the best ones:

- -

What are the Benefits of Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated?

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is not only a powerful vector graphics software, but also a versatile and creative tool that can help you achieve your design goals. Here are some of the benefits of using this software:

- -

Conclusion

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is a great software for creating vector graphics and typography. You can download it for free from the link above and use it without any hassle. We hope this article was helpful and informative for you. If you have any questions or problems, feel free to leave a comment below or contact us through our website.

-

What are the Reviews of Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated?

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated has received many positive reviews from users and experts alike. Here are some of the highlights of what they have to say about this software:

- -

Conclusion

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is a great software for creating vector graphics and typography. You can download it for free from the link above and use it without any hassle. We hope this article was helpful and informative for you. If you have any questions or problems, feel free to leave a comment below or contact us through our website.

-

What are the Alternatives to Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated?

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is not the only software that can create and edit vector graphics. There are many other alternatives that you can try, depending on your needs and preferences. Here are some of the most popular ones:

- -

Conclusion

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is a great software for creating vector graphics and typography. You can download it for free from the link above and use it without any hassle. We hope this article was helpful and informative for you. If you have any questions or problems, feel free to leave a comment below or contact us through our website.

-

Conclusion

-

Adobe Illustrator CC 2019 64-Bit 23.1 Pre-Activated is a great software for creating vector graphics and typography. You can download it for free from the link above and use it without any hassle. We hope this article was helpful and informative for you. If you have any questions or problems, feel free to leave a comment below or contact us through our website.

3cee63e6c2
-
-
\ No newline at end of file diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Dawn AI APK The Most Powerful App for Selfies Portraits and Headshots.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Dawn AI APK The Most Powerful App for Selfies Portraits and Headshots.md deleted file mode 100644 index 32d743c69f43f5a7c0a115c20a358c0c8f5ff4b1..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Dawn AI APK The Most Powerful App for Selfies Portraits and Headshots.md +++ /dev/null @@ -1,112 +0,0 @@ -
-

Download Dawn AI APK Mod: How to Create Stunning Avatars with AI

-

Do you want to transform your selfies into amazing avatars using the latest AI technology? Do you want to explore endless styles and settings and generate fun and unique images with AI? Do you want to have unlimited access to all the features and styles of Dawn AI without paying anything? If you answered yes to any of these questions, then you should download Dawn AI APK Mod, a free avatars and stickers creator app that lets you create unlimited stylish avatars. It uses cutting-edge AI technology to convert your photos into exceptionally detailed sticker art.

-

In this article, we will tell you what is Dawn AI APK Mod, how to download and install it, how to use it, what are the benefits of using it, and what are some alternatives to it. By the end of this article, you will be able to create stunning avatars with AI using Dawn AI APK Mod.

-

download dawn ai apk mod


Download Ziphttps://urlin.us/2uSV5H



-

What is Dawn AI APK Mod?

-

Dawn AI APK Mod is a modified version of Dawn AI, an app that allows users to turn their words into art using the latest AI technology. With just a text prompt, the app generates an entirely new and beautiful image that users can save and share with others. The app offers a variety of creative styles and possibilities, from photorealism to fantasy, oil painting to anime, and more.

-

Dawn AI APK Mod is a free version of Dawn AI that unlocks all the premium features and styles of the app. Users can enjoy unlimited access to all the filters, overlays, themes, packs, and settings of the app without paying anything. Moreover, users can also remove the watermarks and ads from the generated images, making them more professional and attractive.

-

Features of Dawn AI APK Mod

-

Dawn AI APK Mod has many features that make it a powerful and versatile app for creating avatars with AI. Some of these features are:

-

How to download dawn ai apk mod for free
-Dawn ai apk mod latest version download
-Dawn ai premium apk mod unlocked all features
-Download dawn ai apk mod and create amazing avatars
-Dawn ai apk mod no watermark download
-Best dawn ai apk mod alternatives in 2023
-Dawn ai apk mod review and tutorial
-Download dawn ai apk mod and get unlimited stickers
-Dawn ai apk mod vs other avatar creator apps
-Dawn ai apk mod features and benefits
-Download dawn ai apk mod and enjoy AI-powered photo editing
-Dawn ai apk mod download link and installation guide
-Dawn ai apk mod compatibility and requirements
-Download dawn ai apk mod and share your sticker art with friends
-Dawn ai apk mod pros and cons
-Download dawn ai apk mod and customize your avatars
-Dawn ai apk mod tips and tricks
-Download dawn ai apk mod and join the community
-Dawn ai apk mod FAQs and answers
-Download dawn ai apk mod and have fun with your photos
-Dawn ai apk mod update and changelog
-Download dawn ai apk mod and access premium content
-Dawn ai apk mod feedback and ratings
-Download dawn ai apk mod and discover new styles
-Dawn ai apk mod bugs and fixes

-

Image recreation and enhancement

-

Dawn AI APK Mod takes your pictures and recreates them to virtually anything you want. You can enter a text prompt or a sketch and let the app generate an image based on your input. You can also use the @me tag feature to create your own avatars based on your selfies. The app uses advanced AI technology to analyze your photos and learn what you look like, then produces stunning portraits with thousands of possible styles.

-

Gender switch

-

Think you could be better as the other gender? With Dawn AI APK Mod, you can find out how you would look as a different gender. Just upload your photo and select the gender switch option. The app will transform your face into a male or female version, depending on your choice. You can also adjust the intensity of the transformation using a slider.

-

Large database for styles

-

The app (dawn AI mod apk) obviously has a large database to contain almost any profession and look you can think of. You can choose from a variety of styles and settings, such as 3D render, fine art, pen sketch, black and white, cartoon, anime, and more. You can also mix and match different styles and settings to create your own unique combinations. The app constantly updates its database with new styles and themes, so you will never run out of options.

-

Filters and overlays

-

Dawn AI APK Mod also allows you to apply various filters and overlays to your images to enhance their appearance and mood. You can choose from a range of filters, such as vintage, sepia, noir, retro, and more. You can also add overlays, such as stickers, emojis, text, frames, and more. You can adjust the opacity and size of the filters and overlays to suit your preferences.

-

Ease of usage

-

The app is very easy to use and does not require any technical skills or knowledge. You just need to enter a text prompt or a sketch and let the app do the rest. You can also use the @me tag feature to create your own avatars based on your selfies. The app has a simple and intuitive interface that guides you through the process of creating avatars with AI.

-

Share with friends

-

Once you have created your avatars with AI, you can easily save and share them with your friends and family. You can export your images in high resolution and quality. You can also share them on social media platforms, such as Facebook, Instagram, Twitter, WhatsApp, and more. You can also use your avatars as profile pictures, wallpapers, stickers, memes, and more.

-

How to download and install Dawn AI APK Mod?

-

If you want to download and install Dawn AI APK Mod on your Android device, you need to follow these simple steps:

-

Step 1: Download the APK file

-

The first step is to download the APK file of Dawn AI APK Mod from a reliable source. You can use the link below to download the latest version of the app:

-

Download Dawn AI APK Mod

-

Step 2: Enable unknown sources

-

The next step is to enable unknown sources on your device. This will allow you to install apps from sources other than the Google Play Store. To do this, go to Settings > Security > Unknown Sources and toggle it on.

-

Step 3: Install the APK file

-

The third step is to install the APK file on your device. To do this, locate the downloaded file in your file manager and tap on it. Follow the instructions on the screen to complete the installation.

-

Step 4: Launch the app and enjoy

-

The final step is to launch the app and enjoy creating stunning avatars with AI. You can access all the features and styles of the app without any limitations or restrictions.

-

How to use Dawn AI APK Mod?

-

Dawn AI APK Mod is very easy to use and does not require any technical skills or knowledge. You can use it in three different modes: text mode, sketch mode, and @me tag mode.

-

Text mode

-

In text mode, you can enter a text prompt and let the app generate an image based on your input. For example, you can enter "a beautiful woman with long blonde hair wearing a red dress" and see what the app produces. You can also enter a genre or a style, such as "fantasy", "anime", "oil painting", etc., and see what the app creates.

-

Sketch mode

-

In sketch mode, you can draw a sketch on the screen and let the app generate an image based on your drawing. For example, you can draw a face or a body shape and see what the app produces. You can also use different colors and brushes to create more detailed sketches.

-

@me tag mode

-

In @me tag mode, you can create your own avatars based on your selfies. To do this, you need to upload your photo and add the @me tag at the end of your text prompt. For example, you can enter "a handsome man wearing glasses @me" and see what the app produces. The app will analyze your photo and learn what you look like, then generate a portrait with thousands of possible styles.

-

What are the benefits of using Dawn AI APK Mod?

-

Dawn AI APK Mod has many benefits that make it a great app for creating avatars with AI. Some of these benefits are:

-

Unlimited access to all features and styles

-

Dawn AI APK Mod unlocks all the premium features and styles of Dawn AI without paying anything. You can enjoy unlimited access to all the filters, overlays, themes, packs, and settings of the app and create stunning avatars with AI. You can also remove the watermarks and ads from the generated images, making them more professional and attractive.

-

No watermarks or ads

-

Dawn AI APK Mod also removes the watermarks and ads from the generated images, making them more professional and attractive. You can save and share your images without any distractions or interruptions. You can also enjoy a smooth and fast performance of the app without any lags or crashes.

-

High-quality image generation

-

Dawn AI APK Mod uses cutting-edge AI technology to generate high-quality images that are exceptionally detailed and realistic. The app analyzes your photos and learns what you look like, then produces stunning portraits with thousands of possible styles. The app also recreates and enhances your images to virtually anything you want, from photorealism to fantasy, oil painting to anime, and more.

-

Fun and creative content creation

-

Dawn AI APK Mod allows you to have fun and be creative with your content creation. You can explore endless styles and settings and generate fun and unique images with AI. You can also mix and match different styles and settings to create your own unique combinations. You can also use your avatars as profile pictures, wallpapers, stickers, memes, and more.

-

What are some alternatives to Dawn AI APK Mod?

-

If you are looking for some alternatives to Dawn AI APK Mod, you can try these apps that also allow you to create avatars with AI:

-

Arible AI

-

Arible AI is an app that allows you to create realistic 3D avatars from your photos. You can customize your avatars with different hairstyles, outfits, accessories, and backgrounds. You can also animate your avatars with different expressions, poses, and movements. You can also chat with other users using your avatars.

-

Reface NEOCORTEXT

-

Reface NEOCORTEXT is an app that allows you to swap your face with celebrities, movie characters, cartoons, and more. You can use your photos or videos and choose from a huge library of faces to create hilarious and amazing face swaps. You can also share your creations on social media platforms.

-

TheDream.AI

-

TheDream.AI is an app that allows you to create dream-like images from your photos. You can use different filters, effects, stickers, and texts to transform your photos into surreal and artistic creations. You can also use the app's AI to generate images based on your text prompts or sketches.

-

Conclusion

-

Dawn AI APK Mod is a free avatars and stickers creator app that lets you create unlimited stylish avatars using the latest AI technology. It uses cutting-edge AI technology to convert your photos into exceptionally detailed sticker art. You can enjoy unlimited access to all the features and styles of the app without paying anything. Moreover, you can also remove the watermarks and ads from the generated images, making them more professional and attractive.

-

If you want to download Dawn AI APK Mod on your Android device, you can follow the steps mentioned in this article. You can also use the app in three different modes: text mode, sketch mode, and @me tag mode. You can also try some alternatives to Dawn AI APK Mod if you want to explore more options for creating avatars with AI.

-

We hope this article was helpful for you. If you have any questions or feedback, please feel free to leave a comment below.

-

FAQs

-

Here are some frequently asked questions about Dawn AI APK Mod:

-
    -
  1. Is Dawn AI APK Mod safe to use?
  2. -

    Dawn AI APK Mod is safe to use as long as you download it from a reliable source. However, since it is a modified version of Dawn AI, it may not be compatible with some devices or updates. Therefore, use it at your own risk.

    -
  3. How do I update Dawn AI APK Mod?
  4. -

    To update Dawn AI APK Mod, you need to download the latest version of the APK file from a reliable source and install it on your device. However, since it is a modified version of Dawn AI, it may not be compatible with some devices or updates. Therefore, check the compatibility before updating.

    -
  5. Can I use Dawn AI APK Mod on PC?
  6. -

    To use Dawn AI APK Mod on PC, you need to use an Android emulator software that allows you to run Android apps on PC. Some popular Android emulators are BlueStacks, NoxPlayer, MEmu, etc. However, since it is a modified version of Dawn AI, it may not work properly on some emulators.

    -
  7. Can I use Dawn AI APK Mod offline?
  8. -

    Dawn AI APK Mod requires an internet connection to work properly. The app uses AI technology to generate images based on your input, which requires a lot of data and processing power. Therefore, you cannot use the app offline.

    -
  9. What are some tips and tricks for using Dawn AI APK Mod?
  10. -

    Some tips and tricks for using Dawn AI APK Mod are:

    - -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download Driving Zone Russia Mod APK with Unlimited Coins and Cash.md b/spaces/1phancelerku/anime-remove-background/Download Driving Zone Russia Mod APK with Unlimited Coins and Cash.md deleted file mode 100644 index 25055581acf033dee97c83b24f291f14683e64ed..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download Driving Zone Russia Mod APK with Unlimited Coins and Cash.md +++ /dev/null @@ -1,149 +0,0 @@ -
-

Driving Zone Russia Mod APK Unlimited Money: A Review

-

If you are a fan of racing games, especially those that feature cars from Russia, then you might want to check out Driving Zone Russia. This is a simulator of street racing on the cars produced in Russia, with online and offline game modes. You can choose from classic cars produced in Russia, and the most modern models, each with its own character and a real engine sound. You can also customize your car with different colors, rims, spoilers, body kits, and liveries.

-

driving zone russia mod apk unlimited money


Downloadhttps://jinyurl.com/2uNRWI



-

But what if you want to enjoy the game without any limitations or restrictions? What if you want to have unlimited money to buy any car you want, or unlock all the features of the game? Well, there is a way to do that, and that is by downloading and installing Driving Zone Russia Mod APK Unlimited Money. This is a modified version of the original game that gives you access to unlimited money, coins, and other resources. You can use them to buy any car you want, upgrade your car's performance, or change the appearance of your car. You can also enjoy all the tracks, modes, and settings of the game without any ads or interruptions.

-

In this article, we will review Driving Zone Russia Mod APK Unlimited Money and tell you everything you need to know about it. We will cover its features, how to download and install it, tips and tricks for playing it, and its pros and cons. By the end of this article, you will be able to decide if this mod apk is worth trying or not.

-

Features of Driving Zone Russia Mod APK Unlimited Money

-

Driving Zone Russia Mod APK Unlimited Money has many features that make it an exciting and enjoyable racing game. Here are some of them:

-

driving zone russia mod apk unlimited coins
-driving zone russia mod apk download
-driving zone russia mod apk latest version
-driving zone russia mod apk android 1
-driving zone russia mod apk revdl
-driving zone russia mod apk hack
-driving zone russia mod apk free shopping
-driving zone russia mod apk all cars unlocked
-driving zone russia mod apk rexdl
-driving zone russia mod apk no ads
-driving zone russia mod apk unlimited everything
-driving zone russia mod apk obb
-driving zone russia mod apk offline
-driving zone russia mod apk old version
-driving zone russia mod apk 2023
-driving zone russia mod apk 2022
-driving zone russia mod apk 2021
-driving zone russia mod apk 2020
-driving zone russia mod apk 2019
-driving zone russia mod apk 2018
-driving zone russia mod apk 2017
-driving zone russia mod apk 2016
-driving zone russia mod apk 2015
-driving zone russia hack apk download
-driving zone russia hack apk unlimited money and coins
-driving zone russia hack apk latest version
-driving zone russia hack apk android 1
-driving zone russia hack apk revdl
-driving zone russia hack apk rexdl
-driving zone russia hack apk no ads
-download game driving zone russia mod apk unlimited money
-download game driving zone russia mod apk unlimited coins
-download game driving zone russia mod apk latest version
-download game driving zone russia mod apk android 1
-download game driving zone russia mod apk revdl
-download game driving zone russia mod apk rexdl
-download game driving zone russia mod apk no ads
-how to install driving zone russia mod apk unlimited money
-how to install driving zone russia mod apk unlimited coins
-how to install driving zone russia mod apk latest version
-how to install driving zone russia mod apk android 1
-how to install driving zone russia mod apk revdl
-how to install driving zone russia mod apk rexdl
-how to install driving zone russia mod apk no ads
-how to play driving zone russia mod apk unlimited money
-how to play driving zone russia mod apk unlimited coins
-how to play driving zone russia mod apk latest version
-how to play driving zone russia mod apk android 1

-

Modern graphics and realistic physics

-

The game has modern beautiful graphics that create a realistic atmosphere of street racing. The cars are detailed and well-designed, with accurate body and interior models. The tracks are also diverse and immersive, with different scenery and weather conditions. The game also has realistic car physics that simulate the behavior of real cars on different surfaces and situations. You can feel the speed, acceleration, braking, steering, and drifting of your car as you race along the busy highway or the challenging track.

-

Qualitatively modeled Russian cars

-

The game features a variety of cars produced in Russia, from classic models to modern ones. Each car has its own character and a real engine sound that matches its performance. You can choose from sedans, hatchbacks, coupes, SUVs, sports cars, or even trucks. Some of the cars available in the game are Lada Priora, Lada Granta, Lada Kalina, Lada Niva, Volga GAZ-24, Volga GAZ-3110, Moskvich-2141 AZLK-2141-02 Svyatogor Turbo Plus (Moskvich-2141), Moskvich-412 IE AZLK-412-028 (Moskvich-412), VAZ-2106 Zhiguli (Lada Riva), VAZ-2107 Zhiguli (Lada Riva), VAZ-2108 Sputnik (L ada Samara), VAZ-2109 Sputnik (Lada Samara), VAZ-2110 Lada (Lada 110), VAZ-2112 Lada (Lada 112), VAZ-2113 Lada (Lada 113), VAZ-2114 Lada (Lada 114), VAZ-2115 Lada (Lada 115), VAZ-2121 Niva (Lada Niva), GAZ-66, GAZ-3302 Gazelle, GAZ-3307, GAZ-3309, GAZ-3310 Valdai, GAZ-2330 Tigr, UAZ-469, UAZ-452, UAZ Patriot, UAZ Hunter, UAZ Cargo, Kamaz-4310, Kamaz-43118, Kamaz-5350 Mustang, Kamaz-6520, Kamaz-6522, ZIL-130, ZIL-131, ZIL-133, ZIL-157, ZIL-4331, MAZ-504, MAZ-5337, MAZ-5432, MAZ-6422, MAZ-7310 Uragan (MAZ 543M), and many more.

-

Four tracks with different weather conditions

-

The game offers four different tracks to race on, each with its own weather conditions and time of day. You can choose from a city track with busy traffic and pedestrians, a suburban track with a quieter atmosphere and a scenic view, a winter track with snow and ice on the road, or a desert track with sand and dust. Each track has its own challenges and surprises that will test your driving skills and reflexes. You can also change the weather conditions and the time of day in real-time to create your own unique racing experience.

-

Change the time of day in real-time

-

One of the most impressive features of the game is the ability to change the time of day in real-time. You can switch from day to night or vice versa with a simple swipe on the screen. This will affect the lighting and the visibility of the track, as well as the behavior of other drivers and pedestrians. You can also adjust the speed of time to make the day or night last longer or shorter. This feature adds more realism and variety to the game and allows you to enjoy different scenarios and atmospheres.

-

First person view / interior camera

-

The game also gives you the option to switch from the third person view to the first person view or the interior camera. This will let you see the road from the driver's perspective and feel more immersed in the game. You can also see the dashboard and the steering wheel of your car, as well as the mirrors and the indicators. The interior camera also shows you the damage and the wear of your car parts, such as the tires, the engine, or the brakes. You can use this feature to enhance your driving experience and challenge yourself more.

-

How to download and install Driving Zone Russia Mod APK Unlimited Money

-

If you are interested in trying Driving Zone Russia Mod APK Unlimited Money, you will need to follow these steps to download and install it on your device:

-

Requirements and compatibility

-

Before you download and install Driving Zone Russia Mod APK Unlimited Money, you will need to make sure that your device meets these requirements:

- -

Driving Zone Russia Mod APK Unlimited Money is compatible with most Android devices, including smartphones and tablets. However, some devices may not support some features or functions of the game due to hardware limitations or software issues.

-

Steps to download and install

-

Once you have checked that your device meets the requirements and compatibility, you can proceed to download and install Driving Zone Russia Mod APK Unlimited Money by following these steps:

-
    -
  1. Click on this link to download Driving Zone Russia Mod APK Unlimited Money file on your device.
  2. -
  3. Locate the downloaded file on your device storage and tap on it to start the installation process.
  4. -
  5. Follow the instructions on the screen to complete the installation process.
  6. -
  7. Launch the game from your app drawer or home screen and enjoy unlimited money and other mod features.
  8. -
-

How to use the mod features

-

After you have successfully installed Driving Zone Russia Mod APK Unlimited Money on your device, you can start using the mod features to enhance your gameplay. Here are some of the mod features and how to use them:

- -

Tips and tricks for playing Driving Zone Russia Mod APK Unlimited Money

-

Driving Zone Russia Mod APK Unlimited Money is a fun and addictive racing game that will keep you entertained for hours. However, if you want to master the game and become a pro racer, you will need some tips and tricks to help you out. Here are some of them:

-

Choose the right car for each track

-

The game offers a variety of cars to choose from, each with its own strengths and weaknesses. Some cars are faster, some are more agile, some are more durable, and some are more balanced. You will need to choose the right car for each track depending on the weather conditions, the road surface, and the traffic situation. For example, if you are racing on a winter track with snow and ice, you might want to choose a car with good traction and stability, such as an SUV or a truck. If you are racing on a desert track with sand and dust, you might want to choose a car with good speed and acceleration, such as a sports car or a coupe.

-

Adjust the settings to suit your preference

-

The game also allows you to adjust the settings to suit your preference and play style. You can change the difficulty level, the camera angle, the control method, the sound volume, and the graphics quality. You can also enable or disable some features such as traffic rules, damage system, police chase, or online mode. You can experiment with different settings until you find the ones that work best for you.

-

Use the brake and accelerator wisely

-

The game has realistic car physics that require you to use the brake and accelerator wisely. You cannot just press the gas pedal all the time and expect to win the race. You will need to slow down when approaching a turn, a curve, an obstacle, or a traffic jam. You will also need to accelerate when exiting a turn, a curve, an obstacle, or a traffic jam. You will need to balance between speed and control to avoid crashing or losing control of your car.

-

Record and share your gameplay videos

-

The game also has a feature that allows you to record and share your gameplay videos with other players online. You can capture your best moments in the game, such as your fastest lap time, your most epic drift, your most daring overtaking, or your most spectacular crash. You can then share your videos with other players on social media platforms such as Facebook, Twitter, Instagram, YouTube, or TikTok. You can also watch other players' videos and learn from their skills and strategies.

-

Pros and cons of Driving Zone Russia Mod APK Unlimited Money

-

Driving Zone Russia Mod APK Unlimited Money is not a perfect game and it has its pros and cons. Here are some of them:

-

Pros

- -

Cons

- -

Conclusion

-

Driving Zone Russia Mod APK Unlimited Money is a simulator of street racing on the cars produced in Russia, with online and offline game modes. The game has modern graphics and realistic physics that create a realistic atmosphere of street racing. The game features a variety of cars produced in Russia, each with its own character and a real engine sound. The game offers four different tracks with different weather conditions and time of day. The game allows you to change the time of day in real-time. The game gives you the option to switch from the third person view to the first person view or the interior camera. The game has unlimited money and other resources that allow you to buy any car you want, upgrade your car's performance, or change the appearance of your car. The game has no ads or interruptions that can ruin your gameplay. The game has a feature that allows you to record and share your gameplay videos with other players online.

-

However, the game also has some drawbacks that may affect your enjoyment of the game. The game can be too easy or boring for some players who prefer more challenge or variety in their racing games. The game can be too hard or frustrating for some players who are not used to the realistic car physics or the traffic rules. The game can be too repetitive or monotonous for some players who want more tracks, modes, or features in their racing games. The game can have some bugs or glitches that can affect the gameplay or the graphics quality. The game can be risky or illegal to download and install from third-party sources that may contain viruses or malware.

-

Therefore, we recommend Driving Zone Russia Mod APK Unlimited Money to anyone who loves racing games, especially those that feature cars from Russia. This game will give you a realistic and immersive experience of street racing on Russian cars, with unlimited money and other mod features. However, we also advise you to be careful when downloading and installing this mod apk from third-party sources, as they may not be safe or legal. We also suggest you to try the original version of Driving Zone Russia first before trying this mod apk, as it may suit your preference better.

-

FAQs

-

Here are some frequently asked questions about Driving Zone Russia Mod APK Unlimited Money:

-
    -
  1. Q: Is Driving Zone Russia Mod APK Unlimited Money free?
  2. -
  3. A: Yes, Driving Zone Russia Mod APK Unlimited Money is free to download and play. However, you may need to pay for some in-app purchases or subscriptions if you want to access some premium features or items in the game.
  4. -
  5. Q: Is Driving Zone Russia Mod APK Unlimited Money safe?
  6. -
  7. A: Driving Zone Russia Mod APK Unlimited Money is not officially endorsed by the developers of Driving Zone Russia, so it may not be safe or legal to download and install from third-party sources. You may encounter some viruses or malware that can harm your device or compromise your privacy. You may also face some legal issues if you violate the terms and conditions of Driving Zone Russia.
  8. -
  9. Q: How do I update Driving Zone Russia Mod APK Unlimited Money?
  10. -
  11. A: Driving Zone Russia Mod APK Unlimited Money may not be compatible with the latest version of Driving Zone Russia, so you may need to update it manually from time to time. You will need to check for updates from the source where you downloaded it from, and follow the instructions on how to download and install the updated version.
  12. -
  13. Q: How do I uninstall Driving Zone Russia Mod APK Unlimited Money?
  14. -
  15. A: If you want to uninstall Driving Zone Russia Mod APK Unlimited Money from your device, you will need to follow these steps:
  16. - -
  17. Q: Can I play Driving Zone Russia Mod APK Unlimited Money offline?
  18. -
  19. A: Yes, you can play Driving Zone Russia Mod APK Unlimited Money offline without an internet connection. However, you may not be able to access some online features or modes, such as multiplayer mode, leaderboards, or achievements.
  20. -

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download Plants vs Zombies 2 for PC and Protect Your Garden from the Undead.md b/spaces/1phancelerku/anime-remove-background/Download Plants vs Zombies 2 for PC and Protect Your Garden from the Undead.md deleted file mode 100644 index 8d10147615f69abad8231adda31f2886cb5a1b30..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download Plants vs Zombies 2 for PC and Protect Your Garden from the Undead.md +++ /dev/null @@ -1,53 +0,0 @@ - -

How to Download Plants vs Zombies 2 on PC

-

Plants vs Zombies 2 is a popular tower defense game that pits you against hordes of zombies who want to eat your brains. You have to use various plants with different abilities to stop them from reaching your house. The game features hundreds of levels across different worlds and time periods, as well as endless modes, mini-games, daily events, and online competitions.

-

While Plants vs Zombies 2 is primarily designed for mobile devices, you might want to play it on your PC for various reasons. Maybe you want to enjoy the game on a bigger screen, or use a keyboard and mouse or a controller for better control. Maybe you want to save battery life on your phone or tablet, or avoid interruptions from calls and notifications. Whatever your reason, there are several ways to download Plants vs Zombies 2 on PC. In this article, we will show you three methods that you can use to play this fun and addictive game on your PC.

-

download plants vs zombies 2 in pc


Downloadhttps://jinyurl.com/2uNPYz



-

Method 1: Use Windows 11 and native Android emulation

-

One of the easiest ways to download Plants vs Zombies 2 on PC is to use Windows 11, the latest version of Microsoft's operating system. Windows 11 comes with a built-in feature that allows you to run Android apps natively on your PC, without the need for any third-party software. Here are the steps to follow:

-
    -
  1. Check if your PC meets the minimum requirements for Windows 11 and Android emulation. You will need a 64-bit processor, 4 GB of RAM, 64 GB of storage, a TPM 2.0 chip, and a DirectX 12 compatible graphics card. You can use the PC Health Check app to see if your PC is eligible for the upgrade.
  2. -
  3. Update your PC to Windows 11 and enable the Windows Subsystem for Android. You can download Windows 11 from the Windows Update section in the Settings app. To enable the Windows Subsystem for Android, go to the Microsoft Store and install the app. You will also need to install the Amazon Appstore app, which will allow you to access Android apps on your PC.
  4. -
  5. Install Plants vs Zombies 2 from the Amazon Appstore or the Google Play Store. You can launch the Amazon Appstore app from the Start menu or the Taskbar and search for Plants vs Zombies 2. Alternatively, you can also install the Google Play Store app from the Amazon Appstore and use it to download Plants vs Zombies 2. You will need to sign in with your Google account to access the Google Play Store.
  6. -
  7. Launch the game and enjoy playing it on your PC. You can find Plants vs Zombies 2 in the Start menu or the Taskbar, along with other Android apps. You can use your mouse or touchpad to interact with the game, or connect a keyboard or a controller for better control. You can also adjust the window size and orientation of the game according to your preference.
  8. -
-

Method 2: Use an Android emulator such as Bluestacks or Nox Player

-

Another way to download Plants vs Zombies 2 on PC is to use an Android emulator, which is a software that simulates an Android device on your PC. There are many Android emulators available online, but some of the most popular ones are Bluestacks and Nox Player. Here are the steps to follow:

-
    -
  1. Download and install an Android emulator of your choice from their official websites. You can visit Bluestacks.com or Bignox.com to download Bluestacks or Nox Player respectively . Follow the instructions on the screen to install and set up the emulator on your PC.
  2. -
  3. Sign in with your Google account and access the Google Play Store. Once you launch the emulator, you will need to sign in with your Google account to access the Google Play Store and other Google services. You can use an existing account or create a new one.
  4. -
  5. Search for Plants vs Zombies 2 and install it on your emulator. You can use the search bar in the Google Play Store to find Plants vs Zombies 2 and click on the Install button to download it on your emulator.
  6. -
  7. Launch the game and customize the controls according to your preference. You can find Plants vs Zombies 2 on the home screen or in the app drawer of your emulator. You can use your mouse or touchpad to interact with the game, or connect a keyboard or a controller for better control. You can also customize the controls by using the settings menu of your emulator.
  8. -
-

Method 3: Use Parsec to stream the game from your PC to your Android device

-

A third way to download Plants vs Zombies 2 on PC is to use Parsec, which is a software that allows you to stream games from your PC to your Android device. This way, you can play Plants vs Zombies 2 on your PC without installing it, as long as you have a good internet connection and a compatible device. Here are the steps to follow:

-
    -
  1. Download and install Parsec on both your PC and your Android device. You can visit Parsecgaming.com to download Parsec for free. Follow the instructions on the screen to install and set up Parsec on your PC and your Android device.
  2. -
  3. Create a Parsec account and sign in on both devices. You will need to create a Parsec account and sign in on both your PC and your Android device to use the streaming service. You can use an existing account or create a new one.
  4. -
  5. Launch Plants vs Zombies 2 on your PC and start hosting a game session. You can launch Plants vs Zombies 2 on your PC from the Start menu or the Taskbar, or from any other source that you have installed it from. Once the game is running, open Parsec on your PC and click on the Host tab. You will see a code that you can use to invite other devices to join your game session.
  6. -
  7. Connect to your PC from your Android device using Parsec and start playing the game. Open Parsec on your Android device and click on the Friends tab. You will see a list of devices that you can connect to, including your PC. Enter the code that you got from your PC and click on the Connect button. You will see the game screen on your Android device and you can start playing the game.
  8. -
-

Conclusion

-

Plants vs Zombies 2 is a fun and addictive game that you can enjoy on your PC using any of the methods mentioned above. Whether you use Windows 11, an Android emulator, or Parsec, you can experience the game on a bigger screen, with better control and performance. Here are some tips and tricks for playing the game on PC:

- -

FAQs

-

Here are some common questions that readers might have about downloading Plants vs Zombies 2 on PC:

-
-
Q1: Is Plants vs Zombies 2 free to play?
-
A1: Yes, Plants vs Zombies 2 is free to play, but it contains ads and in-app purchases that can enhance your gaming experience.
-
Q2: Can I play Plants vs Zombies 2 offline?
-
A2: Yes, you can play Plants vs Zombies 2 offline, but you will need an internet connection to access some features such as daily events, leaderboards, and cloud save.
-
Q3: How many worlds are there in Plants vs Zombies 2?
-
A3: There are currently 11 worlds in Plants vs Zombies 2, each with its own theme, plants, zombies, and challenges. You can unlock them by collecting stars or paying with gems.
-
Q4: What is Plant Food and how do I use it?
-
A4: Plant Food is a special item that can boost your plants' abilities for a short time. You can get Plant Food by killing glowing zombies, planting Power Lily, or buying it with coins. To use Plant Food, just drag it onto any plant on the lawn.
-
Q5: What is the best strategy for playing Plants vs Zombies 2?
-
A5: There is no definitive answer to this question, as different strategies work for different levels, modes, and preferences. However, some general tips are to plan ahead, use a variety of plants, upgrade your plants regularly, and experiment with different combinations.
-
-

I hope you found this article helpful and informative. If you have any questions or feedback, please leave a comment below. Happy gaming!

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/2ndelement/voicevox/voicevox_engine/kana_parser.py b/spaces/2ndelement/voicevox/voicevox_engine/kana_parser.py deleted file mode 100644 index 7aa9e9d82c8e48195c6993dea267708b42012c5a..0000000000000000000000000000000000000000 --- a/spaces/2ndelement/voicevox/voicevox_engine/kana_parser.py +++ /dev/null @@ -1,146 +0,0 @@ -from typing import List, Optional - -from .model import AccentPhrase, Mora, ParseKanaError, ParseKanaErrorCode -from .mora_list import openjtalk_text2mora - -LOOP_LIMIT = 300 -UNVOICE_SYMBOL = "_" -ACCENT_SYMBOL = "'" -NOPAUSE_DELIMITER = "/" -PAUSE_DELIMITER = "、" -WIDE_INTERROGATION_MARK = "?" - -text2mora_with_unvoice = {} -for text, (consonant, vowel) in openjtalk_text2mora.items(): - text2mora_with_unvoice[text] = Mora( - text=text, - consonant=consonant if len(consonant) > 0 else None, - consonant_length=0 if len(consonant) > 0 else None, - vowel=vowel, - vowel_length=0, - pitch=0, - is_interrogative=False, - ) - if vowel in ["a", "i", "u", "e", "o"]: - text2mora_with_unvoice[UNVOICE_SYMBOL + text] = Mora( - text=text, - consonant=consonant if len(consonant) > 0 else None, - consonant_length=0 if len(consonant) > 0 else None, - vowel=vowel.upper(), - vowel_length=0, - pitch=0, - is_interrogative=False, - ) - - -def _text_to_accent_phrase(phrase: str) -> AccentPhrase: - """ - longest matchにより読み仮名からAccentPhraseを生成 - 入力長Nに対し計算量O(N^2) - """ - accent_index: Optional[int] = None - moras: List[Mora] = [] - - base_index = 0 # パース開始位置。ここから右の文字列をstackに詰めていく。 - stack = "" # 保留中の文字列 - matched_text: Optional[str] = None # 保留中の文字列内で最後にマッチした仮名 - - outer_loop = 0 - while base_index < len(phrase): - outer_loop += 1 - if phrase[base_index] == ACCENT_SYMBOL: - if len(moras) == 0: - raise ParseKanaError(ParseKanaErrorCode.ACCENT_TOP, text=phrase) - if accent_index is not None: - raise ParseKanaError(ParseKanaErrorCode.ACCENT_TWICE, text=phrase) - accent_index = len(moras) - base_index += 1 - continue - for watch_index in range(base_index, len(phrase)): - if phrase[watch_index] == ACCENT_SYMBOL: - break - # 普通の文字の場合 - stack += phrase[watch_index] - if stack in text2mora_with_unvoice: - matched_text = stack - # push mora - if matched_text is None: - raise ParseKanaError(ParseKanaErrorCode.UNKNOWN_TEXT, text=stack) - else: - moras.append(text2mora_with_unvoice[matched_text].copy(deep=True)) - base_index += len(matched_text) - stack = "" - matched_text = None - if outer_loop > LOOP_LIMIT: - raise ParseKanaError(ParseKanaErrorCode.INFINITE_LOOP) - if accent_index is None: - raise ParseKanaError(ParseKanaErrorCode.ACCENT_NOTFOUND, text=phrase) - else: - return AccentPhrase(moras=moras, accent=accent_index, pause_mora=None) - - -def parse_kana(text: str) -> List[AccentPhrase]: - """ - AquesTalkライクな読み仮名をパースして音長・音高未指定のaccent phraseに変換 - """ - - parsed_results: List[AccentPhrase] = [] - phrase_base = 0 - if len(text) == 0: - raise ParseKanaError(ParseKanaErrorCode.EMPTY_PHRASE, position=1) - - for i in range(len(text) + 1): - if i == len(text) or text[i] in [PAUSE_DELIMITER, NOPAUSE_DELIMITER]: - phrase = text[phrase_base:i] - if len(phrase) == 0: - raise ParseKanaError( - ParseKanaErrorCode.EMPTY_PHRASE, - position=str(len(parsed_results) + 1), - ) - phrase_base = i + 1 - - is_interrogative = WIDE_INTERROGATION_MARK in phrase - if is_interrogative: - if WIDE_INTERROGATION_MARK in phrase[:-1]: - raise ParseKanaError( - ParseKanaErrorCode.INTERROGATION_MARK_NOT_AT_END, text=phrase - ) - phrase = phrase.replace(WIDE_INTERROGATION_MARK, "") - - accent_phrase: AccentPhrase = _text_to_accent_phrase(phrase) - if i < len(text) and text[i] == PAUSE_DELIMITER: - accent_phrase.pause_mora = Mora( - text="、", - consonant=None, - consonant_length=None, - vowel="pau", - vowel_length=0, - pitch=0, - ) - accent_phrase.is_interrogative = is_interrogative - - parsed_results.append(accent_phrase) - - return parsed_results - - -def create_kana(accent_phrases: List[AccentPhrase]) -> str: - text = "" - for i, phrase in enumerate(accent_phrases): - for j, mora in enumerate(phrase.moras): - if mora.vowel in ["A", "I", "U", "E", "O"]: - text += UNVOICE_SYMBOL - - text += mora.text - if j + 1 == phrase.accent: - text += ACCENT_SYMBOL - - if phrase.is_interrogative: - text += WIDE_INTERROGATION_MARK - - if i < len(accent_phrases) - 1: - if phrase.pause_mora is None: - text += NOPAUSE_DELIMITER - else: - text += PAUSE_DELIMITER - return text diff --git a/spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/GenerSpeech/model/prosody_util.py b/spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/GenerSpeech/model/prosody_util.py deleted file mode 100644 index 113c39df9d1b0144aa5a5f00505c7e08bfc6ea11..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/GenerSpeech/model/prosody_util.py +++ /dev/null @@ -1,385 +0,0 @@ -from torch import nn -import copy -import torch -from utils.hparams import hparams -from modules.GenerSpeech.model.wavenet import WN -import math - -from modules.fastspeech.tts_modules import LayerNorm -import torch.nn.functional as F -from utils.tts_utils import group_hidden_by_segs, sequence_mask - -from scipy.cluster.vq import kmeans2 -from torch.nn import functional as F - - -class VQEmbeddingEMA(nn.Module): - def __init__(self, n_embeddings, embedding_dim, commitment_cost=0.25, decay=0.999, epsilon=1e-5, - print_vq_prob=False): - super(VQEmbeddingEMA, self).__init__() - self.commitment_cost = commitment_cost - self.n_embeddings = n_embeddings - self.decay = decay - self.epsilon = epsilon - self.print_vq_prob = print_vq_prob - self.register_buffer('data_initialized', torch.zeros(1)) - init_bound = 1 / 512 - embedding = torch.Tensor(n_embeddings, embedding_dim) - embedding.uniform_(-init_bound, init_bound) - self.register_buffer("embedding", embedding) - self.register_buffer("ema_count", torch.zeros(n_embeddings)) - self.register_buffer("ema_weight", self.embedding.clone()) - - def encode(self, x): - B, T, _ = x.shape - M, D = self.embedding.size() - x_flat = x.detach().reshape(-1, D) - - distances = torch.addmm(torch.sum(self.embedding ** 2, dim=1) + - torch.sum(x_flat ** 2, dim=1, keepdim=True), - x_flat, self.embedding.t(), - alpha=-2.0, beta=1.0) # [B*T_mel, N_vq] - indices = torch.argmin(distances.float(), dim=-1) # [B*T_mel] - quantized = F.embedding(indices, self.embedding) - quantized = quantized.view_as(x) - return x_flat, quantized, indices - - def forward(self, x): - """ - - :param x: [B, T, D] - :return: [B, T, D] - """ - B, T, _ = x.shape - M, D = self.embedding.size() - if self.training and self.data_initialized.item() == 0: - print('| running kmeans in VQVAE') # data driven initialization for the embeddings - x_flat = x.detach().reshape(-1, D) - rp = torch.randperm(x_flat.size(0)) - kd = kmeans2(x_flat[rp].data.cpu().numpy(), self.n_embeddings, minit='points') - self.embedding.copy_(torch.from_numpy(kd[0])) - x_flat, quantized, indices = self.encode(x) - encodings = F.one_hot(indices, M).float() - self.ema_weight.copy_(torch.matmul(encodings.t(), x_flat)) - self.ema_count.copy_(torch.sum(encodings, dim=0)) - - x_flat, quantized, indices = self.encode(x) - encodings = F.one_hot(indices, M).float() - indices = indices.reshape(B, T) - - if self.training and self.data_initialized.item() != 0: - self.ema_count = self.decay * self.ema_count + (1 - self.decay) * torch.sum(encodings, dim=0) - - n = torch.sum(self.ema_count) - self.ema_count = (self.ema_count + self.epsilon) / (n + M * self.epsilon) * n - - dw = torch.matmul(encodings.t(), x_flat) - self.ema_weight = self.decay * self.ema_weight + (1 - self.decay) * dw - - self.embedding = self.ema_weight / self.ema_count.unsqueeze(-1) - self.data_initialized.fill_(1) - - e_latent_loss = F.mse_loss(x, quantized.detach(), reduction='none') - nonpadding = (x.abs().sum(-1) > 0).float() - e_latent_loss = (e_latent_loss.mean(-1) * nonpadding).sum() / nonpadding.sum() - loss = self.commitment_cost * e_latent_loss - - quantized = x + (quantized - x).detach() - - avg_probs = torch.mean(encodings, dim=0) - perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10))) - if self.print_vq_prob: - print("| VQ code avg_probs: ", avg_probs) - return quantized, loss, indices, perplexity - -class CrossAttenLayer(nn.Module): - def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1): - super(CrossAttenLayer, self).__init__() - self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) - self.linear1 = nn.Linear(d_model, dim_feedforward) - self.dropout1 = nn.Dropout(dropout) - self.norm1 = nn.LayerNorm(d_model) - self.linear2 = nn.Linear(dim_feedforward, d_model) - self.dropout2 = nn.Dropout(dropout) - self.norm2 = nn.LayerNorm(d_model) - self.activation = nn.ReLU() - - def forward(self, src, local_emotion, emotion_key_padding_mask=None, forcing=False): - # src: (Tph, B, 256) local_emotion: (Temo, B, 256) emotion_key_padding_mask: (B, Temo) - if forcing: - maxlength = src.shape[0] - k = local_emotion.shape[0] / src.shape[0] - lengths1 = torch.ceil(torch.tensor([i for i in range(maxlength)]).to(src.device) * k) + 1 - lengths2 = torch.floor(torch.tensor([i for i in range(maxlength)]).to(src.device) * k) - 1 - mask1 = sequence_mask(lengths1, local_emotion.shape[0]) - mask2 = sequence_mask(lengths2, local_emotion.shape[0]) - mask = mask1.float() - mask2.float() - attn_emo = mask.repeat(src.shape[1], 1, 1) # (B, Tph, Temo) - src2 = torch.matmul(local_emotion.permute(1, 2, 0), attn_emo.float().transpose(1, 2)).permute(2, 0, 1) - else: - src2, attn_emo = self.multihead_attn(src, local_emotion, local_emotion, key_padding_mask=emotion_key_padding_mask) - src = src + self.dropout1(src2) - src = self.norm1(src) - src2 = self.linear2(self.activation(self.linear1(src))) - src = src + self.dropout2(src2) - src = self.norm2(src) - return src, attn_emo - - -class ProsodyAligner(nn.Module): - def __init__(self, num_layers, guided_sigma=0.3, guided_layers=None, norm=None): - super(ProsodyAligner, self).__init__() - self.layers = nn.ModuleList([CrossAttenLayer(d_model=hparams['hidden_size'], nhead=2) for _ in range(num_layers)]) - self.num_layers = num_layers - self.norm = norm - self.guided_sigma = guided_sigma - self.guided_layers = guided_layers if guided_layers is not None else num_layers - - def forward(self, src, local_emotion, src_key_padding_mask=None, emotion_key_padding_mask=None, forcing=False): - output = src - guided_loss = 0 - attn_emo_list = [] - for i, mod in enumerate(self.layers): - # output: (Tph, B, 256), global_emotion: (1, B, 256), local_emotion: (Temo, B, 256) mask: None, src_key_padding_mask: (B, Tph), - # emotion_key_padding_mask: (B, Temo) - output, attn_emo = mod(output, local_emotion, emotion_key_padding_mask=emotion_key_padding_mask, forcing=forcing) - attn_emo_list.append(attn_emo.unsqueeze(1)) - # attn_emo: (B, Tph, Temo) attn: (B, Tph, Tph) - if i < self.guided_layers and src_key_padding_mask is not None: - s_length = (~src_key_padding_mask).float().sum(-1) # B - emo_length = (~emotion_key_padding_mask).float().sum(-1) - attn_w_emo = _make_guided_attention_mask(src_key_padding_mask.size(-1), s_length, emotion_key_padding_mask.size(-1), emo_length, self.guided_sigma) - - g_loss_emo = attn_emo * attn_w_emo # N, L, S - non_padding_mask = (~src_key_padding_mask).unsqueeze(-1) & (~emotion_key_padding_mask).unsqueeze(1) - guided_loss = g_loss_emo[non_padding_mask].mean() + guided_loss - - if self.norm is not None: - output = self.norm(output) - - return output, guided_loss, attn_emo_list - -def _make_guided_attention_mask(ilen, rilen, olen, rolen, sigma): - grid_x, grid_y = torch.meshgrid(torch.arange(ilen, device=rilen.device), torch.arange(olen, device=rolen.device)) - grid_x = grid_x.unsqueeze(0).expand(rilen.size(0), -1, -1) - grid_y = grid_y.unsqueeze(0).expand(rolen.size(0), -1, -1) - rilen = rilen.unsqueeze(1).unsqueeze(1) - rolen = rolen.unsqueeze(1).unsqueeze(1) - return 1.0 - torch.exp( - -((grid_y.float() / rolen - grid_x.float() / rilen) ** 2) / (2 * (sigma ** 2)) - ) - -class LocalStyleAdaptor(nn.Module): - def __init__(self, hidden_size, num_vq_codes=64, padding_idx=0): - super(LocalStyleAdaptor, self).__init__() - self.encoder = ConvBlocks(80, hidden_size, [1] * 5, 5, dropout=hparams['vae_dropout']) - self.n_embed = num_vq_codes - self.vqvae = VQEmbeddingEMA(self.n_embed, hidden_size, commitment_cost=hparams['lambda_commit']) - self.wavenet = WN(hidden_channels=80, gin_channels=80, kernel_size=3, dilation_rate=1, n_layers=4) - self.padding_idx = padding_idx - self.hidden_size = hidden_size - - def forward(self, ref_mels, mel2ph=None, no_vq=False): - """ - - :param ref_mels: [B, T, 80] - :return: [B, 1, H] - """ - padding_mask = ref_mels[:, :, 0].eq(self.padding_idx).data - ref_mels = self.wavenet(ref_mels.transpose(1, 2), x_mask=(~padding_mask).unsqueeze(1).repeat([1, 80, 1])).transpose(1, 2) - if mel2ph is not None: - ref_ph, _ = group_hidden_by_segs(ref_mels, mel2ph, torch.max(mel2ph)) - else: - ref_ph = ref_mels - prosody = self.encoder(ref_ph) - if no_vq: - return prosody - z, vq_loss, vq_tokens, ppl = self.vqvae(prosody) - vq_loss = vq_loss.mean() - return z, vq_loss, ppl - - - - -class LambdaLayer(nn.Module): - def __init__(self, lambd): - super(LambdaLayer, self).__init__() - self.lambd = lambd - - def forward(self, x): - return self.lambd(x) - - -class Conv1d(nn.Conv1d): - """A wrapper around nn.Conv1d, that works on (batch, time, channels)""" - - def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, dilation=1, groups=1, bias=True, padding=0): - super(Conv1d, self).__init__(in_channels=in_channels, out_channels=out_channels, - kernel_size=kernel_size, stride=stride, dilation=dilation, - groups=groups, bias=bias, padding=padding) - - def forward(self, x): - return super().forward(x.transpose(2, 1)).transpose(2, 1) - - -def init_weights_func(m): - classname = m.__class__.__name__ - if classname.find("Conv1d") != -1: - torch.nn.init.xavier_uniform_(m.weight) - - -class ResidualBlock(nn.Module): - """Implements conv->PReLU->norm n-times""" - - def __init__(self, channels, kernel_size, dilation, n=2, norm_type='bn', dropout=0.0, - c_multiple=2, ln_eps=1e-12): - super(ResidualBlock, self).__init__() - - if norm_type == 'bn': - norm_builder = lambda: nn.BatchNorm1d(channels) - elif norm_type == 'in': - norm_builder = lambda: nn.InstanceNorm1d(channels, affine=True) - elif norm_type == 'gn': - norm_builder = lambda: nn.GroupNorm(8, channels) - elif norm_type == 'ln': - norm_builder = lambda: LayerNorm(channels, dim=1, eps=ln_eps) - else: - norm_builder = lambda: nn.Identity() - - self.blocks = [ - nn.Sequential( - norm_builder(), - nn.Conv1d(channels, c_multiple * channels, kernel_size, dilation=dilation, - padding=(dilation * (kernel_size - 1)) // 2), - LambdaLayer(lambda x: x * kernel_size ** -0.5), - nn.GELU(), - nn.Conv1d(c_multiple * channels, channels, 1, dilation=dilation), - ) - for i in range(n) - ] - - self.blocks = nn.ModuleList(self.blocks) - self.dropout = dropout - - def forward(self, x): - nonpadding = (x.abs().sum(1) > 0).float()[:, None, :] - for b in self.blocks: - x_ = b(x) - if self.dropout > 0 and self.training: - x_ = F.dropout(x_, self.dropout, training=self.training) - x = x + x_ - x = x * nonpadding - return x - - -class Pad(nn.ZeroPad2d): - def __init__(self, kernel_size, dilation): - pad_total = dilation * (kernel_size - 1) - begin = pad_total // 2 - end = pad_total - begin - - super(Pad, self).__init__((begin, end, begin, end)) - - -class ZeroTemporalPad(nn.ZeroPad2d): - """Pad sequences to equal lentgh in the temporal dimension""" - - def __init__(self, kernel_size, dilation, causal=False): - total_pad = (dilation * (kernel_size - 1)) - - if causal: - super(ZeroTemporalPad, self).__init__((total_pad, 0)) - else: - begin = total_pad // 2 - end = total_pad - begin - super(ZeroTemporalPad, self).__init__((begin, end)) - - -class ConvBlocks(nn.Module): - """Decodes the expanded phoneme encoding into spectrograms""" - - def __init__(self, channels, out_dims, dilations, kernel_size, - norm_type='ln', layers_in_block=2, c_multiple=2, - dropout=0.0, ln_eps=1e-5, init_weights=True): - super(ConvBlocks, self).__init__() - self.res_blocks = nn.Sequential( - *[ResidualBlock(channels, kernel_size, d, - n=layers_in_block, norm_type=norm_type, c_multiple=c_multiple, - dropout=dropout, ln_eps=ln_eps) - for d in dilations], - ) - if norm_type == 'bn': - norm = nn.BatchNorm1d(channels) - elif norm_type == 'in': - norm = nn.InstanceNorm1d(channels, affine=True) - elif norm_type == 'gn': - norm = nn.GroupNorm(8, channels) - elif norm_type == 'ln': - norm = LayerNorm(channels, dim=1, eps=ln_eps) - self.last_norm = norm - self.post_net1 = nn.Conv1d(channels, out_dims, kernel_size=3, padding=1) - if init_weights: - self.apply(init_weights_func) - - def forward(self, x): - """ - - :param x: [B, T, H] - :return: [B, T, H] - """ - x = x.transpose(1, 2) - nonpadding = (x.abs().sum(1) > 0).float()[:, None, :] - x = self.res_blocks(x) * nonpadding - x = self.last_norm(x) * nonpadding - x = self.post_net1(x) * nonpadding - return x.transpose(1, 2) - - -class TextConvEncoder(ConvBlocks): - def __init__(self, embed_tokens, channels, out_dims, dilations, kernel_size, - norm_type='ln', layers_in_block=2, c_multiple=2, - dropout=0.0, ln_eps=1e-5, init_weights=True): - super().__init__(channels, out_dims, dilations, kernel_size, - norm_type, layers_in_block, c_multiple, - dropout, ln_eps, init_weights) - self.embed_tokens = embed_tokens - self.embed_scale = math.sqrt(channels) - - def forward(self, txt_tokens): - """ - - :param txt_tokens: [B, T] - :return: { - 'encoder_out': [B x T x C] - } - """ - x = self.embed_scale * self.embed_tokens(txt_tokens) - return super().forward(x) - - -class ConditionalConvBlocks(ConvBlocks): - def __init__(self, channels, g_channels, out_dims, dilations, kernel_size, - norm_type='ln', layers_in_block=2, c_multiple=2, - dropout=0.0, ln_eps=1e-5, init_weights=True, is_BTC=True): - super().__init__(channels, out_dims, dilations, kernel_size, - norm_type, layers_in_block, c_multiple, - dropout, ln_eps, init_weights) - self.g_prenet = nn.Conv1d(g_channels, channels, 3, padding=1) - self.is_BTC = is_BTC - if init_weights: - self.g_prenet.apply(init_weights_func) - - def forward(self, x, g, x_mask): - if self.is_BTC: - x = x.transpose(1, 2) - g = g.transpose(1, 2) - x_mask = x_mask.transpose(1, 2) - x = x + self.g_prenet(g) - x = x * x_mask - - if not self.is_BTC: - x = x.transpose(1, 2) - x = super(ConditionalConvBlocks, self).forward(x) # input needs to be BTC - if not self.is_BTC: - x = x.transpose(1, 2) - return x diff --git a/spaces/AIGC-Audio/Make_An_Audio_inpaint/README.md b/spaces/AIGC-Audio/Make_An_Audio_inpaint/README.md deleted file mode 100644 index d2c182d1786442911f6a5a165054a35db9ed2cf3..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/Make_An_Audio_inpaint/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Make An Audio Inpaint -emoji: 🔥 -colorFrom: green -colorTo: pink -sdk: gradio -sdk_version: 3.17.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/ASJMO/freegpt/g4f/Provider/Providers/Bard.py b/spaces/ASJMO/freegpt/g4f/Provider/Providers/Bard.py deleted file mode 100644 index 4c37c4b719430031fce41ce49946f0e6ac93d155..0000000000000000000000000000000000000000 --- a/spaces/ASJMO/freegpt/g4f/Provider/Providers/Bard.py +++ /dev/null @@ -1,74 +0,0 @@ -import os, requests, json, browser_cookie3, re, random -from ...typing import sha256, Dict, get_type_hints - -url = 'https://bard.google.com' -model = ['Palm2'] -supports_stream = False -needs_auth = True - -def _create_completion(model: str, messages: list, stream: bool, **kwargs): - psid = {cookie.name: cookie.value for cookie in browser_cookie3.chrome( - domain_name='.google.com')}['__Secure-1PSID'] - - formatted = '\n'.join([ - '%s: %s' % (message['role'], message['content']) for message in messages - ]) - prompt = f'{formatted}\nAssistant:' - - proxy = kwargs.get('proxy', False) - if proxy == False: - print('warning!, you did not give a proxy, a lot of countries are banned from Google Bard, so it may not work') - - snlm0e = None - conversation_id = None - response_id = None - choice_id = None - - client = requests.Session() - client.proxies = { - 'http': f'http://{proxy}', - 'https': f'http://{proxy}'} if proxy else None - - client.headers = { - 'authority': 'bard.google.com', - 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8', - 'origin': 'https://bard.google.com', - 'referer': 'https://bard.google.com/', - 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36', - 'x-same-domain': '1', - 'cookie': f'__Secure-1PSID={psid}' - } - - snlm0e = re.search(r'SNlM0e\":\"(.*?)\"', - client.get('https://bard.google.com/').text).group(1) if not snlm0e else snlm0e - - params = { - 'bl': 'boq_assistant-bard-web-server_20230326.21_p0', - '_reqid': random.randint(1111, 9999), - 'rt': 'c' - } - - data = { - 'at': snlm0e, - 'f.req': json.dumps([None, json.dumps([[prompt], None, [conversation_id, response_id, choice_id]])])} - - intents = '.'.join([ - 'assistant', - 'lamda', - 'BardFrontendService' - ]) - - response = client.post(f'https://bard.google.com/_/BardChatUi/data/{intents}/StreamGenerate', - data=data, params=params) - - chat_data = json.loads(response.content.splitlines()[3])[0][2] - if chat_data: - json_chat_data = json.loads(chat_data) - - yield json_chat_data[0][0] - - else: - yield 'error' - -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/AbeShinzo0708/AI_Kishida_Fumio_speaker/pre-fix/librosa/__init__.py b/spaces/AbeShinzo0708/AI_Kishida_Fumio_speaker/pre-fix/librosa/__init__.py deleted file mode 100644 index fd33ddb0937cbb125f570af8936083f867e8a41b..0000000000000000000000000000000000000000 --- a/spaces/AbeShinzo0708/AI_Kishida_Fumio_speaker/pre-fix/librosa/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# https://github.com/librosa/librosa/issues/1682 - -import lazy_loader as lazy -from .version import version as __version__ - -_filename = __file__ -if _filename.endswith('.pyc'): - _filename = _filename[:-1] - -__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, _filename) diff --git a/spaces/Abhilashvj/planogram-compliance/classify/predict.py b/spaces/Abhilashvj/planogram-compliance/classify/predict.py deleted file mode 100644 index 0d9bce8929e7758cd2d7c015603c7fc7db685d9c..0000000000000000000000000000000000000000 --- a/spaces/Abhilashvj/planogram-compliance/classify/predict.py +++ /dev/null @@ -1,345 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc. - -Usage - sources: - $ python classify/predict.py --weights yolov5s-cls.pt --source 0 # webcam - img.jpg # image - vid.mp4 # video - screen # screenshot - path/ # directory - list.txt # list of images - list.streams # list of streams - 'path/*.jpg' # glob - 'https://youtu.be/Zgi9g1ksQHc' # YouTube - 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream - -Usage - formats: - $ python classify/predict.py --weights yolov5s-cls.pt # PyTorch - yolov5s-cls.torchscript # TorchScript - yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn - yolov5s-cls_openvino_model # OpenVINO - yolov5s-cls.engine # TensorRT - yolov5s-cls.mlmodel # CoreML (macOS-only) - yolov5s-cls_saved_model # TensorFlow SavedModel - yolov5s-cls.pb # TensorFlow GraphDef - yolov5s-cls.tflite # TensorFlow Lite - yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU - yolov5s-cls_paddle_model # PaddlePaddle -""" - -import argparse -import os -import platform -import sys -from pathlib import Path - -import torch -import torch.nn.functional as F - -FILE = Path(__file__).resolve() -ROOT = FILE.parents[1] # 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 - -from models.common import DetectMultiBackend -from utils.augmentations import classify_transforms -from utils.dataloaders import ( - IMG_FORMATS, - VID_FORMATS, - LoadImages, - LoadScreenshots, - LoadStreams, -) -from utils.general import ( - LOGGER, - Profile, - check_file, - check_img_size, - check_imshow, - check_requirements, - colorstr, - cv2, - increment_path, - print_args, - strip_optimizer, -) -from utils.plots import Annotator -from utils.torch_utils import select_device, smart_inference_mode - - -@smart_inference_mode() -def run( - weights=ROOT / "yolov5s-cls.pt", # model.pt path(s) - source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam) - data=ROOT / "data/coco128.yaml", # dataset.yaml path - imgsz=(224, 224), # inference size (height, width) - device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu - view_img=False, # show results - save_txt=False, # save results to *.txt - nosave=False, # do not save images/videos - augment=False, # augmented inference - visualize=False, # visualize features - update=False, # update all models - project=ROOT / "runs/predict-cls", # save results to project/name - name="exp", # save results to project/name - exist_ok=False, # existing project/name ok, do not increment - half=False, # use FP16 half-precision inference - dnn=False, # use OpenCV DNN for ONNX inference - vid_stride=1, # video frame-rate stride -): - source = str(source) - save_img = not nosave and not source.endswith( - ".txt" - ) # save inference images - is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) - is_url = source.lower().startswith( - ("rtsp://", "rtmp://", "http://", "https://") - ) - webcam = ( - source.isnumeric() - or source.endswith(".streams") - or (is_url and not is_file) - ) - screenshot = source.lower().startswith("screen") - if is_url and is_file: - source = check_file(source) # download - - # Directories - save_dir = increment_path( - Path(project) / name, exist_ok=exist_ok - ) # increment run - (save_dir / "labels" if save_txt else save_dir).mkdir( - parents=True, exist_ok=True - ) # make dir - - # Load model - device = select_device(device) - model = DetectMultiBackend( - weights, device=device, dnn=dnn, data=data, fp16=half - ) - stride, names, pt = model.stride, model.names, model.pt - imgsz = check_img_size(imgsz, s=stride) # check image size - - # Dataloader - bs = 1 # batch_size - if webcam: - view_img = check_imshow(warn=True) - dataset = LoadStreams( - source, - img_size=imgsz, - transforms=classify_transforms(imgsz[0]), - vid_stride=vid_stride, - ) - bs = len(dataset) - elif screenshot: - dataset = LoadScreenshots( - source, img_size=imgsz, stride=stride, auto=pt - ) - else: - dataset = LoadImages( - source, - img_size=imgsz, - transforms=classify_transforms(imgsz[0]), - vid_stride=vid_stride, - ) - vid_path, vid_writer = [None] * bs, [None] * bs - - # Run inference - model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup - seen, windows, dt = 0, [], (Profile(), Profile(), Profile()) - for path, im, im0s, vid_cap, s in dataset: - with dt[0]: - im = torch.Tensor(im).to(model.device) - im = im.half() if model.fp16 else im.float() # uint8 to fp16/32 - if len(im.shape) == 3: - im = im[None] # expand for batch dim - - # Inference - with dt[1]: - results = model(im) - - # Post-process - with dt[2]: - pred = F.softmax(results, dim=1) # probabilities - - # Process predictions - for i, prob in enumerate(pred): # per image - seen += 1 - if webcam: # batch_size >= 1 - p, im0, frame = path[i], im0s[i].copy(), dataset.count - s += f"{i}: " - else: - p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0) - - p = Path(p) # to Path - save_path = str(save_dir / p.name) # im.jpg - txt_path = str(save_dir / "labels" / p.stem) + ( - "" if dataset.mode == "image" else f"_{frame}" - ) # im.txt - - s += "%gx%g " % im.shape[2:] # print string - annotator = Annotator(im0, example=str(names), pil=True) - - # Print results - top5i = prob.argsort(0, descending=True)[ - :5 - ].tolist() # top 5 indices - s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, " - - # Write results - text = "\n".join(f"{prob[j]:.2f} {names[j]}" for j in top5i) - if save_img or view_img: # Add bbox to image - annotator.text((32, 32), text, txt_color=(255, 255, 255)) - if save_txt: # Write to file - with open(f"{txt_path}.txt", "a") as f: - f.write(text + "\n") - - # Stream results - im0 = annotator.result() - if view_img: - if platform.system() == "Linux" and p not in windows: - windows.append(p) - cv2.namedWindow( - str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO - ) # allow window resize (Linux) - cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0]) - 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[i] != save_path: # new video - vid_path[i] = save_path - if isinstance(vid_writer[i], cv2.VideoWriter): - vid_writer[ - i - ].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 = str( - Path(save_path).with_suffix(".mp4") - ) # force *.mp4 suffix on results videos - vid_writer[i] = cv2.VideoWriter( - save_path, - cv2.VideoWriter_fourcc(*"mp4v"), - fps, - (w, h), - ) - vid_writer[i].write(im0) - - # Print time (inference-only) - LOGGER.info(f"{s}{dt[1].dt * 1E3:.1f}ms") - - # Print results - t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image - LOGGER.info( - f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" - % t - ) - 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 "" - ) - LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") - if update: - strip_optimizer( - weights[0] - ) # update model (to fix SourceChangeWarning) - - -def parse_opt(): - parser = argparse.ArgumentParser() - parser.add_argument( - "--weights", - nargs="+", - type=str, - default=ROOT / "yolov5s-cls.pt", - help="model path(s)", - ) - parser.add_argument( - "--source", - type=str, - default=ROOT / "data/images", - help="file/dir/URL/glob/screen/0(webcam)", - ) - parser.add_argument( - "--data", - type=str, - default=ROOT / "data/coco128.yaml", - help="(optional) dataset.yaml path", - ) - parser.add_argument( - "--imgsz", - "--img", - "--img-size", - nargs="+", - type=int, - default=[224], - help="inference size h,w", - ) - parser.add_argument( - "--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu" - ) - parser.add_argument("--view-img", action="store_true", help="show results") - parser.add_argument( - "--save-txt", action="store_true", help="save results to *.txt" - ) - parser.add_argument( - "--nosave", action="store_true", help="do not save images/videos" - ) - parser.add_argument( - "--augment", action="store_true", help="augmented inference" - ) - parser.add_argument( - "--visualize", action="store_true", help="visualize features" - ) - parser.add_argument( - "--update", action="store_true", help="update all models" - ) - parser.add_argument( - "--project", - default=ROOT / "runs/predict-cls", - help="save results to project/name", - ) - parser.add_argument( - "--name", default="exp", help="save results to project/name" - ) - parser.add_argument( - "--exist-ok", - action="store_true", - help="existing project/name ok, do not increment", - ) - parser.add_argument( - "--half", action="store_true", help="use FP16 half-precision inference" - ) - parser.add_argument( - "--dnn", action="store_true", help="use OpenCV DNN for ONNX inference" - ) - parser.add_argument( - "--vid-stride", type=int, default=1, help="video frame-rate stride" - ) - opt = parser.parse_args() - opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand - print_args(vars(opt)) - return opt - - -def main(opt): - check_requirements(exclude=("tensorboard", "thop")) - run(**vars(opt)) - - -if __name__ == "__main__": - opt = parse_opt() - main(opt) diff --git a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/Vitalentum.py b/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/Vitalentum.py deleted file mode 100644 index ade492d2db0d4c84bca5de4b774330fdf292c3ab..0000000000000000000000000000000000000000 --- a/spaces/AchyuthGamer/OpenGPT/g4f/Provider/Providers/Vitalentum.py +++ /dev/null @@ -1,69 +0,0 @@ -from __future__ import annotations - -import json -from aiohttp import ClientSession - -from .base_provider import AsyncGeneratorProvider -from ..typing import AsyncResult, Messages - -class Vitalentum(AsyncGeneratorProvider): - url = "https://app.vitalentum.io" - working = True - supports_gpt_35_turbo = True - - - @classmethod - async def create_async_generator( - cls, - model: str, - messages: Messages, - proxy: str = None, - **kwargs - ) -> AsyncResult: - headers = { - "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36", - "Accept" : "text/event-stream", - "Accept-language" : "de,en-US;q=0.7,en;q=0.3", - "Origin" : cls.url, - "Referer" : cls.url + "/", - "Sec-Fetch-Dest" : "empty", - "Sec-Fetch-Mode" : "cors", - "Sec-Fetch-Site" : "same-origin", - } - conversation = json.dumps({"history": [{ - "speaker": "human" if message["role"] == "user" else "bot", - "text": message["content"], - } for message in messages]}) - data = { - "conversation": conversation, - "temperature": 0.7, - **kwargs - } - async with ClientSession( - headers=headers - ) as session: - async with session.post(cls.url + "/api/converse-edge", json=data, proxy=proxy) as response: - response.raise_for_status() - async for line in response.content: - line = line.decode() - if line.startswith("data: "): - if line.startswith("data: [DONE]"): - break - line = json.loads(line[6:-1]) - content = line["choices"][0]["delta"].get("content") - if content: - yield content - - - @classmethod - @property - def params(cls): - params = [ - ("model", "str"), - ("messages", "list[dict[str, str]]"), - ("stream", "bool"), - ("proxy", "str"), - ("temperature", "float"), - ] - param = ", ".join([": ".join(p) for p in params]) - return f"g4f.provider.{cls.__name__} supports: ({param})" \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/customshapes/CustomShapes.d.ts b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/customshapes/CustomShapes.d.ts deleted file mode 100644 index a7b6fc7bf5775962f7067cca8cbcddad6ae2cd1a..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/customshapes/CustomShapes.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import CustomShapes from '../../../plugins/customshapes'; -export default CustomShapes; \ No newline at end of file diff --git a/spaces/AjulorC/question_answering_bot_deployed_with_Gradio/README.md b/spaces/AjulorC/question_answering_bot_deployed_with_Gradio/README.md deleted file mode 100644 index 4e8f8eaced0efa05c271a6667fd97d9881b48ba1..0000000000000000000000000000000000000000 --- a/spaces/AjulorC/question_answering_bot_deployed_with_Gradio/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Question_answering_bot_deployed_with_Gradio -emoji: 🦀 -colorFrom: green -colorTo: gray -sdk: gradio -sdk_version: 2.8.11 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/Aki004/herta-so-vits/modules/__init__.py b/spaces/Aki004/herta-so-vits/modules/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Akmyradov/TurkmenTTSweSTT/vits/train_ms.py b/spaces/Akmyradov/TurkmenTTSweSTT/vits/train_ms.py deleted file mode 100644 index 34870c622d2c05ad0a1a8fcf648197d0f51800cd..0000000000000000000000000000000000000000 --- a/spaces/Akmyradov/TurkmenTTSweSTT/vits/train_ms.py +++ /dev/null @@ -1,294 +0,0 @@ -import os -import json -import argparse -import itertools -import math -import torch -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 - -import commons -import utils -from data_utils import ( - TextAudioSpeakerLoader, - TextAudioSpeakerCollate, - DistributedBucketSampler -) -from models import ( - SynthesizerTrn, - MultiPeriodDiscriminator, -) -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 -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'] = '80000' - - hps = utils.get_hparams() - 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='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=8, 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=8, shuffle=False, - batch_size=hps.train.batch_size, pin_memory=True, - drop_last=False, collate_fn=collate_fn) - - 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, - **hps.model).cuda(rank) - net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank) - optim_g = torch.optim.AdamW( - 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) - net_g = DDP(net_g, device_ids=[rank]) - net_d = DDP(net_d, device_ids=[rank]) - - try: - _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g) - _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d) - global_step = (epoch_str - 1) * len(train_loader) - except: - epoch_str = 1 - global_step = 0 - - 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) - - 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], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, eval_loader], logger, [writer, writer_eval]) - else: - train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, None], None, None) - scheduler_g.step() - scheduler_d.step() - - -def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers): - net_g, net_d = nets - optim_g, optim_d = optims - scheduler_g, scheduler_d = 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() - for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers) in enumerate(train_loader): - 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) - - 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) = net_g(x, x_lengths, spec, spec_lengths, speakers) - - 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 - 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) - 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 - 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))) - global_step += 1 - - if rank == 0: - logger.info('====> Epoch: {}'.format(epoch)) - - -def evaluate(hps, generator, eval_loader, writer_eval): - generator.eval() - with torch.no_grad(): - for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers) in enumerate(eval_loader): - x, x_lengths = x.cuda(0), x_lengths.cuda(0) - spec, spec_lengths = spec.cuda(0), spec_lengths.cuda(0) - y, y_lengths = y.cuda(0), y_lengths.cuda(0) - speakers = speakers.cuda(0) - - # remove else - x = x[:1] - x_lengths = x_lengths[:1] - spec = spec[:1] - spec_lengths = spec_lengths[:1] - y = y[:1] - y_lengths = y_lengths[:1] - speakers = speakers[:1] - break - y_hat, attn, mask, *_ = generator.module.infer(x, x_lengths, speakers, max_len=1000) - 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 = { - "gen/mel": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy()) - } - audio_dict = { - "gen/audio": y_hat[0,:,:y_hat_lengths[0]] - } - if global_step == 0: - image_dict.update({"gt/mel": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())}) - audio_dict.update({"gt/audio": 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/Alpaca233/SadTalker/src/test_audio2coeff.py b/spaces/Alpaca233/SadTalker/src/test_audio2coeff.py deleted file mode 100644 index bbf19f494e2127b4ae9d6074b172fddb694d6e34..0000000000000000000000000000000000000000 --- a/spaces/Alpaca233/SadTalker/src/test_audio2coeff.py +++ /dev/null @@ -1,123 +0,0 @@ -import os -import torch -import numpy as np -from scipy.io import savemat, loadmat -from yacs.config import CfgNode as CN -from scipy.signal import savgol_filter - -import safetensors -import safetensors.torch - -from src.audio2pose_models.audio2pose import Audio2Pose -from src.audio2exp_models.networks import SimpleWrapperV2 -from src.audio2exp_models.audio2exp import Audio2Exp -from src.utils.safetensor_helper import load_x_from_safetensor - -def load_cpk(checkpoint_path, model=None, optimizer=None, device="cpu"): - checkpoint = torch.load(checkpoint_path, map_location=torch.device(device)) - if model is not None: - model.load_state_dict(checkpoint['model']) - if optimizer is not None: - optimizer.load_state_dict(checkpoint['optimizer']) - - return checkpoint['epoch'] - -class Audio2Coeff(): - - def __init__(self, sadtalker_path, device): - #load config - fcfg_pose = open(sadtalker_path['audio2pose_yaml_path']) - cfg_pose = CN.load_cfg(fcfg_pose) - cfg_pose.freeze() - fcfg_exp = open(sadtalker_path['audio2exp_yaml_path']) - cfg_exp = CN.load_cfg(fcfg_exp) - cfg_exp.freeze() - - # load audio2pose_model - self.audio2pose_model = Audio2Pose(cfg_pose, None, device=device) - self.audio2pose_model = self.audio2pose_model.to(device) - self.audio2pose_model.eval() - for param in self.audio2pose_model.parameters(): - param.requires_grad = False - - try: - if sadtalker_path['use_safetensor']: - checkpoints = safetensors.torch.load_file(sadtalker_path['checkpoint']) - self.audio2pose_model.load_state_dict(load_x_from_safetensor(checkpoints, 'audio2pose')) - else: - load_cpk(sadtalker_path['audio2pose_checkpoint'], model=self.audio2pose_model, device=device) - except: - raise Exception("Failed in loading audio2pose_checkpoint") - - # load audio2exp_model - netG = SimpleWrapperV2() - netG = netG.to(device) - for param in netG.parameters(): - netG.requires_grad = False - netG.eval() - try: - if sadtalker_path['use_safetensor']: - checkpoints = safetensors.torch.load_file(sadtalker_path['checkpoint']) - netG.load_state_dict(load_x_from_safetensor(checkpoints, 'audio2exp')) - else: - load_cpk(sadtalker_path['audio2exp_checkpoint'], model=netG, device=device) - except: - raise Exception("Failed in loading audio2exp_checkpoint") - self.audio2exp_model = Audio2Exp(netG, cfg_exp, device=device, prepare_training_loss=False) - self.audio2exp_model = self.audio2exp_model.to(device) - for param in self.audio2exp_model.parameters(): - param.requires_grad = False - self.audio2exp_model.eval() - - self.device = device - - def generate(self, batch, coeff_save_dir, pose_style, ref_pose_coeff_path=None): - - with torch.no_grad(): - #test - results_dict_exp= self.audio2exp_model.test(batch) - exp_pred = results_dict_exp['exp_coeff_pred'] #bs T 64 - - #for class_id in range(1): - #class_id = 0#(i+10)%45 - #class_id = random.randint(0,46) #46 styles can be selected - batch['class'] = torch.LongTensor([pose_style]).to(self.device) - results_dict_pose = self.audio2pose_model.test(batch) - pose_pred = results_dict_pose['pose_pred'] #bs T 6 - - pose_len = pose_pred.shape[1] - if pose_len<13: - pose_len = int((pose_len-1)/2)*2+1 - pose_pred = torch.Tensor(savgol_filter(np.array(pose_pred.cpu()), pose_len, 2, axis=1)).to(self.device) - else: - pose_pred = torch.Tensor(savgol_filter(np.array(pose_pred.cpu()), 13, 2, axis=1)).to(self.device) - - coeffs_pred = torch.cat((exp_pred, pose_pred), dim=-1) #bs T 70 - - coeffs_pred_numpy = coeffs_pred[0].clone().detach().cpu().numpy() - - if ref_pose_coeff_path is not None: - coeffs_pred_numpy = self.using_refpose(coeffs_pred_numpy, ref_pose_coeff_path) - - savemat(os.path.join(coeff_save_dir, '%s##%s.mat'%(batch['pic_name'], batch['audio_name'])), - {'coeff_3dmm': coeffs_pred_numpy}) - - return os.path.join(coeff_save_dir, '%s##%s.mat'%(batch['pic_name'], batch['audio_name'])) - - def using_refpose(self, coeffs_pred_numpy, ref_pose_coeff_path): - num_frames = coeffs_pred_numpy.shape[0] - refpose_coeff_dict = loadmat(ref_pose_coeff_path) - refpose_coeff = refpose_coeff_dict['coeff_3dmm'][:,64:70] - refpose_num_frames = refpose_coeff.shape[0] - if refpose_num_frames None: - callback_fn.has_been_called = True - nonlocal number_of_steps - number_of_steps += 1 - if step == 1: - latents = latents.detach().cpu().numpy() - assert latents.shape == (1, 4, 64, 64) - latents_slice = latents[0, -3:, -3:, -1] - expected_slice = np.array( - [-0.1621, 0.2837, -0.7979, -0.1221, -1.3057, 0.7681, -2.1191, 0.0464, 1.6309] - ) - - assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2 - elif step == 2: - latents = latents.detach().cpu().numpy() - assert latents.shape == (1, 4, 64, 64) - latents_slice = latents[0, -3:, -3:, -1] - expected_slice = np.array([0.6299, 1.7500, 1.1992, -2.1582, -1.8994, 0.7334, -0.7090, 1.0137, 1.5273]) - - assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2 - - callback_fn.has_been_called = False - - pipe = StableDiffusionImageVariationPipeline.from_pretrained( - "fusing/sd-image-variations-diffusers", - safety_checker=None, - torch_dtype=torch.float16, - ) - pipe.to(torch_device) - pipe.set_progress_bar_config(disable=None) - pipe.enable_attention_slicing() - - inputs = self.get_inputs(torch_device, dtype=torch.float16) - pipe(**inputs, callback=callback_fn, callback_steps=1) - assert callback_fn.has_been_called - assert number_of_steps == inputs["num_inference_steps"] - - def test_stable_diffusion_pipeline_with_sequential_cpu_offloading(self): - torch.cuda.empty_cache() - torch.cuda.reset_max_memory_allocated() - torch.cuda.reset_peak_memory_stats() - - model_id = "fusing/sd-image-variations-diffusers" - pipe = StableDiffusionImageVariationPipeline.from_pretrained( - model_id, safety_checker=None, torch_dtype=torch.float16 - ) - pipe = pipe.to(torch_device) - pipe.set_progress_bar_config(disable=None) - pipe.enable_attention_slicing(1) - pipe.enable_sequential_cpu_offload() - - inputs = self.get_inputs(torch_device, dtype=torch.float16) - _ = pipe(**inputs) - - mem_bytes = torch.cuda.max_memory_allocated() - # make sure that less than 2.6 GB is allocated - assert mem_bytes < 2.6 * 10**9 - - -@nightly -@require_torch_gpu -class StableDiffusionImageVariationPipelineNightlyTests(unittest.TestCase): - def tearDown(self): - super().tearDown() - gc.collect() - torch.cuda.empty_cache() - - def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0): - generator = torch.Generator(device=generator_device).manual_seed(seed) - init_image = load_image( - "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" - "/stable_diffusion_imgvar/input_image_vermeer.png" - ) - latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64)) - latents = torch.from_numpy(latents).to(device=device, dtype=dtype) - inputs = { - "image": init_image, - "latents": latents, - "generator": generator, - "num_inference_steps": 50, - "guidance_scale": 7.5, - "output_type": "numpy", - } - return inputs - - def test_img_variation_pndm(self): - sd_pipe = StableDiffusionImageVariationPipeline.from_pretrained("fusing/sd-image-variations-diffusers") - sd_pipe.to(torch_device) - sd_pipe.set_progress_bar_config(disable=None) - - inputs = self.get_inputs(torch_device) - image = sd_pipe(**inputs).images[0] - - expected_image = load_numpy( - "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" - "/stable_diffusion_imgvar/lambdalabs_variations_pndm.npy" - ) - max_diff = np.abs(expected_image - image).max() - assert max_diff < 1e-3 - - def test_img_variation_dpm(self): - sd_pipe = StableDiffusionImageVariationPipeline.from_pretrained("fusing/sd-image-variations-diffusers") - sd_pipe.scheduler = DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config) - sd_pipe.to(torch_device) - sd_pipe.set_progress_bar_config(disable=None) - - inputs = self.get_inputs(torch_device) - inputs["num_inference_steps"] = 25 - image = sd_pipe(**inputs).images[0] - - expected_image = load_numpy( - "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" - "/stable_diffusion_imgvar/lambdalabs_variations_dpm_multi.npy" - ) - max_diff = np.abs(expected_image - image).max() - assert max_diff < 1e-3 diff --git a/spaces/Andy1621/uniformer_image_detection/configs/groie/mask_rcnn_r50_fpn_syncbn-backbone_r4_gcb_c3-c5_groie_1x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/groie/mask_rcnn_r50_fpn_syncbn-backbone_r4_gcb_c3-c5_groie_1x_coco.py deleted file mode 100644 index 852c5ca7c5c4ba04f6a5f7dd6dbaf6b2c357a2fa..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/groie/mask_rcnn_r50_fpn_syncbn-backbone_r4_gcb_c3-c5_groie_1x_coco.py +++ /dev/null @@ -1,45 +0,0 @@ -_base_ = '../gcnet/mask_rcnn_r50_fpn_syncbn-backbone_r4_gcb_c3-c5_1x_coco.py' -# model settings -model = dict( - roi_head=dict( - bbox_roi_extractor=dict( - type='GenericRoIExtractor', - aggregation='sum', - roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=2), - out_channels=256, - featmap_strides=[4, 8, 16, 32], - pre_cfg=dict( - type='ConvModule', - in_channels=256, - out_channels=256, - kernel_size=5, - padding=2, - inplace=False, - ), - post_cfg=dict( - type='GeneralizedAttention', - in_channels=256, - spatial_range=-1, - num_heads=6, - attention_type='0100', - kv_stride=2)), - mask_roi_extractor=dict( - type='GenericRoIExtractor', - roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=2), - out_channels=256, - featmap_strides=[4, 8, 16, 32], - pre_cfg=dict( - type='ConvModule', - in_channels=256, - out_channels=256, - kernel_size=5, - padding=2, - inplace=False, - ), - post_cfg=dict( - type='GeneralizedAttention', - in_channels=256, - spatial_range=-1, - num_heads=6, - attention_type='0100', - kv_stride=2)))) diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/apcnet_r50-d8.py b/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/apcnet_r50-d8.py deleted file mode 100644 index c8f5316cbcf3896ba9de7ca2c801eba512f01d5e..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/apcnet_r50-d8.py +++ /dev/null @@ -1,44 +0,0 @@ -# model settings -norm_cfg = dict(type='SyncBN', requires_grad=True) -model = dict( - type='EncoderDecoder', - pretrained='open-mmlab://resnet50_v1c', - backbone=dict( - type='ResNetV1c', - depth=50, - num_stages=4, - out_indices=(0, 1, 2, 3), - dilations=(1, 1, 2, 4), - strides=(1, 2, 1, 1), - norm_cfg=norm_cfg, - norm_eval=False, - style='pytorch', - contract_dilation=True), - decode_head=dict( - type='APCHead', - in_channels=2048, - in_index=3, - channels=512, - pool_scales=(1, 2, 3, 6), - dropout_ratio=0.1, - num_classes=19, - norm_cfg=dict(type='SyncBN', requires_grad=True), - align_corners=False, - loss_decode=dict( - type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), - auxiliary_head=dict( - type='FCNHead', - in_channels=1024, - in_index=2, - channels=256, - num_convs=1, - concat_input=False, - dropout_ratio=0.1, - num_classes=19, - 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='whole')) diff --git a/spaces/Andy1621/uniformer_image_segmentation/configs/gcnet/gcnet_r101-d8_512x512_160k_ade20k.py b/spaces/Andy1621/uniformer_image_segmentation/configs/gcnet/gcnet_r101-d8_512x512_160k_ade20k.py deleted file mode 100644 index 9888120f65b045df1c7d4d05fb010373abf82ccf..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_segmentation/configs/gcnet/gcnet_r101-d8_512x512_160k_ade20k.py +++ /dev/null @@ -1,2 +0,0 @@ -_base_ = './gcnet_r50-d8_512x512_160k_ade20k.py' -model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101)) diff --git a/spaces/ArtGAN/Video-Diffusion-WebUI/video_diffusion/stable_diffusion_video/stable_diffusion_pipeline.py b/spaces/ArtGAN/Video-Diffusion-WebUI/video_diffusion/stable_diffusion_video/stable_diffusion_pipeline.py deleted file mode 100644 index 34ac4676d3775fabc28ff3dd6f8932d6b7f13764..0000000000000000000000000000000000000000 --- a/spaces/ArtGAN/Video-Diffusion-WebUI/video_diffusion/stable_diffusion_video/stable_diffusion_pipeline.py +++ /dev/null @@ -1,848 +0,0 @@ -import inspect -import json -import math -import time -from pathlib import Path -from typing import Callable, List, Optional, Tuple, Union - -import numpy as np -import torch -from diffusers.configuration_utils import FrozenDict -from diffusers.models import AutoencoderKL, UNet2DConditionModel -from diffusers.pipeline_utils import DiffusionPipeline -from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput -from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker -from diffusers.schedulers import ( - DDIMScheduler, - DPMSolverMultistepScheduler, - EulerAncestralDiscreteScheduler, - EulerDiscreteScheduler, - LMSDiscreteScheduler, - PNDMScheduler, -) -from diffusers.utils import deprecate, logging -from packaging import version -from torch import nn -from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer - -from .upsampling import RealESRGANModel -from .utils import get_timesteps_arr, make_video_pyav, slerp - -logging.set_verbosity_info() -logger = logging.get_logger(__name__) - - -class StableDiffusionWalkPipeline(DiffusionPipeline): - r""" - Pipeline for generating videos by interpolating Stable Diffusion's latent space. - This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the - library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) - Args: - vae ([`AutoencoderKL`]): - Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. - text_encoder ([`CLIPTextModel`]): - Frozen text-encoder. Stable Diffusion uses the text portion of - [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically - the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. - tokenizer (`CLIPTokenizer`): - Tokenizer of class - [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). - unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. - scheduler ([`SchedulerMixin`]): - A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of - [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. - safety_checker ([`StableDiffusionSafetyChecker`]): - Classification module that estimates whether generated images could be considered offensive or harmful. - Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details. - feature_extractor ([`CLIPFeatureExtractor`]): - Model that extracts features from generated images to be used as inputs for the `safety_checker`. - """ - _optional_components = ["safety_checker", "feature_extractor"] - - def __init__( - self, - vae: AutoencoderKL, - text_encoder: CLIPTextModel, - tokenizer: CLIPTokenizer, - unet: UNet2DConditionModel, - scheduler: Union[ - DDIMScheduler, - PNDMScheduler, - LMSDiscreteScheduler, - EulerDiscreteScheduler, - EulerAncestralDiscreteScheduler, - DPMSolverMultistepScheduler, - ], - safety_checker: StableDiffusionSafetyChecker, - feature_extractor: CLIPFeatureExtractor, - requires_safety_checker: bool = True, - ): - super().__init__() - - if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: - deprecation_message = ( - f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" - f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " - "to update the config accordingly as leaving `steps_offset` might led to incorrect results" - " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," - " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" - " file" - ) - deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(scheduler.config) - new_config["steps_offset"] = 1 - scheduler._internal_dict = FrozenDict(new_config) - - if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: - deprecation_message = ( - f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." - " `clip_sample` should be set to False in the configuration file. Please make sure to update the" - " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" - " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" - " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" - ) - deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(scheduler.config) - new_config["clip_sample"] = False - scheduler._internal_dict = FrozenDict(new_config) - - if safety_checker is None and requires_safety_checker: - logger.warning( - f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" - " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" - " results in services or applications open to the public. Both the diffusers team and Hugging Face" - " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" - " it only for use-cases that involve analyzing network behavior or auditing its results. For more" - " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." - ) - - if safety_checker is not None and feature_extractor is None: - raise ValueError( - "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" - " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." - ) - - is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( - version.parse(unet.config._diffusers_version).base_version - ) < version.parse("0.9.0.dev0") - is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 - if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: - deprecation_message = ( - "The configuration file of the unet has set the default `sample_size` to smaller than" - " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the" - " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" - " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" - " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" - " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" - " in the config might lead to incorrect results in future versions. If you have downloaded this" - " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" - " the `unet/config.json` file" - ) - deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(unet.config) - new_config["sample_size"] = 64 - unet._internal_dict = FrozenDict(new_config) - - self.register_modules( - vae=vae, - text_encoder=text_encoder, - tokenizer=tokenizer, - unet=unet, - scheduler=scheduler, - safety_checker=safety_checker, - feature_extractor=feature_extractor, - ) - self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) - self.register_to_config(requires_safety_checker=requires_safety_checker) - - def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"): - r""" - Enable sliced attention computation. - When this option is enabled, the attention module will split the input tensor in slices, to compute attention - in several steps. This is useful to save some memory in exchange for a small speed decrease. - Args: - slice_size (`str` or `int`, *optional*, defaults to `"auto"`): - When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If - a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, - `attention_head_dim` must be a multiple of `slice_size`. - """ - if slice_size == "auto": - if isinstance(self.unet.config.attention_head_dim, int): - # half the attention head size is usually a good trade-off between - # speed and memory - slice_size = self.unet.config.attention_head_dim // 2 - else: - # if `attention_head_dim` is a list, take the smallest head size - slice_size = min(self.unet.config.attention_head_dim) - - self.unet.set_attention_slice(slice_size) - - def disable_attention_slicing(self): - r""" - Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go - back to computing attention in one step. - """ - # set slice_size = `None` to disable `attention slicing` - self.enable_attention_slicing(None) - - @torch.no_grad() - def __call__( - self, - prompt: Optional[Union[str, List[str]]] = None, - height: Optional[int] = None, - width: Optional[int] = None, - num_inference_steps: int = 50, - guidance_scale: float = 7.5, - negative_prompt: Optional[Union[str, List[str]]] = None, - num_images_per_prompt: Optional[int] = 1, - eta: float = 0.0, - generator: Optional[torch.Generator] = None, - latents: Optional[torch.FloatTensor] = None, - output_type: Optional[str] = "pil", - return_dict: bool = True, - callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, - callback_steps: Optional[int] = 1, - text_embeddings: Optional[torch.FloatTensor] = None, - **kwargs, - ): - r""" - Function invoked when calling the pipeline for generation. - Args: - prompt (`str` or `List[str]`, *optional*, defaults to `None`): - The prompt or prompts to guide the image generation. If not provided, `text_embeddings` is required. - height (`int`, *optional*, defaults to 512): - The height in pixels of the generated image. - width (`int`, *optional*, defaults to 512): - The width in pixels of the generated image. - num_inference_steps (`int`, *optional*, defaults to 50): - The number of denoising steps. More denoising steps usually lead to a higher quality image at the - expense of slower inference. - guidance_scale (`float`, *optional*, defaults to 7.5): - Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). - `guidance_scale` is defined as `w` of equation 2. of [Imagen - Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > - 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, - usually at the expense of lower image quality. - negative_prompt (`str` or `List[str]`, *optional*): - The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored - if `guidance_scale` is less than `1`). - num_images_per_prompt (`int`, *optional*, defaults to 1): - The number of images to generate per prompt. - eta (`float`, *optional*, defaults to 0.0): - Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to - [`schedulers.DDIMScheduler`], will be ignored for others. - generator (`torch.Generator`, *optional*): - A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation - deterministic. - latents (`torch.FloatTensor`, *optional*): - Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image - generation. Can be used to tweak the same generation with different prompts. If not provided, a latents - tensor will ge generated by sampling using the supplied random `generator`. - output_type (`str`, *optional*, defaults to `"pil"`): - The output format of the generate image. Choose between - [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. - return_dict (`bool`, *optional*, defaults to `True`): - Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a - plain tuple. - callback (`Callable`, *optional*): - A function that will be called every `callback_steps` steps during inference. The function will be - called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. - callback_steps (`int`, *optional*, defaults to 1): - The frequency at which the `callback` function will be called. If not specified, the callback will be - called at every step. - text_embeddings (`torch.FloatTensor`, *optional*, defaults to `None`): - Pre-generated text embeddings to be used as inputs for image generation. Can be used in place of - `prompt` to avoid re-computing the embeddings. If not provided, the embeddings will be generated from - the supplied `prompt`. - Returns: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. - When returning a tuple, the first element is a list with the generated images, and the second element is a - list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" - (nsfw) content, according to the `safety_checker`. - """ - # 0. Default height and width to unet - height = height or self.unet.config.sample_size * self.vae_scale_factor - width = width or self.unet.config.sample_size * self.vae_scale_factor - - if height % 8 != 0 or width % 8 != 0: - raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") - - if (callback_steps is None) or ( - callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) - ): - raise ValueError( - f"`callback_steps` has to be a positive integer but is {callback_steps} of type" - f" {type(callback_steps)}." - ) - - if text_embeddings is None: - if isinstance(prompt, str): - batch_size = 1 - elif isinstance(prompt, list): - batch_size = len(prompt) - else: - raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") - - # get prompt text embeddings - text_inputs = self.tokenizer( - prompt, - padding="max_length", - max_length=self.tokenizer.model_max_length, - return_tensors="pt", - ) - text_input_ids = text_inputs.input_ids - - if text_input_ids.shape[-1] > self.tokenizer.model_max_length: - removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]) - print( - "The following part of your input was truncated because CLIP can only handle sequences up to" - f" {self.tokenizer.model_max_length} tokens: {removed_text}" - ) - text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length] - text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0] - else: - batch_size = text_embeddings.shape[0] - - # duplicate text embeddings for each generation per prompt, using mps friendly method - bs_embed, seq_len, _ = text_embeddings.shape - text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1) - text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1) - - # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) - # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` - # corresponds to doing no classifier free guidance. - do_classifier_free_guidance = guidance_scale > 1.0 - # get unconditional embeddings for classifier free guidance - if do_classifier_free_guidance: - uncond_tokens: List[str] - if negative_prompt is None: - uncond_tokens = [""] - elif text_embeddings is None and type(prompt) is not type(negative_prompt): - raise TypeError( - f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" - f" {type(prompt)}." - ) - elif isinstance(negative_prompt, str): - uncond_tokens = [negative_prompt] - elif batch_size != len(negative_prompt): - raise ValueError( - f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" - f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" - " the batch size of `prompt`." - ) - else: - uncond_tokens = negative_prompt - - max_length = self.tokenizer.model_max_length - uncond_input = self.tokenizer( - uncond_tokens, - padding="max_length", - max_length=max_length, - truncation=True, - return_tensors="pt", - ) - uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0] - - # duplicate unconditional embeddings for each generation per prompt, using mps friendly method - seq_len = uncond_embeddings.shape[1] - uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1) - uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1) - - # For classifier free guidance, we need to do two forward passes. - # Here we concatenate the unconditional and text embeddings into a single batch - # to avoid doing two forward passes - text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) - - # get the initial random noise unless the user supplied it - - # Unlike in other pipelines, latents need to be generated in the target device - # for 1-to-1 results reproducibility with the CompVis implementation. - # However this currently doesn't work in `mps`. - latents_shape = ( - batch_size * num_images_per_prompt, - self.unet.in_channels, - height // 8, - width // 8, - ) - latents_dtype = text_embeddings.dtype - if latents is None: - if self.device.type == "mps": - # randn does not exist on mps - latents = torch.randn( - latents_shape, - generator=generator, - device="cpu", - dtype=latents_dtype, - ).to(self.device) - else: - latents = torch.randn( - latents_shape, - generator=generator, - device=self.device, - dtype=latents_dtype, - ) - else: - if latents.shape != latents_shape: - raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}") - latents = latents.to(self.device) - - # set timesteps - self.scheduler.set_timesteps(num_inference_steps) - - # Some schedulers like PNDM have timesteps as arrays - # It's more optimized to move all timesteps to correct device beforehand - timesteps_tensor = self.scheduler.timesteps.to(self.device) - - # scale the initial noise by the standard deviation required by the scheduler - latents = latents * self.scheduler.init_noise_sigma - - # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature - # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. - # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 - # and should be between [0, 1] - accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) - extra_step_kwargs = {} - if accepts_eta: - extra_step_kwargs["eta"] = eta - - for i, t in enumerate(self.progress_bar(timesteps_tensor)): - # expand the latents if we are doing classifier free guidance - latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents - latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) - - # predict the noise residual - noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample - - # perform guidance - if do_classifier_free_guidance: - noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) - noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) - - # compute the previous noisy sample x_t -> x_t-1 - latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample - - # call the callback, if provided - if callback is not None and i % callback_steps == 0: - callback(i, t, latents) - - latents = 1 / 0.18215 * latents - image = self.vae.decode(latents).sample - - image = (image / 2 + 0.5).clamp(0, 1) - - # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 - image = image.cpu().permute(0, 2, 3, 1).float().numpy() - - if self.safety_checker is not None: - safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(self.device) - image, has_nsfw_concept = self.safety_checker( - images=image, - clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype), - ) - else: - has_nsfw_concept = None - - if output_type == "pil": - image = self.numpy_to_pil(image) - - if not return_dict: - return (image, has_nsfw_concept) - - return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) - - def generate_inputs(self, prompt_a, prompt_b, seed_a, seed_b, noise_shape, T, batch_size): - embeds_a = self.embed_text(prompt_a) - embeds_b = self.embed_text(prompt_b) - latents_dtype = embeds_a.dtype - latents_a = self.init_noise(seed_a, noise_shape, latents_dtype) - latents_b = self.init_noise(seed_b, noise_shape, latents_dtype) - - batch_idx = 0 - embeds_batch, noise_batch = None, None - for i, t in enumerate(T): - embeds = torch.lerp(embeds_a, embeds_b, t) - noise = slerp(float(t), latents_a, latents_b) - - embeds_batch = embeds if embeds_batch is None else torch.cat([embeds_batch, embeds]) - noise_batch = noise if noise_batch is None else torch.cat([noise_batch, noise]) - batch_is_ready = embeds_batch.shape[0] == batch_size or i + 1 == T.shape[0] - if not batch_is_ready: - continue - yield batch_idx, embeds_batch, noise_batch - batch_idx += 1 - del embeds_batch, noise_batch - torch.cuda.empty_cache() - embeds_batch, noise_batch = None, None - - def make_clip_frames( - self, - prompt_a: str, - prompt_b: str, - seed_a: int, - seed_b: int, - num_interpolation_steps: int = 5, - save_path: Union[str, Path] = "outputs/", - num_inference_steps: int = 50, - guidance_scale: float = 7.5, - eta: float = 0.0, - height: Optional[int] = None, - width: Optional[int] = None, - upsample: bool = False, - batch_size: int = 1, - image_file_ext: str = ".png", - T: np.ndarray = None, - skip: int = 0, - negative_prompt: str = None, - step: Optional[Tuple[int, int]] = None, - ): - # 0. Default height and width to unet - height = height or self.unet.config.sample_size * self.vae_scale_factor - width = width or self.unet.config.sample_size * self.vae_scale_factor - - save_path = Path(save_path) - save_path.mkdir(parents=True, exist_ok=True) - - T = T if T is not None else np.linspace(0.0, 1.0, num_interpolation_steps) - if T.shape[0] != num_interpolation_steps: - raise ValueError(f"Unexpected T shape, got {T.shape}, expected dim 0 to be {num_interpolation_steps}") - - if upsample: - if getattr(self, "upsampler", None) is None: - self.upsampler = RealESRGANModel.from_pretrained("nateraw/real-esrgan") - self.upsampler.to(self.device) - - batch_generator = self.generate_inputs( - prompt_a, - prompt_b, - seed_a, - seed_b, - (1, self.unet.in_channels, height // 8, width // 8), - T[skip:], - batch_size, - ) - num_batches = math.ceil(num_interpolation_steps / batch_size) - - log_prefix = "" if step is None else f"[{step[0]}/{step[1]}] " - - frame_index = skip - for batch_idx, embeds_batch, noise_batch in batch_generator: - if batch_size == 1: - msg = f"Generating frame {frame_index}" - else: - msg = f"Generating frames {frame_index}-{frame_index+embeds_batch.shape[0]-1}" - logger.info(f"{log_prefix}[{batch_idx}/{num_batches}] {msg}") - outputs = self( - latents=noise_batch, - text_embeddings=embeds_batch, - height=height, - width=width, - guidance_scale=guidance_scale, - eta=eta, - num_inference_steps=num_inference_steps, - output_type="pil" if not upsample else "numpy", - negative_prompt=negative_prompt, - )["images"] - - for image in outputs: - frame_filepath = save_path / (f"frame%06d{image_file_ext}" % frame_index) - image = image if not upsample else self.upsampler(image) - image.save(frame_filepath) - frame_index += 1 - - def walk( - self, - prompts: Optional[List[str]] = None, - seeds: Optional[List[int]] = None, - num_interpolation_steps: Optional[Union[int, List[int]]] = 5, # int or list of int - output_dir: Optional[str] = "./dreams", - name: Optional[str] = None, - image_file_ext: Optional[str] = ".png", - fps: Optional[int] = 30, - num_inference_steps: Optional[int] = 50, - guidance_scale: Optional[float] = 7.5, - eta: Optional[float] = 0.0, - height: Optional[int] = None, - width: Optional[int] = None, - upsample: Optional[bool] = False, - batch_size: Optional[int] = 1, - resume: Optional[bool] = False, - audio_filepath: str = None, - audio_start_sec: Optional[Union[int, float]] = None, - margin: Optional[float] = 1.0, - smooth: Optional[float] = 0.0, - negative_prompt: Optional[str] = None, - make_video: Optional[bool] = True, - ): - """Generate a video from a sequence of prompts and seeds. Optionally, add audio to the - video to interpolate to the intensity of the audio. - Args: - prompts (Optional[List[str]], optional): - list of text prompts. Defaults to None. - seeds (Optional[List[int]], optional): - list of random seeds corresponding to prompts. Defaults to None. - num_interpolation_steps (Union[int, List[int]], *optional*): - How many interpolation steps between each prompt. Defaults to None. - output_dir (Optional[str], optional): - Where to save the video. Defaults to './dreams'. - name (Optional[str], optional): - Name of the subdirectory of output_dir. Defaults to None. - image_file_ext (Optional[str], *optional*, defaults to '.png'): - The extension to use when writing video frames. - fps (Optional[int], *optional*, defaults to 30): - The frames per second in the resulting output videos. - num_inference_steps (Optional[int], *optional*, defaults to 50): - The number of denoising steps. More denoising steps usually lead to a higher quality image at the - expense of slower inference. - guidance_scale (Optional[float], *optional*, defaults to 7.5): - Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). - `guidance_scale` is defined as `w` of equation 2. of [Imagen - Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > - 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, - usually at the expense of lower image quality. - eta (Optional[float], *optional*, defaults to 0.0): - Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to - [`schedulers.DDIMScheduler`], will be ignored for others. - height (Optional[int], *optional*, defaults to None): - height of the images to generate. - width (Optional[int], *optional*, defaults to None): - width of the images to generate. - upsample (Optional[bool], *optional*, defaults to False): - When True, upsamples images with realesrgan. - batch_size (Optional[int], *optional*, defaults to 1): - Number of images to generate at once. - resume (Optional[bool], *optional*, defaults to False): - When True, resumes from the last frame in the output directory based - on available prompt config. Requires you to provide the `name` argument. - audio_filepath (str, *optional*, defaults to None): - Optional path to an audio file to influence the interpolation rate. - audio_start_sec (Optional[Union[int, float]], *optional*, defaults to 0): - Global start time of the provided audio_filepath. - margin (Optional[float], *optional*, defaults to 1.0): - Margin from librosa hpss to use for audio interpolation. - smooth (Optional[float], *optional*, defaults to 0.0): - Smoothness of the audio interpolation. 1.0 means linear interpolation. - negative_prompt (Optional[str], *optional*, defaults to None): - Optional negative prompt to use. Same across all prompts. - make_video (Optional[bool], *optional*, defaults to True): - When True, makes a video from the generated frames. If False, only - generates the frames. - This function will create sub directories for each prompt and seed pair. - For example, if you provide the following prompts and seeds: - ``` - prompts = ['a dog', 'a cat', 'a bird'] - seeds = [1, 2, 3] - num_interpolation_steps = 5 - output_dir = 'output_dir' - name = 'name' - fps = 5 - ``` - Then the following directories will be created: - ``` - output_dir - ├── name - │ ├── name_000000 - │ │ ├── frame000000.png - │ │ ├── ... - │ │ ├── frame000004.png - │ │ ├── name_000000.mp4 - │ ├── name_000001 - │ │ ├── frame000000.png - │ │ ├── ... - │ │ ├── frame000004.png - │ │ ├── name_000001.mp4 - │ ├── ... - │ ├── name.mp4 - | |── prompt_config.json - ``` - Returns: - str: The resulting video filepath. This video includes all sub directories' video clips. - """ - # 0. Default height and width to unet - height = height or self.unet.config.sample_size * self.vae_scale_factor - width = width or self.unet.config.sample_size * self.vae_scale_factor - - output_path = Path(output_dir) - - name = name or time.strftime("%Y%m%d-%H%M%S") - save_path_root = output_path / name - save_path_root.mkdir(parents=True, exist_ok=True) - - # Where the final video of all the clips combined will be saved - output_filepath = save_path_root / f"{name}.mp4" - - # If using same number of interpolation steps between, we turn into list - if not resume and isinstance(num_interpolation_steps, int): - num_interpolation_steps = [num_interpolation_steps] * (len(prompts) - 1) - - if not resume: - audio_start_sec = audio_start_sec or 0 - - # Save/reload prompt config - prompt_config_path = save_path_root / "prompt_config.json" - if not resume: - prompt_config_path.write_text( - json.dumps( - dict( - prompts=prompts, - seeds=seeds, - num_interpolation_steps=num_interpolation_steps, - fps=fps, - num_inference_steps=num_inference_steps, - guidance_scale=guidance_scale, - eta=eta, - upsample=upsample, - height=height, - width=width, - audio_filepath=audio_filepath, - audio_start_sec=audio_start_sec, - negative_prompt=negative_prompt, - ), - indent=2, - sort_keys=False, - ) - ) - else: - data = json.load(open(prompt_config_path)) - prompts = data["prompts"] - seeds = data["seeds"] - num_interpolation_steps = data["num_interpolation_steps"] - fps = data["fps"] - num_inference_steps = data["num_inference_steps"] - guidance_scale = data["guidance_scale"] - eta = data["eta"] - upsample = data["upsample"] - height = data["height"] - width = data["width"] - audio_filepath = data["audio_filepath"] - audio_start_sec = data["audio_start_sec"] - negative_prompt = data.get("negative_prompt", None) - - for i, (prompt_a, prompt_b, seed_a, seed_b, num_step) in enumerate( - zip(prompts, prompts[1:], seeds, seeds[1:], num_interpolation_steps) - ): - # {name}_000000 / {name}_000001 / ... - save_path = save_path_root / f"{name}_{i:06d}" - - # Where the individual clips will be saved - step_output_filepath = save_path / f"{name}_{i:06d}.mp4" - - # Determine if we need to resume from a previous run - skip = 0 - if resume: - if step_output_filepath.exists(): - print(f"Skipping {save_path} because frames already exist") - continue - - existing_frames = sorted(save_path.glob(f"*{image_file_ext}")) - if existing_frames: - skip = int(existing_frames[-1].stem[-6:]) + 1 - if skip + 1 >= num_step: - print(f"Skipping {save_path} because frames already exist") - continue - print(f"Resuming {save_path.name} from frame {skip}") - - audio_offset = audio_start_sec + sum(num_interpolation_steps[:i]) / fps - audio_duration = num_step / fps - - self.make_clip_frames( - prompt_a, - prompt_b, - seed_a, - seed_b, - num_interpolation_steps=num_step, - save_path=save_path, - num_inference_steps=num_inference_steps, - guidance_scale=guidance_scale, - eta=eta, - height=height, - width=width, - upsample=upsample, - batch_size=batch_size, - T=get_timesteps_arr( - audio_filepath, - offset=audio_offset, - duration=audio_duration, - fps=fps, - margin=margin, - smooth=smooth, - ) - if audio_filepath - else None, - skip=skip, - negative_prompt=negative_prompt, - step=(i, len(prompts) - 1), - ) - if make_video: - make_video_pyav( - save_path, - audio_filepath=audio_filepath, - fps=fps, - output_filepath=step_output_filepath, - glob_pattern=f"*{image_file_ext}", - audio_offset=audio_offset, - audio_duration=audio_duration, - sr=44100, - ) - if make_video: - return make_video_pyav( - save_path_root, - audio_filepath=audio_filepath, - fps=fps, - audio_offset=audio_start_sec, - audio_duration=sum(num_interpolation_steps) / fps, - output_filepath=output_filepath, - glob_pattern=f"**/*{image_file_ext}", - sr=44100, - ) - - def embed_text(self, text, negative_prompt=None): - """Helper to embed some text""" - text_input = self.tokenizer( - text, - padding="max_length", - max_length=self.tokenizer.model_max_length, - truncation=True, - return_tensors="pt", - ) - with torch.no_grad(): - embed = self.text_encoder(text_input.input_ids.to(self.device))[0] - return embed - - def init_noise(self, seed, noise_shape, dtype): - """Helper to initialize noise""" - # randn does not exist on mps, so we create noise on CPU here and move it to the device after initialization - if self.device.type == "mps": - noise = torch.randn( - noise_shape, - device="cpu", - generator=torch.Generator(device="cpu").manual_seed(seed), - ).to(self.device) - else: - noise = torch.randn( - noise_shape, - device=self.device, - generator=torch.Generator(device=self.device).manual_seed(seed), - dtype=dtype, - ) - return noise - - @classmethod - def from_pretrained(cls, *args, tiled=False, **kwargs): - """Same as diffusers `from_pretrained` but with tiled option, which makes images tilable""" - if tiled: - - def patch_conv(**patch): - cls = nn.Conv2d - init = cls.__init__ - - def __init__(self, *args, **kwargs): - return init(self, *args, **kwargs, **patch) - - cls.__init__ = __init__ - - patch_conv(padding_mode="circular") - - pipeline = super().from_pretrained(*args, **kwargs) - pipeline.tiled = tiled - return pipeline diff --git a/spaces/Arulkumar03/GroundingDINO_SOTA_Zero_Shot_Model/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h b/spaces/Arulkumar03/GroundingDINO_SOTA_Zero_Shot_Model/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h deleted file mode 100644 index ad1311a78f61303616504eb991aaa9c4a93d9948..0000000000000000000000000000000000000000 --- a/spaces/Arulkumar03/GroundingDINO_SOTA_Zero_Shot_Model/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h +++ /dev/null @@ -1,33 +0,0 @@ -/*! -************************************************************************************************** -* Deformable DETR -* Copyright (c) 2020 SenseTime. All Rights Reserved. -* Licensed under the Apache License, Version 2.0 [see LICENSE for details] -************************************************************************************************** -* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0 -************************************************************************************************** -*/ - -#pragma once -#include - -namespace groundingdino { - -at::Tensor ms_deform_attn_cuda_forward( - const at::Tensor &value, - const at::Tensor &spatial_shapes, - const at::Tensor &level_start_index, - const at::Tensor &sampling_loc, - const at::Tensor &attn_weight, - const int im2col_step); - -std::vector ms_deform_attn_cuda_backward( - const at::Tensor &value, - const at::Tensor &spatial_shapes, - const at::Tensor &level_start_index, - const at::Tensor &sampling_loc, - const at::Tensor &attn_weight, - const at::Tensor &grad_output, - const int im2col_step); - -} // namespace groundingdino \ No newline at end of file diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/metadata/_json.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/metadata/_json.py deleted file mode 100644 index 336b52f1efddbcaeb6716583fc2f043699e278fa..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/metadata/_json.py +++ /dev/null @@ -1,84 +0,0 @@ -# Extracted from https://github.com/pfmoore/pkg_metadata - -from email.header import Header, decode_header, make_header -from email.message import Message -from typing import Any, Dict, List, Union - -METADATA_FIELDS = [ - # Name, Multiple-Use - ("Metadata-Version", False), - ("Name", False), - ("Version", False), - ("Dynamic", True), - ("Platform", True), - ("Supported-Platform", True), - ("Summary", False), - ("Description", False), - ("Description-Content-Type", False), - ("Keywords", False), - ("Home-page", False), - ("Download-URL", False), - ("Author", False), - ("Author-email", False), - ("Maintainer", False), - ("Maintainer-email", False), - ("License", False), - ("Classifier", True), - ("Requires-Dist", True), - ("Requires-Python", False), - ("Requires-External", True), - ("Project-URL", True), - ("Provides-Extra", True), - ("Provides-Dist", True), - ("Obsoletes-Dist", True), -] - - -def json_name(field: str) -> str: - return field.lower().replace("-", "_") - - -def msg_to_json(msg: Message) -> Dict[str, Any]: - """Convert a Message object into a JSON-compatible dictionary.""" - - def sanitise_header(h: Union[Header, str]) -> str: - if isinstance(h, Header): - chunks = [] - for bytes, encoding in decode_header(h): - if encoding == "unknown-8bit": - try: - # See if UTF-8 works - bytes.decode("utf-8") - encoding = "utf-8" - except UnicodeDecodeError: - # If not, latin1 at least won't fail - encoding = "latin1" - chunks.append((bytes, encoding)) - return str(make_header(chunks)) - return str(h) - - result = {} - for field, multi in METADATA_FIELDS: - if field not in msg: - continue - key = json_name(field) - if multi: - value: Union[str, List[str]] = [ - sanitise_header(v) for v in msg.get_all(field) - ] - else: - value = sanitise_header(msg.get(field)) - if key == "keywords": - # Accept both comma-separated and space-separated - # forms, for better compatibility with old data. - if "," in value: - value = [v.strip() for v in value.split(",")] - else: - value = value.split() - result[key] = value - - payload = msg.get_payload() - if payload: - result["description"] = payload - - return result diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/rich/_pick.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/rich/_pick.py deleted file mode 100644 index 4f6d8b2d79406012c5f8bae9c289ed5bf4d179cc..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/rich/_pick.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Optional - - -def pick_bool(*values: Optional[bool]) -> bool: - """Pick the first non-none bool or return the last value. - - Args: - *values (bool): Any number of boolean or None values. - - Returns: - bool: First non-none boolean. - """ - assert values, "1 or more values required" - for value in values: - if value is not None: - return value - return bool(value) diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/py36compat.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/py36compat.py deleted file mode 100644 index 343547a4d316e48144ba6bdf342dcc24cd6cb6cd..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/py36compat.py +++ /dev/null @@ -1,134 +0,0 @@ -import os -from glob import glob -from distutils.util import convert_path -from distutils.command import sdist - - -class sdist_add_defaults: - """ - Mix-in providing forward-compatibility for functionality as found in - distutils on Python 3.7. - - Do not edit the code in this class except to update functionality - as implemented in distutils. Instead, override in the subclass. - """ - - def add_defaults(self): - """Add all the default files to self.filelist: - - README or README.txt - - setup.py - - test/test*.py - - all pure Python modules mentioned in setup script - - all files pointed by package_data (build_py) - - all files defined in data_files. - - all files defined as scripts. - - all C sources listed as part of extensions or C libraries - in the setup script (doesn't catch C headers!) - Warns if (README or README.txt) or setup.py are missing; everything - else is optional. - """ - self._add_defaults_standards() - self._add_defaults_optional() - self._add_defaults_python() - self._add_defaults_data_files() - self._add_defaults_ext() - self._add_defaults_c_libs() - self._add_defaults_scripts() - - @staticmethod - def _cs_path_exists(fspath): - """ - Case-sensitive path existence check - - >>> sdist_add_defaults._cs_path_exists(__file__) - True - >>> sdist_add_defaults._cs_path_exists(__file__.upper()) - False - """ - if not os.path.exists(fspath): - return False - # make absolute so we always have a directory - abspath = os.path.abspath(fspath) - directory, filename = os.path.split(abspath) - return filename in os.listdir(directory) - - def _add_defaults_standards(self): - standards = [self.READMES, self.distribution.script_name] - for fn in standards: - if isinstance(fn, tuple): - alts = fn - got_it = False - for fn in alts: - if self._cs_path_exists(fn): - got_it = True - self.filelist.append(fn) - break - - if not got_it: - self.warn("standard file not found: should have one of " + - ', '.join(alts)) - else: - if self._cs_path_exists(fn): - self.filelist.append(fn) - else: - self.warn("standard file '%s' not found" % fn) - - def _add_defaults_optional(self): - optional = ['test/test*.py', 'setup.cfg'] - for pattern in optional: - files = filter(os.path.isfile, glob(pattern)) - self.filelist.extend(files) - - def _add_defaults_python(self): - # build_py is used to get: - # - python modules - # - files defined in package_data - build_py = self.get_finalized_command('build_py') - - # getting python files - if self.distribution.has_pure_modules(): - self.filelist.extend(build_py.get_source_files()) - - # getting package_data files - # (computed in build_py.data_files by build_py.finalize_options) - for pkg, src_dir, build_dir, filenames in build_py.data_files: - for filename in filenames: - self.filelist.append(os.path.join(src_dir, filename)) - - def _add_defaults_data_files(self): - # getting distribution.data_files - if self.distribution.has_data_files(): - for item in self.distribution.data_files: - if isinstance(item, str): - # plain file - item = convert_path(item) - if os.path.isfile(item): - self.filelist.append(item) - else: - # a (dirname, filenames) tuple - dirname, filenames = item - for f in filenames: - f = convert_path(f) - if os.path.isfile(f): - self.filelist.append(f) - - def _add_defaults_ext(self): - if self.distribution.has_ext_modules(): - build_ext = self.get_finalized_command('build_ext') - self.filelist.extend(build_ext.get_source_files()) - - def _add_defaults_c_libs(self): - if self.distribution.has_c_libraries(): - build_clib = self.get_finalized_command('build_clib') - self.filelist.extend(build_clib.get_source_files()) - - def _add_defaults_scripts(self): - if self.distribution.has_scripts(): - build_scripts = self.get_finalized_command('build_scripts') - self.filelist.extend(build_scripts.get_source_files()) - - -if hasattr(sdist.sdist, '_add_defaults_standards'): - # disable the functionality already available upstream - class sdist_add_defaults: # noqa - pass diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ.py b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ.py deleted file mode 100644 index ef0b6d16d4403fb5d16a3aeb71a22621a0be5e21..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ.py +++ /dev/null @@ -1,29 +0,0 @@ -from .mask_rcnn_R_50_FPN_100ep_LSJ import ( - dataloader, - lr_multiplier, - model, - optimizer, - train, -) -from detectron2.config import LazyCall as L -from detectron2.modeling.backbone import RegNet -from detectron2.modeling.backbone.regnet import SimpleStem, ResBottleneckBlock - -# Config source: -# https://github.com/facebookresearch/detectron2/blob/main/configs/COCO-InstanceSegmentation/mask_rcnn_regnetx_4gf_dds_fpn_1x.py # noqa -model.backbone.bottom_up = L(RegNet)( - stem_class=SimpleStem, - stem_width=32, - block_class=ResBottleneckBlock, - depth=23, - w_a=38.65, - w_0=96, - w_m=2.43, - group_width=40, - norm="SyncBN", - out_features=["s1", "s2", "s3", "s4"], -) -model.pixel_std = [57.375, 57.120, 58.395] - -# RegNets benefit from enabling cudnn benchmark mode -train.cudnn_benchmark = True diff --git a/spaces/BREWDAcademy/Brewd-Diffusion/style.css b/spaces/BREWDAcademy/Brewd-Diffusion/style.css deleted file mode 100644 index d4e49cdac816cc36a98e7c7664c2adc40ab4b488..0000000000000000000000000000000000000000 --- a/spaces/BREWDAcademy/Brewd-Diffusion/style.css +++ /dev/null @@ -1,77 +0,0 @@ -/* Main background and font styles to fit the steampunk/parchment theme */ -body { - background-color: #f5f5dc; /* Parchment color */ - font-family: 'IM Fell English SC', serif; /* Steampunk-inspired font */ - color: #3a2e22; /* Dark brown text color */ -} - -/* Style for header element with class 'pretty' */ -.pretty h1 { - text-align: center; - font-family: 'IM Fell English SC', serif; /* Steampunk font */ - color: #806c50; /* Muted brown color */ -} - -/* Style for button element with ID 'duplicate-button' */ -#duplicate-button { - margin: auto; - color: #efe0c9; /* Light parchment color */ - background-color: #806c50; /* Leather-like brown */ - border-radius: 4px; /* Less roundness for a more vintage look */ - cursor: pointer; - padding: 10px 20px; - border: none; - font-size: 1em; -} - -/* Style for the Gradio interface elements to match the steampunk theme */ -.gradio_container { - background-color: #f2e5bc; /* Light beige for input areas */ - border: 1px solid #9e7053; /* Darker border to stand out on parchment */ -} - -/* Style for gallery/result container */ -.gr-gallery { - background-color: #fff; /* Clean white for results to stand out */ - border: 2px solid #9e7053; /* A darker border for contrast */ -} - -/* Style for input text and text areas */ -input[type='text'], textarea { - background-color: #f2e5bc; /* Light beige, like old paper */ - color: #3a2e22; /* Dark brown text color */ - border: 1px solid #9e7053; /* Leather-like border */ -} - -/* Style for sliders */ -input[type='range'] { - background: #806c50; /* A leather-like slider background */ -} - -/* Style for radio buttons and checkboxes */ -input[type='radio'], input[type='checkbox'] { - accent-color: #806c50; /* Leather-like accent color */ -} - -/* Adjust the style for buttons in the interface */ -button { - background-color: #806c50; /* Leather-like brown */ - color: #efe0c9; /* Parchment color text */ - border: none; /* Remove default border */ -} - -/* Style adjustments for the accordion */ -.gr-accordion { - background-color: #f2e5bc; /* Light beige */ - color: #3a2e22; /* Dark brown text color */ -} - -/* Ensure links match the theme as well */ -a { - color: #3a2e22; /* Dark brown, similar to the text */ -} - -/* Style for the progress bar */ -.gr-progress-bar { - background-color: #c0a080; /* A muted brown progress bar */ -} diff --git a/spaces/Benson/text-generation/Examples/Coche De Carreras Juego De Configuracin Para Pc Windows 7.md b/spaces/Benson/text-generation/Examples/Coche De Carreras Juego De Configuracin Para Pc Windows 7.md deleted file mode 100644 index 37dc44f1230514b3ee610373c5c3905c18a7c2fc..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Coche De Carreras Juego De Configuracin Para Pc Windows 7.md +++ /dev/null @@ -1,85 +0,0 @@ - -

Configuración del juego de carreras de coches Descargar para PC Windows 7

-

Si eres un fan de la velocidad, la adrenalina y la emoción, es posible que te interese jugar juegos de carreras de coches. Los juegos de carreras de autos son videojuegos que simulan conducir un vehículo en una pista, una carretera o un terreno todoterreno. Pueden ser realistas, árcade o futuristas, dependiendo del estilo y el tema del juego. Los juegos de carreras de coches son populares entre los jugadores de todas las edades y preferencias, ya que ofrecen una variedad de desafíos, modos, vehículos y entornos para elegir.

-

Una de las ventajas de jugar juegos de carreras de coches es que se puede disfrutar de ellos en diferentes plataformas, incluyendo PC Windows 7. PC Windows 7 es un sistema operativo confiable y compatible que puede ejecutar muchos juegos de carreras de coches sin problemas y de manera eficiente. Jugar juegos de carreras de coches en PC Windows 7 también le da más control sobre la configuración, los gráficos y el rendimiento del juego. También puede utilizar diferentes dispositivos de entrada, como un teclado, un ratón, un joystick o un volante, para mejorar su experiencia de juego.

-

coche de carreras juego de configuración para pc windows 7


Download Ziphttps://bltlly.com/2v6Mln



-

Pero ¿cómo encontrar y jugar juegos de carreras de coches en PC Windows 7? Hay muchas fuentes donde se puede descargar juegos de carreras de coches para PC Windows 7, tales como sitios web oficiales, tiendas en línea, o plataformas de terceros. Sin embargo, debes tener cuidado con la calidad, seguridad y legalidad de los archivos de juego que descargas. También debe seguir las instrucciones para instalar y ejecutar el juego en su PC Windows 7.

-

En este artículo, le presentaremos algunos de los mejores juegos de carreras de coches para PC Windows 7 que puede descargar y jugar. También le proporcionaremos información sobre sus características, pros y contras, y cómo descargarlos e instalarlos en su PC Windows 7. ¡Comencemos!

-

BeamNG.drive

-

¿Qué es BeamNG.drive y cuáles son sus características?

- -

BeamNG.drive no es solo un juego de carreras de coches, sino también un juego de caja de arena que le permite experimentar con diferentes situaciones y resultados. Puede estrellar sus vehículos contra paredes, árboles, edificios u otros vehículos, y ver cómo se deforman y se rompen. También puedes probar tus habilidades de conducción en varios desafíos, como pruebas de tiempo, cursos de acrobacias, persecuciones policiales o aventuras fuera de la carretera

. También puedes jugar con tus amigos online o offline en modo multijugador.

-

Cómo descargar e instalar BeamNG.drive en PC Windows 7?

-

Para descargar e instalar BeamNG.drive en PC Windows 7, debe seguir estos pasos:

-
    -
  1. Vaya al sitio web oficial de BeamNG.drive y haga clic en el botón "Comprar ahora". Serás redirigido a la tienda de Steam, donde puedes comprar el juego por $24.99.
  2. -
  3. Después de comprar el juego, necesita descargar e instalar Steam en su PC Windows 7. Steam es una plataforma de distribución digital que le permite administrar sus juegos y acceder a las funciones en línea.
  4. -
  5. Una vez que haya instalado Steam, inicie sesión con su cuenta. Luego, vaya a su biblioteca y busque BeamNG.drive. Haga clic en el botón "Instalar" y espere a que el juego se descargue e instale en su PC Windows 7.
  6. -
  7. Después de que la instalación se haya completado, puede iniciar el juego desde Steam o desde el acceso directo de su escritorio. Disfrute!
  8. -
-

Pros y contras de BeamNG.drive

-

BeamNG.drive es un divertido y realista juego de simulación de vehículos que ofrece muchas posibilidades y libertad. Sin embargo, también tiene algunos inconvenientes que debe tener en cuenta. Estos son algunos de los pros y contras de BeamNG.drive:

- -ProsContras -- Increíbles gráficos y física que hacen que los vehículos y entornos se vean y se sientan reales. - Altos requisitos del sistema que pueden no funcionar bien en PC más viejos o más débiles. - -- Una comunidad creativa y activa que crea y comparte nuevos contenidos y comentarios. - Falta de una historia clara u objetivos que puedan hacer que el juego sea aburrido o repetitivo para algunos jugadores. -- Un modo multijugador que te permite jugar con tus amigos online o offline. - Algunos errores y fallos que pueden afectar el juego o el rendimiento del juego. - -

Necesidad de velocidad

-

¿Cuál es la necesidad de velocidad y cuáles son sus características?

-

Need for Speed es una de las franquicias de juegos de carreras de coches más populares y exitosas del mundo. Ha existido desde 1994 y ha lanzado más de 20 títulos en diferentes plataformas. Los juegos de Need for Speed son conocidos por su ritmo rápido, estilo árcade y juego de carreras callejeras. También cuentan con una variedad de coches, pistas, modos, opciones de personalización e historias.

-

-

Uno de los mejores juegos de Need for Speed para PC Windows 7 es Need for Speed: Most Wanted (2012). Este juego es un reinicio de la original Need for Speed: Most Wanted (2005) y se desarrolla en una ciudad de mundo abierto llamada Fairhaven. Juegas como un corredor callejero que tiene que competir con otros corredores, evadir a la policía y desafiar a la lista de los más buscados. Puedes conducir cualquier coche que veas en la ciudad, desde coches deportivos exóticos hasta coches deportivos y todoterrenos. También puede actualizar sus coches con piezas de rendimiento, trabajos de pintura, vinilos, matrículas y más. También puedes participar en diferentes eventos, como carreras, persecuciones, carreras de velocidad, emboscadas o hitos.

-

¿Cómo descargar e instalar Necesidad de velocidad en PC Windows 7?

-

Para descargar e instalar Need for Speed: Most Wanted (2012) en PC Windows 7, debe seguir estos pasos:

-
    -
  1. Ir al sitio web oficial de Need for Speed: Most Wanted (2012) y haga clic en el botón "Comprar ahora". Serás redirigido a la tienda de Origin, donde puedes comprar el juego por $19.99.
  2. - -
  3. Una vez que tenga Origin instalado, ejecútelo e inicie sesión con su cuenta. Luego, vaya a su biblioteca y encuentre Need for Speed: Most Wanted (2012). Haga clic en el botón "Descargar" y espere a que el juego se descargue e instale en su PC Windows 7.
  4. -
  5. Después de que la instalación se haya completado, puede iniciar el juego desde Origin o desde el acceso directo de su escritorio. Disfrute!
  6. -
-

Pros y contras de la necesidad de velocidad

-

Need for Speed: Most Wanted (2012) es un emocionante y adictivo juego de carreras de coches que ofrece mucha acción y diversión. Sin embargo, también tiene algunos inconvenientes que debes tener en cuenta. Estos son algunos de los pros y contras de Need for Speed: Most Wanted (2012):

- -ProsContras -- Impresionantes gráficos y efectos de sonido que hacen que la ciudad y los coches se ven y suenan increíble. - Altos requisitos del sistema que pueden no funcionar bien en PC más viejos o más débiles. -- Una gran y diversa ciudad de mundo abierto que puedes explorar y descubrir. - Una historia repetitiva y superficial que puede no atraer a algunos jugadores. -- Una gran selección de coches, opciones de personalización y eventos para elegir. - La falta de una opción de transmisión manual que puede decepcionar a algunos corredores hardcore. -- Un modo multijugador que te permite jugar con tus amigos online o offline. - Algunos errores y fallos que pueden afectar el juego o el rendimiento del juego. - -

Carreras de la ciudad

-

¿Qué es City Racing y cuáles son sus características?

-

City Racing es un juego de carreras de coches gratis que te permite conducir por una gran ciudad y competir con otros corredores. Puede elegir entre diferentes coches, desde sedanes hasta autos deportivos, y personalizarlos con diferentes colores, ruedas, spoilers y más. También puede actualizar sus coches con mejores motores, frenos, neumáticos y suspensión. También puede reparar sus coches cuando se dañan o se ensucian.

- -

¿Cómo descargar e instalar City Racing en PC Windows 7?

-

Para descargar e instalar City Racing en PC Windows 7, debe seguir estos pasos:

-
    -
  1. Ir a la página web oficial de City Racing y haga clic en el "Descargar" botón. Serás redirigido a una plataforma de terceros llamada GameTop, donde puedes descargar el juego gratis.
  2. -
  3. Después de descargar el archivo del juego, haga doble clic en él y siga el asistente de instalación. Es posible que necesite aceptar algunos términos y condiciones y elegir una carpeta de destino para el juego.
  4. -
  5. Después de la instalación se ha completado, puede iniciar el juego desde el acceso directo del escritorio o desde el menú de inicio. Disfrute!
  6. -
-

Pros y contras de City Racing

-

City Racing es un juego de carreras de coches divertido y gratuito que ofrece mucha variedad y emoción. Sin embargo, también tiene algunos inconvenientes que debes tener en cuenta. Estos son algunos de los pros y contras de City Racing:

- -ProsContras -- Gratis para descargar y jugar sin limitaciones o anuncios. - Gráficos y efectos de sonido de baja calidad que pueden no parecer o sonar atractivos. -- Una gran y diversa ciudad de mundo abierto que puedes explorar y disfrutar. - La falta de un mapa o un sistema GPS que puede dificultar la navegación o encontrar el camino. -- Una amplia gama de coches, opciones de personalización y carreras para elegir. - Un sistema de física poco realista y fácil que puede hacer la conducción demasiado simple o aburrido. -- Un modo multijugador que te permite jugar con tus amigos online o offline. - Algunos malware o virus que pueden venir con el archivo del juego o la plataforma de terceros. - -

Conclusión

- -

En este artículo, le hemos presentado algunos de los mejores juegos de carreras de coches para PC Windows 7 que puede descargar y jugar. También le hemos proporcionado alguna información sobre sus características, pros y contras, y cómo descargar e instalar confirmar que desea eliminar el juego de su PC. -

  • Siga las instrucciones y avisos que aparecen en la pantalla para completar el proceso de actualización o desinstalación.
  • - -

    ¿Dónde encontrar más juegos de carreras de coches para PC Windows 7?

    -

    Si está buscando más juegos de carreras de coches para PC Windows 7, puede consultar algunos de estos sitios web que ofrecen una variedad de juegos de forma gratuita o por una tarifa:

    -
      -
    • [GameTop]: Un sitio web que ofrece juegos de carreras de coches gratuitos y legales para PC Windows 7, como City Racing, Moto Racing y Super Bikes.
    • -
    • [Steam]: Un sitio web que ofrece una gran colección de juegos de carreras de coches para PC Windows 7, como BeamNG.drive, Assetto Corsa y Dirt Rally.
    • -
    • [Origin]: Un sitio web que ofrece algunos de los mejores juegos de carreras de coches para PC Windows 7, como Need for Speed, Burnout Paradise y Shift 2 Unleashed.
    • -
    • [GOG]: Un sitio web que ofrece juegos de carreras de coches clásicos y libres de DRM para PC Windows 7, como FlatOut, Carmageddon y Test Drive.
    • -

    64aa2da5cf
    -
    -
    \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Entre Nosotros Gamejolt.md b/spaces/Benson/text-generation/Examples/Descargar Entre Nosotros Gamejolt.md deleted file mode 100644 index 6eda80216b0c2f93ecb5695220b3d8996c724b20..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Entre Nosotros Gamejolt.md +++ /dev/null @@ -1,58 +0,0 @@ -
    -

    Cómo descargar entre nosotros desde GameJolt

    -

    Si está buscando un juego divertido y atractivo para jugar con sus amigos en línea, es posible que haya oído hablar de Among Us. Este es un juego multijugador donde tienes que trabajar junto con otros jugadores para arreglar una nave espacial mientras tratas de averiguar quién de ustedes es un impostor. En este artículo, explicaremos qué es Among Us, qué es GameJolt y cómo descargar e instalar Among Us desde GameJolt. También te daremos algunos consejos y trucos para jugar el juego y responder a algunas preguntas frecuentes.

    -

    descargar entre nosotros gamejolt


    Download ——— https://bltlly.com/2v6KXj



    -

    ¿Qué hay entre nosotros?

    -

    Among Us es un juego que fue lanzado en 2018 por Innersloth, un estudio de juegos estadounidense. El juego fue inspirado por el juego de fiesta Mafia y la película de terror de ciencia ficción The Thing. El juego permite el juego multiplataforma, lo que significa que puedes jugarlo en diferentes dispositivos como Android, iOS, Windows, Nintendo Switch, PlayStation o Xbox.

    -

    Un juego de deducción social en el espacio

    -

    El juego se lleva a cabo en el espacio con temas de configuración donde los jugadores son coloridos, astronautas de dibujos animados sin brazos. Cada jugador toma uno de dos roles: la mayoría son compañeros de equipo, pero un pequeño número son impostores. Los compañeros de equipo trabajan para completar las tareas asignadas en el juego mientras identifican y expulsan a los presuntos Impostores (que parecen idénticos a los Compañeros de Equipo) por medio de deducción social, mientras que los Impostores tienen el objetivo de matar a los Compañeros de Equipo o sabotear un sistema crítico en el mapa.

    -

    El juego puede ser jugado por cuatro a quince jugadores, con hasta tres impostores por ronda. Hay cuatro mapas jugables disponibles: una nave espacial llamada "The Skeld", un edificio de oficinas llamado "MIRA HQ", una base planetaria llamada "Polus" o "The Airship", una configuración de la serie de Innersloth Henry Stickmin.

    -

    ¿Por qué es tan popular?

    - -

    El juego es simple y al estilo de fiesta, con los jugadores asumiendo el papel de una persona del espacio de dibujos animados a bordo de una nave que necesita algunas reparaciones bastante urgentes. Es un juego sobre el trabajo en equipo, donde trabajan juntos para averiguar quién puede y no se puede confiar dentro del grupo de jugadores. Esto puede ser un beneficio, ya que ayuda a perfeccionar la lógica y las habilidades sociales de los niños, especialmente durante un momento en que los niños pueden estar atrapados en casa y necesitan socialización.

    -

    ¿Qué es GameJolt?

    -

    GameJolt es una plataforma para juegos indie, donde los desarrolladores pueden compartir sus creaciones con jugadores de todo el mundo. GameJolt alberga miles de juegos de varios géneros, como acción, aventura, terror, rompecabezas, simulación, estrategia y más. Puedes encontrar juegos gratuitos o de pago, completos o en desarrollo, para un jugador o multijugador.

    -

    Una plataforma para juegos indie

    -

    GameJolt fue fundada en 2004 por David DeCarmine como una forma de mostrar sus propios juegos. Desde entonces, se ha convertido en un sitio impulsado por la comunidad que apoya a los desarrolladores independientes y los jugadores por igual. GameJolt permite a los desarrolladores subir sus juegos, establecer sus propios precios, obtener ingresos de anuncios o donaciones , e interactuar con sus fans. GameJolt también cuenta con un sistema de clasificación, un sistema de trofeos, un sistema de chat, un foro y un blog para cada juego.

    -

    -

    Cómo crear una cuenta y navegar por los juegos

    -

    Para usar GameJolt, primero necesitas crear una cuenta. Puedes registrarte con tu dirección de correo electrónico o tus cuentas de redes sociales, como Facebook, Twitter o Google. Una vez que tenga una cuenta, puede personalizar su perfil, seguir sus juegos y desarrolladores favoritos, unirse a grupos y ganar trofeos y puntos XP.

    - -

    Cómo descargar e instalar Entre nosotros desde GameJolt

    -

    Ahora que sabes lo que entre nosotros y GameJolt son, vamos a ver cómo se puede descargar e instalar entre nosotros desde GameJolt. El proceso es simple y sencillo, pero debe asegurarse de que tiene un dispositivo compatible y suficiente espacio de almacenamiento. Estos son los pasos a seguir:

    -

    Paso 1: Encuentra el juego en GameJolt

    -

    El primer paso es encontrar el juego en GameJolt. Puedes usar este enlace para ir directamente a la página del juego: https://gamejolt.com/games/among-us/516139. Alternativamente, puede buscar "Entre nosotros" en el sitio web de GameJolt y buscar el juego con el logotipo oficial y el nombre del desarrollador "Innersloth".

    -

    En la página del juego, verá una breve descripción del juego, algunas capturas de pantalla y videos, la calificación y comentarios, y las opciones de descarga. También verás un botón que dice "Seguir" si quieres ser notificado de cualquier actualización o noticia sobre el juego.

    -

    Paso 2: Elija la versión y descargue el archivo

    -

    El siguiente paso es elegir la versión del juego que desea descargar. Hay dos versiones disponibles en GameJolt: una para Windows y otra para Android. La versión para Windows es de 57 MB y la versión para Android es de 70 MB. Asegúrese de que tiene suficiente espacio de almacenamiento en su dispositivo antes de descargar.

    -

    Para descargar el archivo, haga clic en el botón verde que dice "Descargar" junto a la versión que desee. Será redirigido a otra página donde verá un temporizador de cuenta atrás. Espere unos segundos hasta que el temporizador llegue a cero y luego haga clic en el botón azul que dice "Descargar ahora". El archivo comenzará a descargarse automáticamente.

    -

    Paso 3: Extraer el archivo y ejecutar el juego

    - -

    Una vez que haya extraído el archivo, verá una carpeta llamada "Entre nosotros". Ábrala y busque el archivo ejecutable que tiene el logotipo del juego. Haga doble clic en él para ejecutar el juego. Verá una ventana que le pide que elija su idioma. Seleccione su idioma preferido y haga clic en "Aceptar". El juego se iniciará y verás el menú principal.

    -

    Consejos y trucos para jugar entre nosotros

    -

    Felicidades! Usted ha descargado e instalado con éxito entre nosotros de GameJolt. Ahora usted está listo para jugar el juego con sus amigos u otros jugadores en línea. Pero antes de entrar en un juego, aquí hay algunos consejos y trucos que te ayudarán a disfrutar más del juego:

    -

    Cómo personalizar el carácter y la configuración

    -

    Antes de unirse o alojar un juego, puede personalizar su personaje y la configuración en el menú principal. Para personalizar tu personaje, haz clic en "Personalizar" en la esquina inferior derecha de la pantalla. Puede cambiar su nombre, color, sombrero, mascota, piel o atuendo haciendo clic en ellos. También puede usar flechas para desplazarse a través de diferentes opciones.

    -

    Para personalizar la configuración, haga clic en "Configuración" en la esquina inferior izquierda de la pantalla. Puede ajustar varias opciones como efectos de sonido, volumen de música, calidad de gráficos, resolución, modo de pantalla completa, idioma o tipo de chat haciendo clic en ellos. También puede usar deslizadores o botones para cambiar los valores. Para restablecer los valores predeterminados, haga clic en "Restablecer a Predeterminado" en la parte inferior de la pantalla.

    -

    Cómo unirse o organizar un juego en línea o localmente

    -

    Para unirse o alojar un juego en línea o localmente, haga clic en "Online" o "Local" en el menú principal. Si eliges "Online", puedes unirte a un juego público, crear un juego privado o introducir un código para unirte a un juego privado. Si eliges "Local", puedes alojar un juego o unirte a un juego alojado en la misma red Wi-Fi que tú.

    - -

    Cómo jugar como un compañero de equipo o un impostor

    -

    Una vez que comience el juego, serás asignado como Compañero de Equipo o Impostor. Su papel se mostrará en la pantalla junto con sus compañeros de equipo si usted es un impostor. También verás una lista de tareas que necesitas completar si eres un Crewmate.

    -

    Si usted es un compañero de equipo, su objetivo es completar sus tareas y averiguar quiénes son los impostores. Puede moverse por el mapa utilizando el joystick en el lado izquierdo de la pantalla e interactuar con los objetos utilizando el botón en el lado derecho de la pantalla. También puede usar respiraderos, cámaras, tabla de administración, signos vitales o registro de puertas para recopilar información. Puedes reportar un cadáver o llamar a una reunión de emergencia si encuentras algo sospechoso. A continuación, puede votar por quien cree que es un impostor o saltar la votación si no está seguro.

    -

    Si eres un impostor, tu objetivo es matar a todos los compañeros de equipo o sabotear un sistema crítico. Puedes moverte por el mapa e interactuar con objetos como un compañero de equipo, pero también tienes algunas habilidades especiales. Puedes usar los respiraderos para viajar rápida y discretamente, matar a los Compañeros de Tripulación cuando están solos o en grupos, y sabotear los sistemas para causar caos o distraer a los Compañeros de Equipo. También puede falsificar tareas, mentir y acusar a otros para evitar sospechas. Puede votar por quién desea eliminar o omitir el voto si desea mezclarse.

    -

    Conclusión y preguntas frecuentes

    -

    En conclusión, Entre nosotros es un juego divertido y atractivo que puedes jugar con tus amigos en línea o localmente. Puedes descargarlo e instalarlo desde GameJolt siguiendo los pasos que hemos explicado en este artículo. También puedes personalizar tu personaje y tu configuración, unirte o organizar un juego y jugar como Crewmate o Impostor. Esperamos que este artículo te haya ayudado a aprender más sobre Among Us y GameJolt y que disfrutes jugando el juego.

    -

    Aquí hay algunas preguntas frecuentes que puede tener sobre Among Us y GameJolt:

    -

    Q: ¿Cuánto cuesta Among Us en GameJolt?

    - -

    Q: ¿Puedo jugar entre nosotros con personas que tienen diferentes dispositivos?

    -

    A: Sí, puedes jugar entre nosotros con personas que tienen diferentes dispositivos, siempre y cuando tengan la misma versión del juego. El juego admite el juego multiplataforma entre dispositivos Android, iOS, Windows, Nintendo Switch, PlayStation y Xbox.

    -

    Q: ¿Cómo puedo actualizar entre nosotros en GameJolt?

    -

    A: Para actualizar entre nosotros en GameJolt, es necesario descargar e instalar la última versión del juego de GameJolt. Puedes comprobar si hay una nueva versión disponible visitando la página del juego en GameJolt y buscando actualizaciones o noticias de los desarrolladores.

    -

    Q: ¿Cómo puedo reportar errores o problemas con Among Us?

    -

    A: Si encuentra algún error o problema con Among Us, puede informar a los desarrolladores utilizando su dirección de correo electrónico oficial: support@innersloth.com. También puede utilizar su servidor de discordia: https://discord.gg/innersloth.

    -

    Q: ¿Cómo puedo encontrar más juegos como Entre nosotros en GameJolt?

    -

    A: Si te gusta Among Us y quieres encontrar más juegos como Among Us en GameJolt, puedes usar las etiquetas o los géneros para filtrar los juegos. Por ejemplo, puedes buscar juegos que tengan etiquetas como "multijugador", "deducción social", "misterio de asesinato", "espacio" o "horror". También puedes buscar juegos que pertenezcan a géneros como "acción", "aventura", "rompecabezas" o "simulación". También puede navegar por los juegos destacados, populares o de tendencia en GameJolt para descubrir juegos nuevos y emocionantes.

    64aa2da5cf
    -
    -
    \ No newline at end of file diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/chardet/langhungarianmodel.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/chardet/langhungarianmodel.py deleted file mode 100644 index 09a0d326b983b59b58f84b00e55fbe6909a23793..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/chardet/langhungarianmodel.py +++ /dev/null @@ -1,4649 +0,0 @@ -from pip._vendor.chardet.sbcharsetprober import SingleByteCharSetModel - -# 3: Positive -# 2: Likely -# 1: Unlikely -# 0: Negative - -HUNGARIAN_LANG_MODEL = { - 28: { # 'A' - 28: 0, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 2, # 'D' - 32: 1, # 'E' - 50: 1, # 'F' - 49: 2, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 2, # 'K' - 41: 2, # 'L' - 34: 1, # 'M' - 35: 2, # 'N' - 47: 1, # 'O' - 46: 2, # 'P' - 43: 2, # 'R' - 33: 2, # 'S' - 37: 2, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 2, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 2, # 'd' - 1: 1, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 1, # 'i' - 22: 1, # 'j' - 7: 2, # 'k' - 6: 2, # 'l' - 13: 2, # 'm' - 4: 2, # 'n' - 8: 0, # 'o' - 23: 2, # 'p' - 10: 2, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 1, # 'u' - 19: 1, # 'v' - 62: 1, # 'x' - 16: 0, # 'y' - 11: 3, # 'z' - 51: 1, # 'Á' - 44: 0, # 'É' - 61: 1, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 40: { # 'B' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 0, # 'M' - 35: 1, # 'N' - 47: 2, # 'O' - 46: 0, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 3, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 2, # 'i' - 22: 1, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 3, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 0, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 54: { # 'C' - 28: 1, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 1, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 0, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 2, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 0, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 1, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 1, # 'h' - 9: 1, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 3, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 1, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 45: { # 'D' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 0, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 0, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 2, # 'O' - 46: 0, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 3, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 1, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 1, # 'o' - 23: 0, # 'p' - 10: 2, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 2, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 1, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 0, # 'ű' - }, - 32: { # 'E' - 28: 1, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 1, # 'E' - 50: 1, # 'F' - 49: 2, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 2, # 'K' - 41: 2, # 'L' - 34: 2, # 'M' - 35: 2, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 2, # 'R' - 33: 2, # 'S' - 37: 2, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 1, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 2, # 'd' - 1: 1, # 'e' - 27: 1, # 'f' - 12: 3, # 'g' - 20: 1, # 'h' - 9: 1, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 2, # 'l' - 13: 2, # 'm' - 4: 2, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 2, # 's' - 3: 1, # 't' - 21: 2, # 'u' - 19: 1, # 'v' - 62: 1, # 'x' - 16: 0, # 'y' - 11: 3, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 0, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 0, # 'Ú' - 63: 1, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 1, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 50: { # 'F' - 28: 1, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 1, # 'E' - 50: 1, # 'F' - 49: 0, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 0, # 'P' - 43: 1, # 'R' - 33: 0, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 0, # 'V' - 55: 1, # 'Y' - 52: 0, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 1, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 2, # 'i' - 22: 1, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 2, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 0, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 0, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 0, # 'Ú' - 63: 1, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 2, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 49: { # 'G' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 2, # 'Y' - 52: 1, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 1, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 2, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 2, # 'y' - 11: 0, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 0, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 0, # 'ű' - }, - 38: { # 'H' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 0, # 'D' - 32: 1, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 1, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 1, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 1, # 'O' - 46: 0, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 0, # 'V' - 55: 1, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 2, # 'i' - 22: 1, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 0, # 'n' - 8: 3, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 2, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 0, # 'z' - 51: 2, # 'Á' - 44: 2, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 1, # 'é' - 30: 2, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 39: { # 'I' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 1, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 2, # 'K' - 41: 2, # 'L' - 34: 1, # 'M' - 35: 2, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 2, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 2, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 2, # 'd' - 1: 0, # 'e' - 27: 1, # 'f' - 12: 2, # 'g' - 20: 1, # 'h' - 9: 0, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 2, # 'l' - 13: 2, # 'm' - 4: 1, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 2, # 's' - 3: 2, # 't' - 21: 0, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 1, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 0, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 53: { # 'J' - 28: 2, # 'A' - 40: 0, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 1, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 1, # 'o' - 23: 0, # 'p' - 10: 0, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 2, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 0, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 0, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 1, # 'é' - 30: 0, # 'í' - 25: 2, # 'ó' - 24: 2, # 'ö' - 31: 1, # 'ú' - 29: 0, # 'ü' - 42: 1, # 'ő' - 56: 0, # 'ű' - }, - 36: { # 'K' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 0, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 2, # 'O' - 46: 0, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 0, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 1, # 'f' - 12: 0, # 'g' - 20: 1, # 'h' - 9: 3, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 2, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 0, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 2, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 2, # 'ö' - 31: 1, # 'ú' - 29: 2, # 'ü' - 42: 1, # 'ő' - 56: 0, # 'ű' - }, - 41: { # 'L' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 2, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 2, # 'O' - 46: 0, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 2, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 3, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 2, # 'i' - 22: 1, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 0, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 2, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 0, # 'z' - 51: 2, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 0, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 34: { # 'M' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 0, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 3, # 'a' - 18: 0, # 'b' - 26: 1, # 'c' - 17: 0, # 'd' - 1: 3, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 3, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 3, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 2, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 0, # 'z' - 51: 2, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 1, # 'ű' - }, - 35: { # 'N' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 2, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 2, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 2, # 'Y' - 52: 1, # 'Z' - 2: 3, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 3, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 2, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 0, # 'm' - 4: 1, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 0, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 2, # 'y' - 11: 0, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 1, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 1, # 'ő' - 56: 0, # 'ű' - }, - 47: { # 'O' - 28: 1, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 1, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 2, # 'K' - 41: 2, # 'L' - 34: 2, # 'M' - 35: 2, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 2, # 'R' - 33: 2, # 'S' - 37: 2, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 1, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 1, # 'i' - 22: 1, # 'j' - 7: 2, # 'k' - 6: 2, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 1, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 1, # 's' - 3: 2, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 1, # 'x' - 16: 0, # 'y' - 11: 1, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 0, # 'Í' - 58: 1, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 46: { # 'P' - 28: 1, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 1, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 0, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 2, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 1, # 'f' - 12: 0, # 'g' - 20: 1, # 'h' - 9: 2, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 1, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 2, # 'r' - 5: 1, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 0, # 'z' - 51: 2, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 0, # 'Ú' - 63: 1, # 'Ü' - 14: 3, # 'á' - 15: 2, # 'é' - 30: 0, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 0, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 0, # 'ű' - }, - 43: { # 'R' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 2, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 2, # 'S' - 37: 2, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 1, # 'h' - 9: 2, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 0, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 0, # 'z' - 51: 2, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 2, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 2, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 33: { # 'S' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 2, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 2, # 'S' - 37: 2, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 3, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 1, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 1, # 'h' - 9: 2, # 'i' - 22: 0, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 1, # 'p' - 10: 0, # 'r' - 5: 0, # 's' - 3: 1, # 't' - 21: 1, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 3, # 'z' - 51: 2, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 37: { # 'T' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 2, # 'O' - 46: 1, # 'P' - 43: 2, # 'R' - 33: 1, # 'S' - 37: 2, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 2, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 1, # 'h' - 9: 2, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 1, # 's' - 3: 0, # 't' - 21: 2, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 1, # 'z' - 51: 2, # 'Á' - 44: 2, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 2, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 57: { # 'U' - 28: 1, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 1, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 2, # 'S' - 37: 1, # 'T' - 57: 0, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 1, # 'e' - 27: 0, # 'f' - 12: 2, # 'g' - 20: 0, # 'h' - 9: 0, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 1, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 0, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 1, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 48: { # 'V' - 28: 2, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 0, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 2, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 2, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 2, # 'o' - 23: 0, # 'p' - 10: 0, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 0, # 'z' - 51: 2, # 'Á' - 44: 2, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 0, # 'Ú' - 63: 1, # 'Ü' - 14: 2, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 0, # 'ó' - 24: 1, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 55: { # 'Y' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 1, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 2, # 'Z' - 2: 1, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 1, # 'd' - 1: 1, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 0, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 0, # 'm' - 4: 0, # 'n' - 8: 1, # 'o' - 23: 1, # 'p' - 10: 0, # 'r' - 5: 0, # 's' - 3: 0, # 't' - 21: 0, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 0, # 'z' - 51: 1, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 52: { # 'Z' - 28: 2, # 'A' - 40: 1, # 'B' - 54: 0, # 'C' - 45: 1, # 'D' - 32: 2, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 2, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 2, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 2, # 'S' - 37: 1, # 'T' - 57: 1, # 'U' - 48: 1, # 'V' - 55: 1, # 'Y' - 52: 1, # 'Z' - 2: 1, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 1, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 1, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 0, # 'm' - 4: 1, # 'n' - 8: 1, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 2, # 's' - 3: 0, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 0, # 'z' - 51: 2, # 'Á' - 44: 1, # 'É' - 61: 1, # 'Í' - 58: 1, # 'Ó' - 59: 1, # 'Ö' - 60: 1, # 'Ú' - 63: 1, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 2: { # 'a' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 3, # 'b' - 26: 3, # 'c' - 17: 3, # 'd' - 1: 2, # 'e' - 27: 2, # 'f' - 12: 3, # 'g' - 20: 3, # 'h' - 9: 3, # 'i' - 22: 3, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 2, # 'o' - 23: 3, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 3, # 'v' - 62: 1, # 'x' - 16: 2, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 18: { # 'b' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 3, # 'i' - 22: 2, # 'j' - 7: 2, # 'k' - 6: 2, # 'l' - 13: 1, # 'm' - 4: 2, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 3, # 'r' - 5: 2, # 's' - 3: 1, # 't' - 21: 3, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 3, # 'ó' - 24: 2, # 'ö' - 31: 2, # 'ú' - 29: 2, # 'ü' - 42: 2, # 'ő' - 56: 1, # 'ű' - }, - 26: { # 'c' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 1, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 1, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 2, # 'a' - 18: 1, # 'b' - 26: 2, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 3, # 'h' - 9: 3, # 'i' - 22: 1, # 'j' - 7: 2, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 3, # 's' - 3: 2, # 't' - 21: 2, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 2, # 'á' - 15: 2, # 'é' - 30: 2, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 17: { # 'd' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 2, # 'b' - 26: 1, # 'c' - 17: 2, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 3, # 'j' - 7: 2, # 'k' - 6: 1, # 'l' - 13: 2, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 2, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 3, # 'í' - 25: 3, # 'ó' - 24: 3, # 'ö' - 31: 2, # 'ú' - 29: 2, # 'ü' - 42: 2, # 'ő' - 56: 1, # 'ű' - }, - 1: { # 'e' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 2, # 'a' - 18: 3, # 'b' - 26: 3, # 'c' - 17: 3, # 'd' - 1: 2, # 'e' - 27: 3, # 'f' - 12: 3, # 'g' - 20: 3, # 'h' - 9: 3, # 'i' - 22: 3, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 2, # 'o' - 23: 3, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 2, # 'u' - 19: 3, # 'v' - 62: 2, # 'x' - 16: 2, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 27: { # 'f' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 2, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 3, # 'i' - 22: 2, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 3, # 'o' - 23: 0, # 'p' - 10: 3, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 2, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 0, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 3, # 'ö' - 31: 1, # 'ú' - 29: 2, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 12: { # 'g' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 2, # 'c' - 17: 2, # 'd' - 1: 3, # 'e' - 27: 2, # 'f' - 12: 3, # 'g' - 20: 3, # 'h' - 9: 3, # 'i' - 22: 3, # 'j' - 7: 2, # 'k' - 6: 3, # 'l' - 13: 2, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 3, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 3, # 'ó' - 24: 2, # 'ö' - 31: 2, # 'ú' - 29: 2, # 'ü' - 42: 2, # 'ő' - 56: 1, # 'ű' - }, - 20: { # 'h' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 0, # 'd' - 1: 3, # 'e' - 27: 0, # 'f' - 12: 1, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 3, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 2, # 's' - 3: 1, # 't' - 21: 3, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 2, # 'y' - 11: 0, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 3, # 'í' - 25: 2, # 'ó' - 24: 2, # 'ö' - 31: 2, # 'ú' - 29: 1, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 9: { # 'i' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 3, # 'c' - 17: 3, # 'd' - 1: 3, # 'e' - 27: 3, # 'f' - 12: 3, # 'g' - 20: 3, # 'h' - 9: 2, # 'i' - 22: 2, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 2, # 'o' - 23: 2, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 3, # 'v' - 62: 1, # 'x' - 16: 1, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 3, # 'ó' - 24: 1, # 'ö' - 31: 2, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 1, # 'ű' - }, - 22: { # 'j' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 2, # 'b' - 26: 1, # 'c' - 17: 3, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 2, # 'h' - 9: 1, # 'i' - 22: 2, # 'j' - 7: 2, # 'k' - 6: 2, # 'l' - 13: 1, # 'm' - 4: 2, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 2, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 1, # 'í' - 25: 3, # 'ó' - 24: 3, # 'ö' - 31: 3, # 'ú' - 29: 2, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 7: { # 'k' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 2, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 2, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 1, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 2, # 'v' - 62: 0, # 'x' - 16: 2, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 3, # 'í' - 25: 2, # 'ó' - 24: 3, # 'ö' - 31: 1, # 'ú' - 29: 3, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 6: { # 'l' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 1, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 1, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 2, # 'b' - 26: 3, # 'c' - 17: 3, # 'd' - 1: 3, # 'e' - 27: 3, # 'f' - 12: 3, # 'g' - 20: 3, # 'h' - 9: 3, # 'i' - 22: 3, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 2, # 'p' - 10: 2, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 3, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 3, # 'í' - 25: 3, # 'ó' - 24: 3, # 'ö' - 31: 2, # 'ú' - 29: 2, # 'ü' - 42: 3, # 'ő' - 56: 1, # 'ű' - }, - 13: { # 'm' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 2, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 2, # 'j' - 7: 1, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 2, # 'n' - 8: 3, # 'o' - 23: 3, # 'p' - 10: 2, # 'r' - 5: 2, # 's' - 3: 2, # 't' - 21: 3, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 2, # 'ó' - 24: 2, # 'ö' - 31: 2, # 'ú' - 29: 2, # 'ü' - 42: 1, # 'ő' - 56: 2, # 'ű' - }, - 4: { # 'n' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 3, # 'c' - 17: 3, # 'd' - 1: 3, # 'e' - 27: 2, # 'f' - 12: 3, # 'g' - 20: 3, # 'h' - 9: 3, # 'i' - 22: 2, # 'j' - 7: 3, # 'k' - 6: 2, # 'l' - 13: 2, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 2, # 'p' - 10: 2, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 2, # 'v' - 62: 1, # 'x' - 16: 3, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 2, # 'ó' - 24: 3, # 'ö' - 31: 2, # 'ú' - 29: 3, # 'ü' - 42: 2, # 'ő' - 56: 1, # 'ű' - }, - 8: { # 'o' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 1, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 2, # 'a' - 18: 3, # 'b' - 26: 3, # 'c' - 17: 3, # 'd' - 1: 2, # 'e' - 27: 2, # 'f' - 12: 3, # 'g' - 20: 3, # 'h' - 9: 2, # 'i' - 22: 2, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 1, # 'o' - 23: 3, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 2, # 'u' - 19: 3, # 'v' - 62: 1, # 'x' - 16: 1, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 1, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 23: { # 'p' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 1, # 'b' - 26: 2, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 2, # 'j' - 7: 2, # 'k' - 6: 3, # 'l' - 13: 1, # 'm' - 4: 2, # 'n' - 8: 3, # 'o' - 23: 3, # 'p' - 10: 3, # 'r' - 5: 2, # 's' - 3: 2, # 't' - 21: 3, # 'u' - 19: 2, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 2, # 'ó' - 24: 2, # 'ö' - 31: 1, # 'ú' - 29: 2, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 10: { # 'r' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 3, # 'c' - 17: 3, # 'd' - 1: 3, # 'e' - 27: 2, # 'f' - 12: 3, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 3, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 2, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 3, # 'v' - 62: 1, # 'x' - 16: 2, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 3, # 'ó' - 24: 3, # 'ö' - 31: 3, # 'ú' - 29: 3, # 'ü' - 42: 2, # 'ő' - 56: 2, # 'ű' - }, - 5: { # 's' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 2, # 'c' - 17: 2, # 'd' - 1: 3, # 'e' - 27: 2, # 'f' - 12: 2, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 1, # 'j' - 7: 3, # 'k' - 6: 2, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 2, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 2, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 3, # 'í' - 25: 3, # 'ó' - 24: 3, # 'ö' - 31: 3, # 'ú' - 29: 3, # 'ü' - 42: 2, # 'ő' - 56: 1, # 'ű' - }, - 3: { # 't' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 3, # 'b' - 26: 2, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 2, # 'f' - 12: 1, # 'g' - 20: 3, # 'h' - 9: 3, # 'i' - 22: 3, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 2, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 3, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 3, # 'ó' - 24: 3, # 'ö' - 31: 3, # 'ú' - 29: 3, # 'ü' - 42: 3, # 'ő' - 56: 2, # 'ű' - }, - 21: { # 'u' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 2, # 'b' - 26: 2, # 'c' - 17: 3, # 'd' - 1: 2, # 'e' - 27: 1, # 'f' - 12: 3, # 'g' - 20: 2, # 'h' - 9: 2, # 'i' - 22: 2, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 1, # 'o' - 23: 2, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 1, # 'u' - 19: 3, # 'v' - 62: 1, # 'x' - 16: 1, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 2, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 0, # 'ö' - 31: 1, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 19: { # 'v' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 2, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 3, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 1, # 'r' - 5: 2, # 's' - 3: 2, # 't' - 21: 2, # 'u' - 19: 2, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 2, # 'ó' - 24: 2, # 'ö' - 31: 1, # 'ú' - 29: 2, # 'ü' - 42: 1, # 'ő' - 56: 1, # 'ű' - }, - 62: { # 'x' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 0, # 'd' - 1: 1, # 'e' - 27: 1, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 1, # 'i' - 22: 0, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 1, # 'o' - 23: 1, # 'p' - 10: 1, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 1, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 0, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 1, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 16: { # 'y' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 2, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 3, # 'e' - 27: 2, # 'f' - 12: 2, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 2, # 'j' - 7: 2, # 'k' - 6: 2, # 'l' - 13: 2, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 2, # 'p' - 10: 2, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 2, # 'í' - 25: 2, # 'ó' - 24: 3, # 'ö' - 31: 2, # 'ú' - 29: 2, # 'ü' - 42: 1, # 'ő' - 56: 2, # 'ű' - }, - 11: { # 'z' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 3, # 'a' - 18: 2, # 'b' - 26: 1, # 'c' - 17: 3, # 'd' - 1: 3, # 'e' - 27: 1, # 'f' - 12: 2, # 'g' - 20: 2, # 'h' - 9: 3, # 'i' - 22: 1, # 'j' - 7: 3, # 'k' - 6: 2, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 3, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 3, # 'u' - 19: 2, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 3, # 'á' - 15: 3, # 'é' - 30: 3, # 'í' - 25: 3, # 'ó' - 24: 3, # 'ö' - 31: 2, # 'ú' - 29: 3, # 'ü' - 42: 2, # 'ő' - 56: 1, # 'ű' - }, - 51: { # 'Á' - 28: 0, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 0, # 'E' - 50: 1, # 'F' - 49: 2, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 2, # 'L' - 34: 1, # 'M' - 35: 2, # 'N' - 47: 0, # 'O' - 46: 1, # 'P' - 43: 2, # 'R' - 33: 2, # 'S' - 37: 1, # 'T' - 57: 0, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 0, # 'e' - 27: 0, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 0, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 2, # 'l' - 13: 2, # 'm' - 4: 0, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 1, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 0, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 1, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 44: { # 'É' - 28: 0, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 1, # 'E' - 50: 0, # 'F' - 49: 2, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 2, # 'L' - 34: 1, # 'M' - 35: 2, # 'N' - 47: 0, # 'O' - 46: 1, # 'P' - 43: 2, # 'R' - 33: 2, # 'S' - 37: 2, # 'T' - 57: 0, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 0, # 'e' - 27: 0, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 0, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 2, # 'l' - 13: 1, # 'm' - 4: 2, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 3, # 's' - 3: 1, # 't' - 21: 0, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 0, # 'z' - 51: 0, # 'Á' - 44: 1, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 61: { # 'Í' - 28: 0, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 0, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 1, # 'J' - 36: 0, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 0, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 0, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 0, # 'e' - 27: 0, # 'f' - 12: 2, # 'g' - 20: 0, # 'h' - 9: 0, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 1, # 'm' - 4: 0, # 'n' - 8: 0, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 0, # 's' - 3: 1, # 't' - 21: 0, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 58: { # 'Ó' - 28: 1, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 0, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 1, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 2, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 0, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 0, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 0, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 2, # 'h' - 9: 0, # 'i' - 22: 0, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 1, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 1, # 'r' - 5: 1, # 's' - 3: 0, # 't' - 21: 0, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 1, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 59: { # 'Ö' - 28: 0, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 0, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 0, # 'O' - 46: 1, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 0, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 0, # 'b' - 26: 1, # 'c' - 17: 1, # 'd' - 1: 0, # 'e' - 27: 0, # 'f' - 12: 0, # 'g' - 20: 0, # 'h' - 9: 0, # 'i' - 22: 0, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 1, # 'm' - 4: 1, # 'n' - 8: 0, # 'o' - 23: 0, # 'p' - 10: 2, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 0, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 60: { # 'Ú' - 28: 0, # 'A' - 40: 1, # 'B' - 54: 1, # 'C' - 45: 1, # 'D' - 32: 0, # 'E' - 50: 1, # 'F' - 49: 1, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 0, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 0, # 'b' - 26: 0, # 'c' - 17: 0, # 'd' - 1: 0, # 'e' - 27: 0, # 'f' - 12: 2, # 'g' - 20: 0, # 'h' - 9: 0, # 'i' - 22: 2, # 'j' - 7: 0, # 'k' - 6: 0, # 'l' - 13: 0, # 'm' - 4: 1, # 'n' - 8: 0, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 0, # 'u' - 19: 0, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 0, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 63: { # 'Ü' - 28: 0, # 'A' - 40: 1, # 'B' - 54: 0, # 'C' - 45: 1, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 1, # 'G' - 38: 1, # 'H' - 39: 0, # 'I' - 53: 1, # 'J' - 36: 1, # 'K' - 41: 1, # 'L' - 34: 1, # 'M' - 35: 1, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 1, # 'R' - 33: 1, # 'S' - 37: 1, # 'T' - 57: 0, # 'U' - 48: 1, # 'V' - 55: 0, # 'Y' - 52: 1, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 0, # 'c' - 17: 1, # 'd' - 1: 0, # 'e' - 27: 0, # 'f' - 12: 1, # 'g' - 20: 0, # 'h' - 9: 0, # 'i' - 22: 0, # 'j' - 7: 0, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 1, # 'n' - 8: 0, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 0, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 1, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 14: { # 'á' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 3, # 'b' - 26: 3, # 'c' - 17: 3, # 'd' - 1: 1, # 'e' - 27: 2, # 'f' - 12: 3, # 'g' - 20: 2, # 'h' - 9: 2, # 'i' - 22: 3, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 1, # 'o' - 23: 2, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 2, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 1, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 1, # 'á' - 15: 2, # 'é' - 30: 1, # 'í' - 25: 0, # 'ó' - 24: 1, # 'ö' - 31: 0, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 15: { # 'é' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 3, # 'b' - 26: 2, # 'c' - 17: 3, # 'd' - 1: 1, # 'e' - 27: 1, # 'f' - 12: 3, # 'g' - 20: 3, # 'h' - 9: 2, # 'i' - 22: 2, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 1, # 'o' - 23: 3, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 0, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 30: { # 'í' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 0, # 'a' - 18: 1, # 'b' - 26: 2, # 'c' - 17: 1, # 'd' - 1: 0, # 'e' - 27: 1, # 'f' - 12: 3, # 'g' - 20: 0, # 'h' - 9: 0, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 2, # 'l' - 13: 2, # 'm' - 4: 3, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 3, # 'r' - 5: 2, # 's' - 3: 3, # 't' - 21: 0, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 25: { # 'ó' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 2, # 'a' - 18: 3, # 'b' - 26: 2, # 'c' - 17: 3, # 'd' - 1: 1, # 'e' - 27: 2, # 'f' - 12: 2, # 'g' - 20: 2, # 'h' - 9: 2, # 'i' - 22: 2, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 2, # 'm' - 4: 3, # 'n' - 8: 1, # 'o' - 23: 2, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 1, # 'u' - 19: 2, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 0, # 'ó' - 24: 1, # 'ö' - 31: 1, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 24: { # 'ö' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 0, # 'a' - 18: 3, # 'b' - 26: 1, # 'c' - 17: 2, # 'd' - 1: 0, # 'e' - 27: 1, # 'f' - 12: 2, # 'g' - 20: 1, # 'h' - 9: 0, # 'i' - 22: 1, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 3, # 'm' - 4: 3, # 'n' - 8: 0, # 'o' - 23: 2, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 3, # 't' - 21: 0, # 'u' - 19: 3, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 3, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 31: { # 'ú' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 1, # 'b' - 26: 2, # 'c' - 17: 1, # 'd' - 1: 1, # 'e' - 27: 2, # 'f' - 12: 3, # 'g' - 20: 1, # 'h' - 9: 1, # 'i' - 22: 3, # 'j' - 7: 1, # 'k' - 6: 3, # 'l' - 13: 1, # 'm' - 4: 2, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 3, # 'r' - 5: 3, # 's' - 3: 2, # 't' - 21: 1, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 1, # 'á' - 15: 1, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 29: { # 'ü' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 1, # 'b' - 26: 1, # 'c' - 17: 2, # 'd' - 1: 1, # 'e' - 27: 1, # 'f' - 12: 3, # 'g' - 20: 2, # 'h' - 9: 1, # 'i' - 22: 1, # 'j' - 7: 3, # 'k' - 6: 3, # 'l' - 13: 1, # 'm' - 4: 3, # 'n' - 8: 0, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 2, # 's' - 3: 2, # 't' - 21: 0, # 'u' - 19: 2, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 1, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 42: { # 'ő' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 2, # 'b' - 26: 1, # 'c' - 17: 2, # 'd' - 1: 1, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 1, # 'i' - 22: 1, # 'j' - 7: 2, # 'k' - 6: 3, # 'l' - 13: 1, # 'm' - 4: 2, # 'n' - 8: 1, # 'o' - 23: 1, # 'p' - 10: 2, # 'r' - 5: 2, # 's' - 3: 2, # 't' - 21: 1, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 1, # 'é' - 30: 1, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 1, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, - 56: { # 'ű' - 28: 0, # 'A' - 40: 0, # 'B' - 54: 0, # 'C' - 45: 0, # 'D' - 32: 0, # 'E' - 50: 0, # 'F' - 49: 0, # 'G' - 38: 0, # 'H' - 39: 0, # 'I' - 53: 0, # 'J' - 36: 0, # 'K' - 41: 0, # 'L' - 34: 0, # 'M' - 35: 0, # 'N' - 47: 0, # 'O' - 46: 0, # 'P' - 43: 0, # 'R' - 33: 0, # 'S' - 37: 0, # 'T' - 57: 0, # 'U' - 48: 0, # 'V' - 55: 0, # 'Y' - 52: 0, # 'Z' - 2: 1, # 'a' - 18: 1, # 'b' - 26: 0, # 'c' - 17: 1, # 'd' - 1: 1, # 'e' - 27: 1, # 'f' - 12: 1, # 'g' - 20: 1, # 'h' - 9: 1, # 'i' - 22: 1, # 'j' - 7: 1, # 'k' - 6: 1, # 'l' - 13: 0, # 'm' - 4: 2, # 'n' - 8: 0, # 'o' - 23: 0, # 'p' - 10: 1, # 'r' - 5: 1, # 's' - 3: 1, # 't' - 21: 0, # 'u' - 19: 1, # 'v' - 62: 0, # 'x' - 16: 0, # 'y' - 11: 2, # 'z' - 51: 0, # 'Á' - 44: 0, # 'É' - 61: 0, # 'Í' - 58: 0, # 'Ó' - 59: 0, # 'Ö' - 60: 0, # 'Ú' - 63: 0, # 'Ü' - 14: 0, # 'á' - 15: 0, # 'é' - 30: 0, # 'í' - 25: 0, # 'ó' - 24: 0, # 'ö' - 31: 0, # 'ú' - 29: 0, # 'ü' - 42: 0, # 'ő' - 56: 0, # 'ű' - }, -} - -# 255: Undefined characters that did not exist in training text -# 254: Carriage/Return -# 253: symbol (punctuation) that does not belong to word -# 252: 0 - 9 -# 251: Control characters - -# Character Mapping Table(s): -WINDOWS_1250_HUNGARIAN_CHAR_TO_ORDER = { - 0: 255, # '\x00' - 1: 255, # '\x01' - 2: 255, # '\x02' - 3: 255, # '\x03' - 4: 255, # '\x04' - 5: 255, # '\x05' - 6: 255, # '\x06' - 7: 255, # '\x07' - 8: 255, # '\x08' - 9: 255, # '\t' - 10: 254, # '\n' - 11: 255, # '\x0b' - 12: 255, # '\x0c' - 13: 254, # '\r' - 14: 255, # '\x0e' - 15: 255, # '\x0f' - 16: 255, # '\x10' - 17: 255, # '\x11' - 18: 255, # '\x12' - 19: 255, # '\x13' - 20: 255, # '\x14' - 21: 255, # '\x15' - 22: 255, # '\x16' - 23: 255, # '\x17' - 24: 255, # '\x18' - 25: 255, # '\x19' - 26: 255, # '\x1a' - 27: 255, # '\x1b' - 28: 255, # '\x1c' - 29: 255, # '\x1d' - 30: 255, # '\x1e' - 31: 255, # '\x1f' - 32: 253, # ' ' - 33: 253, # '!' - 34: 253, # '"' - 35: 253, # '#' - 36: 253, # '$' - 37: 253, # '%' - 38: 253, # '&' - 39: 253, # "'" - 40: 253, # '(' - 41: 253, # ')' - 42: 253, # '*' - 43: 253, # '+' - 44: 253, # ',' - 45: 253, # '-' - 46: 253, # '.' - 47: 253, # '/' - 48: 252, # '0' - 49: 252, # '1' - 50: 252, # '2' - 51: 252, # '3' - 52: 252, # '4' - 53: 252, # '5' - 54: 252, # '6' - 55: 252, # '7' - 56: 252, # '8' - 57: 252, # '9' - 58: 253, # ':' - 59: 253, # ';' - 60: 253, # '<' - 61: 253, # '=' - 62: 253, # '>' - 63: 253, # '?' - 64: 253, # '@' - 65: 28, # 'A' - 66: 40, # 'B' - 67: 54, # 'C' - 68: 45, # 'D' - 69: 32, # 'E' - 70: 50, # 'F' - 71: 49, # 'G' - 72: 38, # 'H' - 73: 39, # 'I' - 74: 53, # 'J' - 75: 36, # 'K' - 76: 41, # 'L' - 77: 34, # 'M' - 78: 35, # 'N' - 79: 47, # 'O' - 80: 46, # 'P' - 81: 72, # 'Q' - 82: 43, # 'R' - 83: 33, # 'S' - 84: 37, # 'T' - 85: 57, # 'U' - 86: 48, # 'V' - 87: 64, # 'W' - 88: 68, # 'X' - 89: 55, # 'Y' - 90: 52, # 'Z' - 91: 253, # '[' - 92: 253, # '\\' - 93: 253, # ']' - 94: 253, # '^' - 95: 253, # '_' - 96: 253, # '`' - 97: 2, # 'a' - 98: 18, # 'b' - 99: 26, # 'c' - 100: 17, # 'd' - 101: 1, # 'e' - 102: 27, # 'f' - 103: 12, # 'g' - 104: 20, # 'h' - 105: 9, # 'i' - 106: 22, # 'j' - 107: 7, # 'k' - 108: 6, # 'l' - 109: 13, # 'm' - 110: 4, # 'n' - 111: 8, # 'o' - 112: 23, # 'p' - 113: 67, # 'q' - 114: 10, # 'r' - 115: 5, # 's' - 116: 3, # 't' - 117: 21, # 'u' - 118: 19, # 'v' - 119: 65, # 'w' - 120: 62, # 'x' - 121: 16, # 'y' - 122: 11, # 'z' - 123: 253, # '{' - 124: 253, # '|' - 125: 253, # '}' - 126: 253, # '~' - 127: 253, # '\x7f' - 128: 161, # '€' - 129: 162, # None - 130: 163, # '‚' - 131: 164, # None - 132: 165, # '„' - 133: 166, # '…' - 134: 167, # '†' - 135: 168, # '‡' - 136: 169, # None - 137: 170, # '‰' - 138: 171, # 'Š' - 139: 172, # '‹' - 140: 173, # 'Ś' - 141: 174, # 'Ť' - 142: 175, # 'Ž' - 143: 176, # 'Ź' - 144: 177, # None - 145: 178, # '‘' - 146: 179, # '’' - 147: 180, # '“' - 148: 78, # '”' - 149: 181, # '•' - 150: 69, # '–' - 151: 182, # '—' - 152: 183, # None - 153: 184, # '™' - 154: 185, # 'š' - 155: 186, # '›' - 156: 187, # 'ś' - 157: 188, # 'ť' - 158: 189, # 'ž' - 159: 190, # 'ź' - 160: 191, # '\xa0' - 161: 192, # 'ˇ' - 162: 193, # '˘' - 163: 194, # 'Ł' - 164: 195, # '¤' - 165: 196, # 'Ą' - 166: 197, # '¦' - 167: 76, # '§' - 168: 198, # '¨' - 169: 199, # '©' - 170: 200, # 'Ş' - 171: 201, # '«' - 172: 202, # '¬' - 173: 203, # '\xad' - 174: 204, # '®' - 175: 205, # 'Ż' - 176: 81, # '°' - 177: 206, # '±' - 178: 207, # '˛' - 179: 208, # 'ł' - 180: 209, # '´' - 181: 210, # 'µ' - 182: 211, # '¶' - 183: 212, # '·' - 184: 213, # '¸' - 185: 214, # 'ą' - 186: 215, # 'ş' - 187: 216, # '»' - 188: 217, # 'Ľ' - 189: 218, # '˝' - 190: 219, # 'ľ' - 191: 220, # 'ż' - 192: 221, # 'Ŕ' - 193: 51, # 'Á' - 194: 83, # 'Â' - 195: 222, # 'Ă' - 196: 80, # 'Ä' - 197: 223, # 'Ĺ' - 198: 224, # 'Ć' - 199: 225, # 'Ç' - 200: 226, # 'Č' - 201: 44, # 'É' - 202: 227, # 'Ę' - 203: 228, # 'Ë' - 204: 229, # 'Ě' - 205: 61, # 'Í' - 206: 230, # 'Î' - 207: 231, # 'Ď' - 208: 232, # 'Đ' - 209: 233, # 'Ń' - 210: 234, # 'Ň' - 211: 58, # 'Ó' - 212: 235, # 'Ô' - 213: 66, # 'Ő' - 214: 59, # 'Ö' - 215: 236, # '×' - 216: 237, # 'Ř' - 217: 238, # 'Ů' - 218: 60, # 'Ú' - 219: 70, # 'Ű' - 220: 63, # 'Ü' - 221: 239, # 'Ý' - 222: 240, # 'Ţ' - 223: 241, # 'ß' - 224: 84, # 'ŕ' - 225: 14, # 'á' - 226: 75, # 'â' - 227: 242, # 'ă' - 228: 71, # 'ä' - 229: 82, # 'ĺ' - 230: 243, # 'ć' - 231: 73, # 'ç' - 232: 244, # 'č' - 233: 15, # 'é' - 234: 85, # 'ę' - 235: 79, # 'ë' - 236: 86, # 'ě' - 237: 30, # 'í' - 238: 77, # 'î' - 239: 87, # 'ď' - 240: 245, # 'đ' - 241: 246, # 'ń' - 242: 247, # 'ň' - 243: 25, # 'ó' - 244: 74, # 'ô' - 245: 42, # 'ő' - 246: 24, # 'ö' - 247: 248, # '÷' - 248: 249, # 'ř' - 249: 250, # 'ů' - 250: 31, # 'ú' - 251: 56, # 'ű' - 252: 29, # 'ü' - 253: 251, # 'ý' - 254: 252, # 'ţ' - 255: 253, # '˙' -} - -WINDOWS_1250_HUNGARIAN_MODEL = SingleByteCharSetModel( - charset_name="windows-1250", - language="Hungarian", - char_to_order_map=WINDOWS_1250_HUNGARIAN_CHAR_TO_ORDER, - language_model=HUNGARIAN_LANG_MODEL, - typical_positive_ratio=0.947368, - keep_ascii_letters=True, - alphabet="ABCDEFGHIJKLMNOPRSTUVZabcdefghijklmnoprstuvzÁÉÍÓÖÚÜáéíóöúüŐőŰű", -) - -ISO_8859_2_HUNGARIAN_CHAR_TO_ORDER = { - 0: 255, # '\x00' - 1: 255, # '\x01' - 2: 255, # '\x02' - 3: 255, # '\x03' - 4: 255, # '\x04' - 5: 255, # '\x05' - 6: 255, # '\x06' - 7: 255, # '\x07' - 8: 255, # '\x08' - 9: 255, # '\t' - 10: 254, # '\n' - 11: 255, # '\x0b' - 12: 255, # '\x0c' - 13: 254, # '\r' - 14: 255, # '\x0e' - 15: 255, # '\x0f' - 16: 255, # '\x10' - 17: 255, # '\x11' - 18: 255, # '\x12' - 19: 255, # '\x13' - 20: 255, # '\x14' - 21: 255, # '\x15' - 22: 255, # '\x16' - 23: 255, # '\x17' - 24: 255, # '\x18' - 25: 255, # '\x19' - 26: 255, # '\x1a' - 27: 255, # '\x1b' - 28: 255, # '\x1c' - 29: 255, # '\x1d' - 30: 255, # '\x1e' - 31: 255, # '\x1f' - 32: 253, # ' ' - 33: 253, # '!' - 34: 253, # '"' - 35: 253, # '#' - 36: 253, # '$' - 37: 253, # '%' - 38: 253, # '&' - 39: 253, # "'" - 40: 253, # '(' - 41: 253, # ')' - 42: 253, # '*' - 43: 253, # '+' - 44: 253, # ',' - 45: 253, # '-' - 46: 253, # '.' - 47: 253, # '/' - 48: 252, # '0' - 49: 252, # '1' - 50: 252, # '2' - 51: 252, # '3' - 52: 252, # '4' - 53: 252, # '5' - 54: 252, # '6' - 55: 252, # '7' - 56: 252, # '8' - 57: 252, # '9' - 58: 253, # ':' - 59: 253, # ';' - 60: 253, # '<' - 61: 253, # '=' - 62: 253, # '>' - 63: 253, # '?' - 64: 253, # '@' - 65: 28, # 'A' - 66: 40, # 'B' - 67: 54, # 'C' - 68: 45, # 'D' - 69: 32, # 'E' - 70: 50, # 'F' - 71: 49, # 'G' - 72: 38, # 'H' - 73: 39, # 'I' - 74: 53, # 'J' - 75: 36, # 'K' - 76: 41, # 'L' - 77: 34, # 'M' - 78: 35, # 'N' - 79: 47, # 'O' - 80: 46, # 'P' - 81: 71, # 'Q' - 82: 43, # 'R' - 83: 33, # 'S' - 84: 37, # 'T' - 85: 57, # 'U' - 86: 48, # 'V' - 87: 64, # 'W' - 88: 68, # 'X' - 89: 55, # 'Y' - 90: 52, # 'Z' - 91: 253, # '[' - 92: 253, # '\\' - 93: 253, # ']' - 94: 253, # '^' - 95: 253, # '_' - 96: 253, # '`' - 97: 2, # 'a' - 98: 18, # 'b' - 99: 26, # 'c' - 100: 17, # 'd' - 101: 1, # 'e' - 102: 27, # 'f' - 103: 12, # 'g' - 104: 20, # 'h' - 105: 9, # 'i' - 106: 22, # 'j' - 107: 7, # 'k' - 108: 6, # 'l' - 109: 13, # 'm' - 110: 4, # 'n' - 111: 8, # 'o' - 112: 23, # 'p' - 113: 67, # 'q' - 114: 10, # 'r' - 115: 5, # 's' - 116: 3, # 't' - 117: 21, # 'u' - 118: 19, # 'v' - 119: 65, # 'w' - 120: 62, # 'x' - 121: 16, # 'y' - 122: 11, # 'z' - 123: 253, # '{' - 124: 253, # '|' - 125: 253, # '}' - 126: 253, # '~' - 127: 253, # '\x7f' - 128: 159, # '\x80' - 129: 160, # '\x81' - 130: 161, # '\x82' - 131: 162, # '\x83' - 132: 163, # '\x84' - 133: 164, # '\x85' - 134: 165, # '\x86' - 135: 166, # '\x87' - 136: 167, # '\x88' - 137: 168, # '\x89' - 138: 169, # '\x8a' - 139: 170, # '\x8b' - 140: 171, # '\x8c' - 141: 172, # '\x8d' - 142: 173, # '\x8e' - 143: 174, # '\x8f' - 144: 175, # '\x90' - 145: 176, # '\x91' - 146: 177, # '\x92' - 147: 178, # '\x93' - 148: 179, # '\x94' - 149: 180, # '\x95' - 150: 181, # '\x96' - 151: 182, # '\x97' - 152: 183, # '\x98' - 153: 184, # '\x99' - 154: 185, # '\x9a' - 155: 186, # '\x9b' - 156: 187, # '\x9c' - 157: 188, # '\x9d' - 158: 189, # '\x9e' - 159: 190, # '\x9f' - 160: 191, # '\xa0' - 161: 192, # 'Ą' - 162: 193, # '˘' - 163: 194, # 'Ł' - 164: 195, # '¤' - 165: 196, # 'Ľ' - 166: 197, # 'Ś' - 167: 75, # '§' - 168: 198, # '¨' - 169: 199, # 'Š' - 170: 200, # 'Ş' - 171: 201, # 'Ť' - 172: 202, # 'Ź' - 173: 203, # '\xad' - 174: 204, # 'Ž' - 175: 205, # 'Ż' - 176: 79, # '°' - 177: 206, # 'ą' - 178: 207, # '˛' - 179: 208, # 'ł' - 180: 209, # '´' - 181: 210, # 'ľ' - 182: 211, # 'ś' - 183: 212, # 'ˇ' - 184: 213, # '¸' - 185: 214, # 'š' - 186: 215, # 'ş' - 187: 216, # 'ť' - 188: 217, # 'ź' - 189: 218, # '˝' - 190: 219, # 'ž' - 191: 220, # 'ż' - 192: 221, # 'Ŕ' - 193: 51, # 'Á' - 194: 81, # 'Â' - 195: 222, # 'Ă' - 196: 78, # 'Ä' - 197: 223, # 'Ĺ' - 198: 224, # 'Ć' - 199: 225, # 'Ç' - 200: 226, # 'Č' - 201: 44, # 'É' - 202: 227, # 'Ę' - 203: 228, # 'Ë' - 204: 229, # 'Ě' - 205: 61, # 'Í' - 206: 230, # 'Î' - 207: 231, # 'Ď' - 208: 232, # 'Đ' - 209: 233, # 'Ń' - 210: 234, # 'Ň' - 211: 58, # 'Ó' - 212: 235, # 'Ô' - 213: 66, # 'Ő' - 214: 59, # 'Ö' - 215: 236, # '×' - 216: 237, # 'Ř' - 217: 238, # 'Ů' - 218: 60, # 'Ú' - 219: 69, # 'Ű' - 220: 63, # 'Ü' - 221: 239, # 'Ý' - 222: 240, # 'Ţ' - 223: 241, # 'ß' - 224: 82, # 'ŕ' - 225: 14, # 'á' - 226: 74, # 'â' - 227: 242, # 'ă' - 228: 70, # 'ä' - 229: 80, # 'ĺ' - 230: 243, # 'ć' - 231: 72, # 'ç' - 232: 244, # 'č' - 233: 15, # 'é' - 234: 83, # 'ę' - 235: 77, # 'ë' - 236: 84, # 'ě' - 237: 30, # 'í' - 238: 76, # 'î' - 239: 85, # 'ď' - 240: 245, # 'đ' - 241: 246, # 'ń' - 242: 247, # 'ň' - 243: 25, # 'ó' - 244: 73, # 'ô' - 245: 42, # 'ő' - 246: 24, # 'ö' - 247: 248, # '÷' - 248: 249, # 'ř' - 249: 250, # 'ů' - 250: 31, # 'ú' - 251: 56, # 'ű' - 252: 29, # 'ü' - 253: 251, # 'ý' - 254: 252, # 'ţ' - 255: 253, # '˙' -} - -ISO_8859_2_HUNGARIAN_MODEL = SingleByteCharSetModel( - charset_name="ISO-8859-2", - language="Hungarian", - char_to_order_map=ISO_8859_2_HUNGARIAN_CHAR_TO_ORDER, - language_model=HUNGARIAN_LANG_MODEL, - typical_positive_ratio=0.947368, - keep_ascii_letters=True, - alphabet="ABCDEFGHIJKLMNOPRSTUVZabcdefghijklmnoprstuvzÁÉÍÓÖÚÜáéíóöúüŐőŰű", -) diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/command/build_ext.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/command/build_ext.py deleted file mode 100644 index cbfe3ec1c28529aade613b000d5b051807287deb..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/command/build_ext.py +++ /dev/null @@ -1,383 +0,0 @@ -import os -import sys -import itertools -from importlib.machinery import EXTENSION_SUFFIXES -from importlib.util import cache_from_source as _compiled_file_name -from typing import Dict, Iterator, List, Tuple - -from distutils.command.build_ext import build_ext as _du_build_ext -from distutils.ccompiler import new_compiler -from distutils.sysconfig import customize_compiler, get_config_var -from distutils import log - -from setuptools.errors import BaseError -from setuptools.extension import Extension, Library - -try: - # Attempt to use Cython for building extensions, if available - from Cython.Distutils.build_ext import build_ext as _build_ext - # Additionally, assert that the compiler module will load - # also. Ref #1229. - __import__('Cython.Compiler.Main') -except ImportError: - _build_ext = _du_build_ext - -# make sure _config_vars is initialized -get_config_var("LDSHARED") -from distutils.sysconfig import _config_vars as _CONFIG_VARS # noqa - - -def _customize_compiler_for_shlib(compiler): - if sys.platform == "darwin": - # building .dylib requires additional compiler flags on OSX; here we - # temporarily substitute the pyconfig.h variables so that distutils' - # 'customize_compiler' uses them before we build the shared libraries. - tmp = _CONFIG_VARS.copy() - try: - # XXX Help! I don't have any idea whether these are right... - _CONFIG_VARS['LDSHARED'] = ( - "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup") - _CONFIG_VARS['CCSHARED'] = " -dynamiclib" - _CONFIG_VARS['SO'] = ".dylib" - customize_compiler(compiler) - finally: - _CONFIG_VARS.clear() - _CONFIG_VARS.update(tmp) - else: - customize_compiler(compiler) - - -have_rtld = False -use_stubs = False -libtype = 'shared' - -if sys.platform == "darwin": - use_stubs = True -elif os.name != 'nt': - try: - import dl - use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW') - except ImportError: - pass - - -def if_dl(s): - return s if have_rtld else '' - - -def get_abi3_suffix(): - """Return the file extension for an abi3-compliant Extension()""" - for suffix in EXTENSION_SUFFIXES: - if '.abi3' in suffix: # Unix - return suffix - elif suffix == '.pyd': # Windows - return suffix - - -class build_ext(_build_ext): - editable_mode: bool = False - inplace: bool = False - - def run(self): - """Build extensions in build directory, then copy if --inplace""" - old_inplace, self.inplace = self.inplace, 0 - _build_ext.run(self) - self.inplace = old_inplace - if old_inplace: - self.copy_extensions_to_source() - - def _get_inplace_equivalent(self, build_py, ext: Extension) -> Tuple[str, str]: - fullname = self.get_ext_fullname(ext.name) - filename = self.get_ext_filename(fullname) - modpath = fullname.split('.') - package = '.'.join(modpath[:-1]) - package_dir = build_py.get_package_dir(package) - inplace_file = os.path.join(package_dir, os.path.basename(filename)) - regular_file = os.path.join(self.build_lib, filename) - return (inplace_file, regular_file) - - def copy_extensions_to_source(self): - build_py = self.get_finalized_command('build_py') - for ext in self.extensions: - inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext) - - # Always copy, even if source is older than destination, to ensure - # that the right extensions for the current Python/platform are - # used. - if os.path.exists(regular_file) or not ext.optional: - self.copy_file(regular_file, inplace_file, level=self.verbose) - - if ext._needs_stub: - inplace_stub = self._get_equivalent_stub(ext, inplace_file) - self._write_stub_file(inplace_stub, ext, compile=True) - # Always compile stub and remove the original (leave the cache behind) - # (this behaviour was observed in previous iterations of the code) - - def _get_equivalent_stub(self, ext: Extension, output_file: str) -> str: - dir_ = os.path.dirname(output_file) - _, _, name = ext.name.rpartition(".") - return f"{os.path.join(dir_, name)}.py" - - def _get_output_mapping(self) -> Iterator[Tuple[str, str]]: - if not self.inplace: - return - - build_py = self.get_finalized_command('build_py') - opt = self.get_finalized_command('install_lib').optimize or "" - - for ext in self.extensions: - inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext) - yield (regular_file, inplace_file) - - if ext._needs_stub: - # This version of `build_ext` always builds artifacts in another dir, - # when "inplace=True" is given it just copies them back. - # This is done in the `copy_extensions_to_source` function, which - # always compile stub files via `_compile_and_remove_stub`. - # At the end of the process, a `.pyc` stub file is created without the - # corresponding `.py`. - - inplace_stub = self._get_equivalent_stub(ext, inplace_file) - regular_stub = self._get_equivalent_stub(ext, regular_file) - inplace_cache = _compiled_file_name(inplace_stub, optimization=opt) - output_cache = _compiled_file_name(regular_stub, optimization=opt) - yield (output_cache, inplace_cache) - - def get_ext_filename(self, fullname): - so_ext = os.getenv('SETUPTOOLS_EXT_SUFFIX') - if so_ext: - filename = os.path.join(*fullname.split('.')) + so_ext - else: - filename = _build_ext.get_ext_filename(self, fullname) - so_ext = get_config_var('EXT_SUFFIX') - - if fullname in self.ext_map: - ext = self.ext_map[fullname] - use_abi3 = getattr(ext, 'py_limited_api') and get_abi3_suffix() - if use_abi3: - filename = filename[:-len(so_ext)] - so_ext = get_abi3_suffix() - filename = filename + so_ext - if isinstance(ext, Library): - fn, ext = os.path.splitext(filename) - return self.shlib_compiler.library_filename(fn, libtype) - elif use_stubs and ext._links_to_dynamic: - d, fn = os.path.split(filename) - return os.path.join(d, 'dl-' + fn) - return filename - - def initialize_options(self): - _build_ext.initialize_options(self) - self.shlib_compiler = None - self.shlibs = [] - self.ext_map = {} - self.editable_mode = False - - def finalize_options(self): - _build_ext.finalize_options(self) - self.extensions = self.extensions or [] - self.check_extensions_list(self.extensions) - self.shlibs = [ext for ext in self.extensions - if isinstance(ext, Library)] - if self.shlibs: - self.setup_shlib_compiler() - for ext in self.extensions: - ext._full_name = self.get_ext_fullname(ext.name) - for ext in self.extensions: - fullname = ext._full_name - self.ext_map[fullname] = ext - - # distutils 3.1 will also ask for module names - # XXX what to do with conflicts? - self.ext_map[fullname.split('.')[-1]] = ext - - ltd = self.shlibs and self.links_to_dynamic(ext) or False - ns = ltd and use_stubs and not isinstance(ext, Library) - ext._links_to_dynamic = ltd - ext._needs_stub = ns - filename = ext._file_name = self.get_ext_filename(fullname) - libdir = os.path.dirname(os.path.join(self.build_lib, filename)) - if ltd and libdir not in ext.library_dirs: - ext.library_dirs.append(libdir) - if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs: - ext.runtime_library_dirs.append(os.curdir) - - if self.editable_mode: - self.inplace = True - - def setup_shlib_compiler(self): - compiler = self.shlib_compiler = new_compiler( - compiler=self.compiler, dry_run=self.dry_run, force=self.force - ) - _customize_compiler_for_shlib(compiler) - - if self.include_dirs is not None: - compiler.set_include_dirs(self.include_dirs) - if self.define is not None: - # 'define' option is a list of (name,value) tuples - for (name, value) in self.define: - compiler.define_macro(name, value) - if self.undef is not None: - for macro in self.undef: - compiler.undefine_macro(macro) - if self.libraries is not None: - compiler.set_libraries(self.libraries) - if self.library_dirs is not None: - compiler.set_library_dirs(self.library_dirs) - if self.rpath is not None: - compiler.set_runtime_library_dirs(self.rpath) - if self.link_objects is not None: - compiler.set_link_objects(self.link_objects) - - # hack so distutils' build_extension() builds a library instead - compiler.link_shared_object = link_shared_object.__get__(compiler) - - def get_export_symbols(self, ext): - if isinstance(ext, Library): - return ext.export_symbols - return _build_ext.get_export_symbols(self, ext) - - def build_extension(self, ext): - ext._convert_pyx_sources_to_lang() - _compiler = self.compiler - try: - if isinstance(ext, Library): - self.compiler = self.shlib_compiler - _build_ext.build_extension(self, ext) - if ext._needs_stub: - build_lib = self.get_finalized_command('build_py').build_lib - self.write_stub(build_lib, ext) - finally: - self.compiler = _compiler - - def links_to_dynamic(self, ext): - """Return true if 'ext' links to a dynamic lib in the same package""" - # XXX this should check to ensure the lib is actually being built - # XXX as dynamic, and not just using a locally-found version or a - # XXX static-compiled version - libnames = dict.fromkeys([lib._full_name for lib in self.shlibs]) - pkg = '.'.join(ext._full_name.split('.')[:-1] + ['']) - return any(pkg + libname in libnames for libname in ext.libraries) - - def get_outputs(self) -> List[str]: - if self.inplace: - return list(self.get_output_mapping().keys()) - return sorted(_build_ext.get_outputs(self) + self.__get_stubs_outputs()) - - def get_output_mapping(self) -> Dict[str, str]: - """See :class:`setuptools.commands.build.SubCommand`""" - mapping = self._get_output_mapping() - return dict(sorted(mapping, key=lambda x: x[0])) - - def __get_stubs_outputs(self): - # assemble the base name for each extension that needs a stub - ns_ext_bases = ( - os.path.join(self.build_lib, *ext._full_name.split('.')) - for ext in self.extensions - if ext._needs_stub - ) - # pair each base with the extension - pairs = itertools.product(ns_ext_bases, self.__get_output_extensions()) - return list(base + fnext for base, fnext in pairs) - - def __get_output_extensions(self): - yield '.py' - yield '.pyc' - if self.get_finalized_command('build_py').optimize: - yield '.pyo' - - def write_stub(self, output_dir, ext, compile=False): - stub_file = os.path.join(output_dir, *ext._full_name.split('.')) + '.py' - self._write_stub_file(stub_file, ext, compile) - - def _write_stub_file(self, stub_file: str, ext: Extension, compile=False): - log.info("writing stub loader for %s to %s", ext._full_name, stub_file) - if compile and os.path.exists(stub_file): - raise BaseError(stub_file + " already exists! Please delete.") - if not self.dry_run: - f = open(stub_file, 'w') - f.write( - '\n'.join([ - "def __bootstrap__():", - " global __bootstrap__, __file__, __loader__", - " import sys, os, pkg_resources, importlib.util" + - if_dl(", dl"), - " __file__ = pkg_resources.resource_filename" - "(__name__,%r)" - % os.path.basename(ext._file_name), - " del __bootstrap__", - " if '__loader__' in globals():", - " del __loader__", - if_dl(" old_flags = sys.getdlopenflags()"), - " old_dir = os.getcwd()", - " try:", - " os.chdir(os.path.dirname(__file__))", - if_dl(" sys.setdlopenflags(dl.RTLD_NOW)"), - " spec = importlib.util.spec_from_file_location(", - " __name__, __file__)", - " mod = importlib.util.module_from_spec(spec)", - " spec.loader.exec_module(mod)", - " finally:", - if_dl(" sys.setdlopenflags(old_flags)"), - " os.chdir(old_dir)", - "__bootstrap__()", - "" # terminal \n - ]) - ) - f.close() - if compile: - self._compile_and_remove_stub(stub_file) - - def _compile_and_remove_stub(self, stub_file: str): - from distutils.util import byte_compile - - byte_compile([stub_file], optimize=0, - force=True, dry_run=self.dry_run) - optimize = self.get_finalized_command('install_lib').optimize - if optimize > 0: - byte_compile([stub_file], optimize=optimize, - force=True, dry_run=self.dry_run) - if os.path.exists(stub_file) and not self.dry_run: - os.unlink(stub_file) - - -if use_stubs or os.name == 'nt': - # Build shared libraries - # - def link_shared_object( - self, objects, output_libname, output_dir=None, libraries=None, - library_dirs=None, runtime_library_dirs=None, export_symbols=None, - debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, - target_lang=None): - self.link( - self.SHARED_LIBRARY, objects, output_libname, - output_dir, libraries, library_dirs, runtime_library_dirs, - export_symbols, debug, extra_preargs, extra_postargs, - build_temp, target_lang - ) -else: - # Build static libraries everywhere else - libtype = 'static' - - def link_shared_object( - self, objects, output_libname, output_dir=None, libraries=None, - library_dirs=None, runtime_library_dirs=None, export_symbols=None, - debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, - target_lang=None): - # XXX we need to either disallow these attrs on Library instances, - # or warn/abort here if set, or something... - # libraries=None, library_dirs=None, runtime_library_dirs=None, - # export_symbols=None, extra_preargs=None, extra_postargs=None, - # build_temp=None - - assert output_dir is None # distutils build_ext doesn't pass this - output_dir, filename = os.path.split(output_libname) - basename, ext = os.path.splitext(filename) - if self.library_filename("x").startswith('lib'): - # strip 'lib' prefix; this is kludgy if some platform uses - # a different prefix - basename = basename[3:] - - self.create_static_lib( - objects, basename, output_dir, debug, target_lang - ) diff --git a/spaces/BigSalmon/AbstractTwst/README.md b/spaces/BigSalmon/AbstractTwst/README.md deleted file mode 100644 index f485e5eeb2320cf768d5ecb2066f92c302774b4f..0000000000000000000000000000000000000000 --- a/spaces/BigSalmon/AbstractTwst/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: AbstractTwst -emoji: 🐨 -colorFrom: yellow -colorTo: green -sdk: streamlit -sdk_version: 1.21.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/Bingsu/color_textual_inversion/app.py b/spaces/Bingsu/color_textual_inversion/app.py deleted file mode 100644 index 9cbe8c85812235cbef406b1c0f889a1cd4e15a36..0000000000000000000000000000000000000000 --- a/spaces/Bingsu/color_textual_inversion/app.py +++ /dev/null @@ -1,128 +0,0 @@ -from __future__ import annotations - -import shlex -import subprocess -from pathlib import Path -from tempfile import TemporaryDirectory -from textwrap import dedent - -import numpy as np -import streamlit as st -import torch -from PIL import Image -from transformers import CLIPTokenizer - - -def hex_to_rgb(s: str) -> tuple[int, int, int]: - value = s.lstrip("#") - return (int(value[:2], 16), int(value[2:4], 16), int(value[4:6], 16)) - - -st.header("Color Textual Inversion") -with st.expander(label="info"): - with open("info.txt", "r", encoding="utf-8") as f: - st.markdown(f.read()) - -duplicate_button = """Duplicate Space""" -st.markdown(duplicate_button, unsafe_allow_html=True) - -col1, col2 = st.columns([15, 85]) -color = col1.color_picker("Pick a color", "#00f900") -col2.text_input("", color, disabled=True) - -emb_name = st.text_input("Embedding name", color.lstrip("#").upper()) -init_token = st.text_input("Initializer token", "init token name") -rgb = hex_to_rgb(color) - -img_array = np.zeros((128, 128, 3), dtype=np.uint8) -for i in range(3): - img_array[..., i] = rgb[i] - -dataset_temp = TemporaryDirectory(prefix="dataset_", dir=".") -dataset_path = Path(dataset_temp.name) -output_temp = TemporaryDirectory(prefix="output_", dir=".") -output_path = Path(output_temp.name) - -img_path = dataset_path / f"{emb_name}.png" -Image.fromarray(img_array).save(img_path) - -with st.sidebar: - model_name = st.text_input("Model name", "Linaqruf/anything-v3.0") - steps = st.slider("Steps", 1, 100, value=1, step=1) - learning_rate = st.text_input("Learning rate", "0.001") - learning_rate = float(learning_rate) - -tokenizer = CLIPTokenizer.from_pretrained(model_name, subfolder="tokenizer") - -# case 1: init_token is not a single token -token = tokenizer.tokenize(init_token) -if len(token) > 1: - st.warning("Initializer token must be a single token") - st.stop() - -# case 2: init_token already exists in the tokenizer -num_added_tokens = tokenizer.add_tokens(emb_name) -if num_added_tokens == 0: - st.warning(f"The tokenizer already contains the token {emb_name}") - st.stop() - -cmd = """ -accelerate launch textual_inversion.py \ - --pretrained_model_name_or_path={model_name} \ - --train_data_dir={dataset_path} \ - --learnable_property="style" \ - --placeholder_token="{emb_name}" \ - --initializer_token="{init}" \ - --resolution=128 \ - --train_batch_size=1 \ - --repeats=1 \ - --gradient_accumulation_steps=1 \ - --max_train_steps={steps} \ - --learning_rate={lr} \ - --output_dir={output_path} \ - --only_save_embeds -""".strip() - -cmd = dedent(cmd).format( - model_name=model_name, - dataset_path=dataset_path.as_posix(), - emb_name=emb_name, - init=init_token, - steps=steps, - lr=learning_rate, - output_path=output_path.as_posix(), -) -cmd = shlex.split(cmd) - -result_path = output_path / "learned_embeds.bin" -captured = "" - -start_button = st.button("Start") -download_button = st.empty() - -if start_button: - with st.spinner("Training..."): - placeholder = st.empty() - p = subprocess.Popen( - cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8" - ) - - while line := p.stderr.readline(): - captured += line - placeholder.code(captured, language="bash") - -if not result_path.exists(): - st.stop() - -# fix unknown file volume bug -trained_emb = torch.load(result_path, map_location="cpu") -for k, v in trained_emb.items(): - trained_emb[k] = torch.from_numpy(v.numpy()) -torch.save(trained_emb, result_path) - -file = result_path.read_bytes() -download_button.download_button(f"Download {emb_name}.pt", file, f"{emb_name}.pt") -st.download_button(f"Download {emb_name}.pt ", file, f"{emb_name}.pt") - -dataset_temp.cleanup() -output_temp.cleanup() diff --git a/spaces/BridgeEight/internlm-20B-chat-w4-turbomind/app.py b/spaces/BridgeEight/internlm-20B-chat-w4-turbomind/app.py deleted file mode 100644 index 1786359ea4fd70c91d59beb49e40174366cc04b8..0000000000000000000000000000000000000000 --- a/spaces/BridgeEight/internlm-20B-chat-w4-turbomind/app.py +++ /dev/null @@ -1,128 +0,0 @@ -import os,random -os.system('sh install_lmdeploy.sh') -import gradio as gr -from lmdeploy.serve.gradio.app import * -os.system('sh download.sh') - -InterFace.async_engine = AsyncEngine(model_path='turbomind-internlm-chat-20b-w4', - instance_num=2, - tp=1) - - -async def reset_local_demo(instruction_txtbox: gr.Textbox, - state_chatbot: gr.State, request: gr.Request): - """reset the session. - - Args: - instruction_txtbox (str): user's prompt - state_chatbot (Sequence): the chatting history - request (gr.Request): the request from a user - """ - state_chatbot = [] - - return ( - state_chatbot, - state_chatbot, - gr.Textbox.update(value=''), - ) - - -async def cancel_local_demo(state_chatbot: gr.State, cancel_btn: gr.Button, - reset_btn: gr.Button, request: gr.Request): - """stop the session. - - Args: - instruction_txtbox (str): user's prompt - state_chatbot (Sequence): the chatting history - request (gr.Request): the request from a user - """ - return (state_chatbot, disable_btn, disable_btn) - -async def chat_stream_demo( - instruction: str, - state_chatbot: Sequence, - cancel_btn: gr.Button, - reset_btn: gr.Button, - request: gr.Request, -): - """Chat with AI assistant. - - Args: - instruction (str): user's prompt - state_chatbot (Sequence): the chatting history - request (gr.Request): the request from a user - """ - session_id = random.randint(0,100000) - bot_summarized_response = '' - state_chatbot = state_chatbot + [(instruction, None)] - messages = [] - for item in state_chatbot: - messages.append(dict(role='user', content=item[0])) - if item[1] is not None: - messages.append(dict(role='assistant', content=item[1])) - - yield (state_chatbot, state_chatbot, disable_btn, disable_btn, - f'{bot_summarized_response}'.strip()) - - async for outputs in InterFace.async_engine.generate( - messages, - session_id, - stream_response=True, - sequence_start=True, - sequence_end=True): - response = outputs.response - if outputs.finish_reason == 'length': - gr.Warning('WARNING: exceed session max length.' - ' Please restart the session by reset button.') - if outputs.generate_token_len < 0: - gr.Warning('WARNING: running on the old session.' - ' Please restart the session by reset button.') - if state_chatbot[-1][-1] is None: - state_chatbot[-1] = (state_chatbot[-1][0], response) - else: - state_chatbot[-1] = (state_chatbot[-1][0], - state_chatbot[-1][1] + response - ) # piece by piece - yield (state_chatbot, state_chatbot, disable_btn, disable_btn, - f'{bot_summarized_response}'.strip()) - - yield (state_chatbot, state_chatbot, disable_btn, disable_btn, - f'{bot_summarized_response}'.strip()) - - -with gr.Blocks(css=CSS, theme=THEME) as demo: - state_chatbot = gr.State([]) - - with gr.Column(elem_id='container'): - gr.Markdown('## LMDeploy Playground') - - chatbot = gr.Chatbot( - elem_id='chatbot', - label=InterFace.async_engine.tm_model.model_name) - instruction_txtbox = gr.Textbox( - placeholder='Please input the instruction', - label='Instruction') - with gr.Row(): - cancel_btn = gr.Button(value='Cancel', interactive=False, visible=False) - reset_btn = gr.Button(value='Reset', interactive=False, visible=False) - - send_event = instruction_txtbox.submit( - chat_stream_demo, - [instruction_txtbox, state_chatbot, cancel_btn, reset_btn], - [state_chatbot, chatbot, cancel_btn, reset_btn]) - instruction_txtbox.submit( - lambda: gr.Textbox.update(value=''), - [], - [instruction_txtbox], - ) - cancel_btn.click(cancel_local_demo, - [state_chatbot, cancel_btn, reset_btn], - [state_chatbot, cancel_btn, reset_btn], - cancels=[send_event]) - - reset_btn.click(reset_local_demo, [instruction_txtbox, state_chatbot], - [state_chatbot, chatbot, instruction_txtbox], - cancels=[send_event]) - -# print(f'server is gonna mount on: http://{server_name}:{server_port}') - demo.queue(concurrency_count=4, max_size=100).launch() diff --git a/spaces/CVPR/LIVE/thrust/thrust/host_vector.h b/spaces/CVPR/LIVE/thrust/thrust/host_vector.h deleted file mode 100644 index ebe64216e284b8ba1e19cfa6950df3ab1d58f331..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/host_vector.h +++ /dev/null @@ -1,514 +0,0 @@ -/* - * Copyright 2008-2018 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 host_vector.h - * \brief A dynamically-sizable array of elements which reside in the "host" memory space - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace thrust -{ - -// forward declaration of device_vector -template class device_vector; - -/*! \addtogroup container_classes Container Classes - * \addtogroup host_containers Host Containers - * \ingroup container_classes - * \{ - */ - -/*! A \p host_vector is a container that supports random access to elements, - * constant time removal of elements at the end, and linear time insertion - * and removal of elements at the beginning or in the middle. The number of - * elements in a \p host_vector may vary dynamically; memory management is - * automatic. The memory associated with a \p host_vector resides in the memory - * space of the host associated with a parallel device. - * - * \see http://www.sgi.com/tech/stl/Vector.html - * \see device_vector - */ -template > - class host_vector - : public detail::vector_base -{ - private: - typedef detail::vector_base Parent; - - public: - /*! \cond - */ - typedef typename Parent::size_type size_type; - typedef typename Parent::value_type value_type; - /*! \endcond - */ - - /*! This constructor creates an empty \p host_vector. - */ - __host__ - host_vector(void) - :Parent() {} - - /*! This constructor creates an empty \p host_vector. - * \param alloc The allocator to use by this host_vector. - */ - __host__ - host_vector(const Alloc &alloc) - :Parent(alloc) {} - - /*! The destructor erases the elements. - */ - // Define an empty destructor to explicitly specify - // its execution space qualifier, as a workaround for nvcc warning - __host__ - ~host_vector(void) {} - - /*! This constructor creates a \p host_vector with the given - * size. - * \param n The number of elements to initially create. - */ - __host__ - explicit host_vector(size_type n) - :Parent(n) {} - - /*! This constructor creates a \p host_vector with the given - * size. - * \param n The number of elements to initially create. - * \param alloc The allocator to use by this host_vector. - */ - __host__ - explicit host_vector(size_type n, const Alloc &alloc) - :Parent(n,alloc) {} - - /*! This constructor creates a \p host_vector with copies - * of an exemplar element. - * \param n The number of elements to initially create. - * \param value An element to copy. - */ - __host__ - explicit host_vector(size_type n, const value_type &value) - :Parent(n,value) {} - - /*! This constructor creates a \p host_vector with copies - * of an exemplar element. - * \param n The number of elements to initially create. - * \param value An element to copy. - * \param alloc The allocator to use by this host_vector. - */ - __host__ - explicit host_vector(size_type n, const value_type &value, const Alloc &alloc) - :Parent(n,value,alloc) {} - - /*! Copy constructor copies from an exemplar \p host_vector. - * \param v The \p host_vector to copy. - */ - __host__ - host_vector(const host_vector &v) - :Parent(v) {} - - /*! Copy constructor copies from an exemplar \p host_vector. - * \param v The \p host_vector to copy. - * \param alloc The allocator to use by this host_vector. - */ - __host__ - host_vector(const host_vector &v, const Alloc &alloc) - :Parent(v,alloc) {} - - #if THRUST_CPP_DIALECT >= 2011 - /*! Move constructor moves from another host_vector. - * \param v The host_vector to move. - */ - __host__ - host_vector(host_vector &&v) - :Parent(std::move(v)) {} - - /*! Move constructor moves from another host_vector. - * \param v The host_vector to move. - * \param alloc The allocator to use by this host_vector. - */ - __host__ - host_vector(host_vector &&v, const Alloc &alloc) - :Parent(std::move(v),alloc) {} - #endif - - /*! Assign operator copies from an exemplar \p host_vector. - * \param v The \p host_vector to copy. - */ - __host__ - host_vector &operator=(const host_vector &v) - { Parent::operator=(v); return *this; } - - #if THRUST_CPP_DIALECT >= 2011 - /*! Move assign operator moves from another host_vector. - * \param v The host_vector to move. - */ - __host__ - host_vector &operator=(host_vector &&v) - { Parent::operator=(std::move(v)); return *this; } - #endif - - /*! Copy constructor copies from an exemplar \p host_vector with different type. - * \param v The \p host_vector to copy. - */ - template - __host__ - host_vector(const host_vector &v) - :Parent(v) {} - - /*! Assign operator copies from an exemplar \p host_vector with different type. - * \param v The \p host_vector to copy. - */ - template - __host__ - host_vector &operator=(const host_vector &v) - { Parent::operator=(v); return *this; } - - /*! Copy constructor copies from an exemplar std::vector. - * \param v The std::vector to copy. - */ - template - __host__ - host_vector(const std::vector &v) - :Parent(v) {} - - /*! Assign operator copies from an exemplar std::vector. - * \param v The std::vector to copy. - */ - template - __host__ - host_vector &operator=(const std::vector &v) - { Parent::operator=(v); return *this;} - - /*! Copy constructor copies from an exemplar \p device_vector with possibly different type. - * \param v The \p device_vector to copy. - */ - template - __host__ - host_vector(const device_vector &v); - - /*! Assign operator copies from an exemplar \p device_vector. - * \param v The \p device_vector to copy. - */ - template - __host__ - host_vector &operator=(const device_vector &v) - { Parent::operator=(v); return *this; } - - /*! This constructor builds a \p host_vector from a range. - * \param first The beginning of the range. - * \param last The end of the range. - */ - template - __host__ - host_vector(InputIterator first, InputIterator last) - :Parent(first, last) {} - - /*! This constructor builds a \p host_vector from a range. - * \param first The beginning of the range. - * \param last The end of the range. - * \param alloc The allocator to use by this host_vector. - */ - template - __host__ - host_vector(InputIterator first, InputIterator last, const Alloc &alloc) - :Parent(first, last, alloc) {} - -// declare these members for the purpose of Doxygenating them -// they actually exist in a derived-from class -#if 0 - /*! \brief Resizes this vector to the specified number of elements. - * \param new_size Number of elements this vector should contain. - * \param x Data with which new elements should be populated. - * \throw std::length_error If n exceeds max_size(). - * - * This method will resize this vector to the specified number of - * elements. If the number is smaller than this vector's current - * size this vector is truncated, otherwise this vector is - * extended and new elements are populated with given data. - */ - void resize(size_type new_size, const value_type &x = value_type()); - - /*! Returns the number of elements in this vector. - */ - size_type size(void) const; - - /*! Returns the size() of the largest possible vector. - * \return The largest possible return value of size(). - */ - size_type max_size(void) const; - - /*! \brief If n is less than or equal to capacity(), this call has no effect. - * Otherwise, this method is a request for allocation of additional memory. If - * the request is successful, then capacity() is greater than or equal to - * n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - * \throw std::length_error If n exceeds max_size(). - */ - void reserve(size_type n); - - /*! Returns the number of elements which have been reserved in this - * vector. - */ - size_type capacity(void) const; - - /*! This method shrinks the capacity of this vector to exactly - * fit its elements. - */ - void shrink_to_fit(void); - - /*! \brief Subscript access to the data contained in this vector_dev. - * \param n The index of the element for which data should be accessed. - * \return Read/write reference to data. - * - * This operator allows for easy, array-style, data access. - * Note that data access with this operator is unchecked and - * out_of_range lookups are not defined. - */ - reference operator[](size_type n); - - /*! \brief Subscript read access to the data contained in this vector_dev. - * \param n The index of the element for which data should be accessed. - * \return Read reference to data. - * - * This operator allows for easy, array-style, data access. - * Note that data access with this operator is unchecked and - * out_of_range lookups are not defined. - */ - const_reference operator[](size_type n) const; - - /*! This method returns an iterator pointing to the beginning of - * this vector. - * \return mStart - */ - iterator begin(void); - - /*! This method returns a const_iterator pointing to the beginning - * of this vector. - * \return mStart - */ - const_iterator begin(void) const; - - /*! This method returns a const_iterator pointing to the beginning - * of this vector. - * \return mStart - */ - const_iterator cbegin(void) const; - - /*! This method returns a reverse_iterator pointing to the beginning of - * this vector's reversed sequence. - * \return A reverse_iterator pointing to the beginning of this - * vector's reversed sequence. - */ - reverse_iterator rbegin(void); - - /*! This method returns a const_reverse_iterator pointing to the beginning of - * this vector's reversed sequence. - * \return A const_reverse_iterator pointing to the beginning of this - * vector's reversed sequence. - */ - const_reverse_iterator rbegin(void) const; - - /*! This method returns a const_reverse_iterator pointing to the beginning of - * this vector's reversed sequence. - * \return A const_reverse_iterator pointing to the beginning of this - * vector's reversed sequence. - */ - const_reverse_iterator crbegin(void) const; - - /*! This method returns an iterator pointing to one element past the - * last of this vector. - * \return begin() + size(). - */ - iterator end(void); - - /*! This method returns a const_iterator pointing to one element past the - * last of this vector. - * \return begin() + size(). - */ - const_iterator end(void) const; - - /*! This method returns a const_iterator pointing to one element past the - * last of this vector. - * \return begin() + size(). - */ - const_iterator cend(void) const; - - /*! This method returns a reverse_iterator pointing to one element past the - * last of this vector's reversed sequence. - * \return rbegin() + size(). - */ - reverse_iterator rend(void); - - /*! This method returns a const_reverse_iterator pointing to one element past the - * last of this vector's reversed sequence. - * \return rbegin() + size(). - */ - const_reverse_iterator rend(void) const; - - /*! This method returns a const_reverse_iterator pointing to one element past the - * last of this vector's reversed sequence. - * \return rbegin() + size(). - */ - const_reverse_iterator crend(void) const; - - /*! This method returns a const_reference referring to the first element of this - * vector. - * \return The first element of this vector. - */ - const_reference front(void) const; - - /*! This method returns a reference pointing to the first element of this - * vector. - * \return The first element of this vector. - */ - reference front(void); - - /*! This method returns a const reference pointing to the last element of - * this vector. - * \return The last element of this vector. - */ - const_reference back(void) const; - - /*! This method returns a reference referring to the last element of - * this vector_dev. - * \return The last element of this vector. - */ - reference back(void); - - /*! This method returns a pointer to this vector's first element. - * \return A pointer to the first element of this vector. - */ - pointer data(void); - - /*! This method returns a const_pointer to this vector's first element. - * \return a const_pointer to the first element of this vector. - */ - const_pointer data(void) const; - - /*! This method resizes this vector to 0. - */ - void clear(void); - - /*! This method returns true iff size() == 0. - * \return true if size() == 0; false, otherwise. - */ - bool empty(void) const; - - /*! This method appends the given element to the end of this vector. - * \param x The element to append. - */ - void push_back(const value_type &x); - - /*! This method erases the last element of this vector, invalidating - * all iterators and references to it. - */ - void pop_back(void); - - /*! This method swaps the contents of this host_vector with another vector. - * \param v The vector with which to swap. - */ - void swap(host_vector &v); - - /*! This method removes the element at position pos. - * \param pos The position of the element of interest. - * \return An iterator pointing to the new location of the element that followed the element - * at position pos. - */ - iterator erase(iterator pos); - - /*! This method removes the range of elements [first,last) from this vector. - * \param first The beginning of the range of elements to remove. - * \param last The end of the range of elements to remove. - * \return An iterator pointing to the new location of the element that followed the last - * element in the sequence [first,last). - */ - iterator erase(iterator first, iterator last); - - /*! This method inserts a single copy of a given exemplar value at the - * specified position in this vector. - * \param position The insertion position. - * \param x The exemplar element to copy & insert. - * \return An iterator pointing to the newly inserted element. - */ - iterator insert(iterator position, const T &x); - - /*! This method inserts a copy of an exemplar value to a range at the - * specified position in this vector. - * \param position The insertion position - * \param n The number of insertions to perform. - * \param x The value to replicate and insert. - */ - void insert(iterator position, size_type n, const T &x); - - /*! This method inserts a copy of an input range at the specified position - * in this vector. - * \param position The insertion position. - * \param first The beginning of the range to copy. - * \param last The end of the range to copy. - * - * \tparam InputIterator is a model of Assignable. - */ - template - void insert(iterator position, InputIterator first, InputIterator last); - - /*! This version of \p assign replicates a given exemplar - * \p n times into this vector. - * \param n The number of times to copy \p x. - * \param x The exemplar element to replicate. - */ - void assign(size_type n, const T &x); - - /*! This version of \p assign makes this vector a copy of a given input range. - * \param first The beginning of the range to copy. - * \param last The end of the range to copy. - * - * \tparam InputIterator is a model of Input Iterator. - */ - template - void assign(InputIterator first, InputIterator last); - - /*! This method returns a copy of this vector's allocator. - * \return A copy of the alloctor used by this vector. - */ - allocator_type get_allocator(void) const; -#endif // end doxygen-only members -}; // end host_vector - -/*! Exchanges the values of two vectors. - * \p x The first \p host_vector of interest. - * \p y The second \p host_vector of interest. - */ -template - void swap(host_vector &a, host_vector &b) -{ - a.swap(b); -} // end swap() - -/*! \} - */ - -} // end thrust - -#include - diff --git a/spaces/CVPR/ml-talking-face/app.py b/spaces/CVPR/ml-talking-face/app.py deleted file mode 100644 index fb4086a0d0f8acee7413f7cdc72a3b56d87c1fce..0000000000000000000000000000000000000000 --- a/spaces/CVPR/ml-talking-face/app.py +++ /dev/null @@ -1,202 +0,0 @@ -# https://huggingface.co/deepkyu/ml-talking-face -import os -import subprocess - -REST_IP = os.environ['REST_IP'] -SERVICE_PORT = int(os.environ['SERVICE_PORT']) -TRANSLATION_APIKEY_URL = os.environ['TRANSLATION_APIKEY_URL'] -GOOGLE_APPLICATION_CREDENTIALS = os.environ['GOOGLE_APPLICATION_CREDENTIALS'] -subprocess.call(f"wget --no-check-certificate -O {GOOGLE_APPLICATION_CREDENTIALS} {TRANSLATION_APIKEY_URL}", shell=True) - -TOXICITY_THRESHOLD = float(os.getenv('TOXICITY_THRESHOLD', 0.7)) - -import gradio as gr -from toxicity_estimator import PerspectiveAPI -from translator import Translator -from client_rest import RestAPIApplication -from pathlib import Path -import argparse -import threading -import yaml - -TITLE = Path("docs/title.txt").read_text() -DESCRIPTION = Path("docs/description.md").read_text() - - -class GradioApplication: - def __init__(self, rest_ip, rest_port, max_seed): - self.lang_list = { - 'ko': 'ko_KR', - 'en': 'en_US', - 'ja': 'ja_JP', - 'zh': 'zh_CN', - 'zh-CN': 'zh_CN' - } - self.background_list = [None, - "background_image/cvpr.png", - "background_image/black.png", - "background_image/river.mp4", - "background_image/sky.mp4"] - - self.perspective_api = PerspectiveAPI() - self.translator = Translator() - self.rest_application = RestAPIApplication(rest_ip, rest_port) - self.output_dir = Path("output_file") - - inputs = prepare_input() - outputs = prepare_output() - - self.iface = gr.Interface(fn=self.infer, - title=TITLE, - description=DESCRIPTION, - inputs=inputs, - outputs=outputs, - allow_flagging='never', - article=Path("docs/article.md").read_text()) - - self.max_seed = max_seed - self._file_seed = 0 - self.lock = threading.Lock() - - - def _get_file_seed(self): - return f"{self._file_seed % self.max_seed:02d}" - - def _reset_file_seed(self): - self._file_seed = 0 - - def _counter_file_seed(self): - with self.lock: - self._file_seed += 1 - - def get_lang_code(self, lang): - return self.lang_list[lang] - - def get_background_data(self, background_index): - # get background filename and its extension - data_path = self.background_list[background_index] - - if data_path is not None: - with open(data_path, 'rb') as rf: - background_data = rf.read() - is_video_background = str(data_path).endswith(".mp4") - else: - background_data = None - is_video_background = False - - return background_data, is_video_background - - @staticmethod - def return_format(toxicity_prob, target_text, lang_dest, video_filename, detail=""): - return {'Toxicity': toxicity_prob}, f"Language: {lang_dest}\nText: {target_text}\n-\nDetails: {detail}", str(video_filename) - - def infer(self, text, lang, duration_rate, action, background_index): - self._counter_file_seed() - print(f"File Seed: {self._file_seed}") - toxicity_prob = 0.0 - target_text = "" - lang_dest = "" - video_filename = "vacant.mp4" - - # Toxicity estimation - try: - toxicity_prob = self.perspective_api.get_score(text) - except Exception as e: # when Perspective API doesn't work - pass - - if toxicity_prob > TOXICITY_THRESHOLD: - detail = "Sorry, it seems that the input text is too toxic." - return self.return_format(toxicity_prob, target_text, lang_dest, video_filename, detail=f"Error: {detail}") - - # Google Translate API - try: - target_text, lang_dest = self.translator.get_translation(text, lang) - except Exception as e: - target_text = "" - lang_dest = "" - detail = f"Error from language translation: ({e})" - return self.return_format(toxicity_prob, target_text, lang_dest, video_filename, detail=f"Error: {detail}") - - try: - self.translator.length_check(lang_dest, target_text) # assertion check - except AssertionError as e: - return self.return_format(toxicity_prob, target_text, lang_dest, video_filename, detail=f"Error: {str(e)}") - - lang_rpc_code = self.get_lang_code(lang_dest) - - # Video Inference - background_data, is_video_background = self.get_background_data(background_index) - - video_data = self.rest_application.get_video(target_text, lang_rpc_code, duration_rate, action.lower(), - background_data, is_video_background) - print(f"Video data size: {len(video_data)}") - - video_filename = self.output_dir / f"{self._file_seed:02d}.mkv" - with open(video_filename, "wb") as video_file: - video_file.write(video_data) - - return self.return_format(toxicity_prob, target_text, lang_dest, video_filename) - - def run(self, server_port=7860, share=False): - try: - self.iface.launch(height=900, - share=share, server_port=server_port, - enable_queue=True) - - except KeyboardInterrupt: - gr.close_all() - - -def prepare_input(): - text_input = gr.Textbox(lines=2, - placeholder="Type your text with English, Chinese, Korean, and Japanese.", - value="Hello, this is demonstration for talking face generation " - "with multilingual text-to-speech.", - label="Text") - lang_input = gr.Radio(['Korean', 'English', 'Japanese', 'Chinese'], - type='value', - value=None, - label="Language") - duration_rate_input = gr.Slider(minimum=0.8, - maximum=1.2, - step=0.01, - value=1.0, - label="Duration (The bigger the value, the slower the speech)") - action_input = gr.Radio(['Default', 'Hand', 'BothHand', 'HandDown', 'Sorry'], - type='value', - value='Default', - label="Select an action ...") - background_input = gr.Radio(['None', 'CVPR', 'Black', 'River', 'Sky'], - type='index', - value='None', - label="Select a background image/video ...") - - return [text_input, lang_input, duration_rate_input, - action_input, background_input] - - -def prepare_output(): - toxicity_output = gr.Label(num_top_classes=1, label="Toxicity (from Perspective API)") - translation_result_otuput = gr.Textbox(type="str", label="Translation Result") - video_output = gr.Video(format='mp4') - return [toxicity_output, translation_result_otuput, video_output] - - -def parse_args(): - parser = argparse.ArgumentParser( - description='GRADIO DEMO for talking face generation submitted to CVPR2022') - parser.add_argument('-p', '--port', dest='gradio_port', type=int, default=7860, help="Port for gradio") - parser.add_argument('--rest_ip', type=str, default=REST_IP, help="IP for REST API") - parser.add_argument('--rest_port', type=int, default=SERVICE_PORT, help="Port for REST API") - parser.add_argument('--max_seed', type=int, default=20, help="Max seed for saving video") - parser.add_argument('--share', action='store_true', help='get publicly sharable link') - args = parser.parse_args() - return args - - -if __name__ == '__main__': - args = parse_args() - - gradio_application = GradioApplication(args.rest_ip, args.rest_port, args.max_seed) - gradio_application.run(server_port=args.gradio_port, share=args.share) - diff --git a/spaces/CikeyQI/Yunzai/Yunzai/plugins/ws-plugin/resources/admin/index.css b/spaces/CikeyQI/Yunzai/Yunzai/plugins/ws-plugin/resources/admin/index.css deleted file mode 100644 index 77a4b5dd95a9f1a41aa857375fe5d5d5cccf394b..0000000000000000000000000000000000000000 --- a/spaces/CikeyQI/Yunzai/Yunzai/plugins/ws-plugin/resources/admin/index.css +++ /dev/null @@ -1,75 +0,0 @@ -body { - transform: scale(1); - width: 660px; -} -.container { - background: url("./imgs/bg.png") #000144 left top repeat-y; - background-size: 700px auto; - width: 660px; -} -.head-box { - margin: 0 0 80px 0; -} -.cfg-box { - border-radius: 15px; - margin-top: 20px; - margin-bottom: 20px; - padding: 5px 15px; - overflow: hidden; - background: #f5f5f5; - box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.15); - position: relative; - background: rgba(35, 38, 57, 0.8); -} -.cfg-group { - color: #ceb78b; - font-size: 18px; - font-weight: bold; - padding: 10px 20px; -} -.cfg-li { - border-radius: 18px; - min-height: 36px; - position: relative; - overflow: hidden; - margin-bottom: 10px; - background: rgba(203, 196, 190, 0); -} -.cfg-line { - color: #4e5769; - line-height: 36px; - padding-left: 20px; - font-weight: bold; - border-radius: 16px; - box-shadow: 0 0 2px rgba(0, 0, 0, 0.5); - background: url("./imgs/cfg-right.jpg") right top #cbc4be no-repeat; - background-size: auto 36px; -} -.cfg-hint { - font-size: 12px; - font-weight: normal; - margin-top: 3px; - margin-bottom: -3px; -} -.cfg-status { - position: absolute; - top: 0; - right: 0; - height: 36px; - width: 160px; - text-align: center; - line-height: 36px; - font-size: 16px; - color: #495366; - font-weight: bold; - border-radius: 0 16px 16px 0; -} -.cfg-status.status-off { - color: #a95151; -} -.cfg-desc { - font-size: 12px; - color: #cbc4be; - margin: 5px 0 5px 20px; -} -/*# sourceMappingURL=index.css.map */ \ No newline at end of file diff --git a/spaces/CikeyQI/meme-api/meme_generator/memes/dianzhongdian/__init__.py b/spaces/CikeyQI/meme-api/meme_generator/memes/dianzhongdian/__init__.py deleted file mode 100644 index 22afc158c4335191c3aecdc15bfbe96df6a0e639..0000000000000000000000000000000000000000 --- a/spaces/CikeyQI/meme-api/meme_generator/memes/dianzhongdian/__init__.py +++ /dev/null @@ -1,65 +0,0 @@ -from typing import List - -from pil_utils import BuildImage - -from meme_generator import add_meme -from meme_generator.exception import TextOverLength -from meme_generator.utils import run_sync, translate - - -@run_sync -def _dianzhongdian(img: BuildImage, text: str, trans: str): - img = img.convert("L").resize_width(500) - text_img1 = BuildImage.new("RGBA", (500, 60)) - text_img2 = BuildImage.new("RGBA", (500, 35)) - - try: - text_img1.draw_text( - (20, 0, text_img1.width - 20, text_img1.height), - text, - max_fontsize=50, - min_fontsize=25, - fill="white", - ) - except ValueError: - raise TextOverLength(text) - - try: - text_img2.draw_text( - (20, 0, text_img2.width - 20, text_img2.height), - trans, - max_fontsize=25, - min_fontsize=10, - fill="white", - ) - except ValueError: - raise TextOverLength(text) - - frame = BuildImage.new("RGBA", (500, img.height + 100), "black") - frame.paste(img, alpha=True) - frame.paste(text_img1, (0, img.height), alpha=True) - frame.paste(text_img2, (0, img.height + 60), alpha=True) - return frame.save_jpg() - - -async def dianzhongdian(images: List[BuildImage], texts: List[str], args): - if len(texts) == 1: - text = texts[0] - trans = await translate(text, lang_to="jp") - else: - text = texts[0] - trans = texts[1] - - return await _dianzhongdian(images[0], text, trans) - - -add_meme( - "dianzhongdian", - dianzhongdian, - min_images=1, - max_images=1, - min_texts=1, - max_texts=2, - default_texts=["救命啊"], - keywords=["入典", "典中典", "黑白草图"], -) diff --git a/spaces/CikeyQI/meme-api/meme_generator/memes/look_flat/__init__.py b/spaces/CikeyQI/meme-api/meme_generator/memes/look_flat/__init__.py deleted file mode 100644 index fd2af58ab7748628f2ac162778d76cdd314beed9..0000000000000000000000000000000000000000 --- a/spaces/CikeyQI/meme-api/meme_generator/memes/look_flat/__init__.py +++ /dev/null @@ -1,58 +0,0 @@ -from typing import List - -from pil_utils import BuildImage -from pydantic import Field - -from meme_generator import MemeArgsModel, MemeArgsParser, MemeArgsType, add_meme -from meme_generator.exception import TextOverLength -from meme_generator.utils import make_jpg_or_gif - -help = "图片“压扁”比例" - -parser = MemeArgsParser() -parser.add_argument("-r", "--ratio", type=int, default=2, help=help) - - -class Model(MemeArgsModel): - ratio: int = Field(2, description=help) - - -def look_flat(images: List[BuildImage], texts: List[str], args: Model): - text = texts[0] if texts else "可恶...被人看扁了" - ratio = args.ratio - - img_w = 500 - text_h = 80 - text_frame = BuildImage.new("RGBA", (img_w, text_h), "white") - try: - text_frame.draw_text( - (10, 0, img_w - 10, text_h), - text, - max_fontsize=55, - min_fontsize=30, - weight="bold", - ) - except ValueError: - raise TextOverLength(text) - - def make(img: BuildImage) -> BuildImage: - img = img.convert("RGBA").resize_width(img_w) - img = img.resize((img_w, img.height // ratio)) - img_h = img.height - frame = BuildImage.new("RGBA", (img_w, img_h + text_h), "white") - return frame.paste(img, alpha=True).paste(text_frame, (0, img_h), alpha=True) - - return make_jpg_or_gif(images[0], make) - - -add_meme( - "look_flat", - look_flat, - min_images=1, - max_images=1, - min_texts=0, - max_texts=1, - default_texts=["可恶...被人看扁了"], - args_type=MemeArgsType(parser, Model), - keywords=["看扁"], -) diff --git a/spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/modeling/registry.py b/spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/modeling/registry.py deleted file mode 100644 index e14fb118c458d0ba97d2a699be3004c6bdd3913c..0000000000000000000000000000000000000000 --- a/spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/modeling/registry.py +++ /dev/null @@ -1,12 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. - -from maskrcnn_benchmark.utils.registry import Registry - -BACKBONES = Registry() -RPN_HEADS = Registry() -ROI_BOX_FEATURE_EXTRACTORS = Registry() -ROI_BOX_PREDICTOR = Registry() -ROI_KEYPOINT_FEATURE_EXTRACTORS = Registry() -ROI_KEYPOINT_PREDICTOR = Registry() -ROI_MASK_FEATURE_EXTRACTORS = Registry() -ROI_MASK_PREDICTOR = Registry() diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/voltLib/ast.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/voltLib/ast.py deleted file mode 100644 index 82c2cca8b7f350bbf2ee579b0978937c22331a2f..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/voltLib/ast.py +++ /dev/null @@ -1,448 +0,0 @@ -from fontTools.voltLib.error import VoltLibError -from typing import NamedTuple - - -class Pos(NamedTuple): - adv: int - dx: int - dy: int - adv_adjust_by: dict - dx_adjust_by: dict - dy_adjust_by: dict - - def __str__(self): - res = " POS" - for attr in ("adv", "dx", "dy"): - value = getattr(self, attr) - if value is not None: - res += f" {attr.upper()} {value}" - adjust_by = getattr(self, f"{attr}_adjust_by", {}) - for size, adjustment in adjust_by.items(): - res += f" ADJUST_BY {adjustment} AT {size}" - res += " END_POS" - return res - - -class Element(object): - def __init__(self, location=None): - self.location = location - - def build(self, builder): - pass - - def __str__(self): - raise NotImplementedError - - -class Statement(Element): - pass - - -class Expression(Element): - pass - - -class VoltFile(Statement): - def __init__(self): - Statement.__init__(self, location=None) - self.statements = [] - - def build(self, builder): - for s in self.statements: - s.build(builder) - - def __str__(self): - return "\n" + "\n".join(str(s) for s in self.statements) + " END\n" - - -class GlyphDefinition(Statement): - def __init__(self, name, gid, gunicode, gtype, components, location=None): - Statement.__init__(self, location) - self.name = name - self.id = gid - self.unicode = gunicode - self.type = gtype - self.components = components - - def __str__(self): - res = f'DEF_GLYPH "{self.name}" ID {self.id}' - if self.unicode is not None: - if len(self.unicode) > 1: - unicodes = ",".join(f"U+{u:04X}" for u in self.unicode) - res += f' UNICODEVALUES "{unicodes}"' - else: - res += f" UNICODE {self.unicode[0]}" - if self.type is not None: - res += f" TYPE {self.type}" - if self.components is not None: - res += f" COMPONENTS {self.components}" - res += " END_GLYPH" - return res - - -class GroupDefinition(Statement): - def __init__(self, name, enum, location=None): - Statement.__init__(self, location) - self.name = name - self.enum = enum - self.glyphs_ = None - - def glyphSet(self, groups=None): - if groups is not None and self.name in groups: - raise VoltLibError( - 'Group "%s" contains itself.' % (self.name), self.location - ) - if self.glyphs_ is None: - if groups is None: - groups = set({self.name}) - else: - groups.add(self.name) - self.glyphs_ = self.enum.glyphSet(groups) - return self.glyphs_ - - def __str__(self): - enum = self.enum and str(self.enum) or "" - return f'DEF_GROUP "{self.name}"\n{enum}\nEND_GROUP' - - -class GlyphName(Expression): - """A single glyph name, such as cedilla.""" - - def __init__(self, glyph, location=None): - Expression.__init__(self, location) - self.glyph = glyph - - def glyphSet(self): - return (self.glyph,) - - def __str__(self): - return f' GLYPH "{self.glyph}"' - - -class Enum(Expression): - """An enum""" - - def __init__(self, enum, location=None): - Expression.__init__(self, location) - self.enum = enum - - def __iter__(self): - for e in self.glyphSet(): - yield e - - def glyphSet(self, groups=None): - glyphs = [] - for element in self.enum: - if isinstance(element, (GroupName, Enum)): - glyphs.extend(element.glyphSet(groups)) - else: - glyphs.extend(element.glyphSet()) - return tuple(glyphs) - - def __str__(self): - enum = "".join(str(e) for e in self.enum) - return f" ENUM{enum} END_ENUM" - - -class GroupName(Expression): - """A glyph group""" - - def __init__(self, group, parser, location=None): - Expression.__init__(self, location) - self.group = group - self.parser_ = parser - - def glyphSet(self, groups=None): - group = self.parser_.resolve_group(self.group) - if group is not None: - self.glyphs_ = group.glyphSet(groups) - return self.glyphs_ - else: - raise VoltLibError( - 'Group "%s" is used but undefined.' % (self.group), self.location - ) - - def __str__(self): - return f' GROUP "{self.group}"' - - -class Range(Expression): - """A glyph range""" - - def __init__(self, start, end, parser, location=None): - Expression.__init__(self, location) - self.start = start - self.end = end - self.parser = parser - - def glyphSet(self): - return tuple(self.parser.glyph_range(self.start, self.end)) - - def __str__(self): - return f' RANGE "{self.start}" TO "{self.end}"' - - -class ScriptDefinition(Statement): - def __init__(self, name, tag, langs, location=None): - Statement.__init__(self, location) - self.name = name - self.tag = tag - self.langs = langs - - def __str__(self): - res = "DEF_SCRIPT" - if self.name is not None: - res += f' NAME "{self.name}"' - res += f' TAG "{self.tag}"\n\n' - for lang in self.langs: - res += f"{lang}" - res += "END_SCRIPT" - return res - - -class LangSysDefinition(Statement): - def __init__(self, name, tag, features, location=None): - Statement.__init__(self, location) - self.name = name - self.tag = tag - self.features = features - - def __str__(self): - res = "DEF_LANGSYS" - if self.name is not None: - res += f' NAME "{self.name}"' - res += f' TAG "{self.tag}"\n\n' - for feature in self.features: - res += f"{feature}" - res += "END_LANGSYS\n" - return res - - -class FeatureDefinition(Statement): - def __init__(self, name, tag, lookups, location=None): - Statement.__init__(self, location) - self.name = name - self.tag = tag - self.lookups = lookups - - def __str__(self): - res = f'DEF_FEATURE NAME "{self.name}" TAG "{self.tag}"\n' - res += " " + " ".join(f'LOOKUP "{l}"' for l in self.lookups) + "\n" - res += "END_FEATURE\n" - return res - - -class LookupDefinition(Statement): - def __init__( - self, - name, - process_base, - process_marks, - mark_glyph_set, - direction, - reversal, - comments, - context, - sub, - pos, - location=None, - ): - Statement.__init__(self, location) - self.name = name - self.process_base = process_base - self.process_marks = process_marks - self.mark_glyph_set = mark_glyph_set - self.direction = direction - self.reversal = reversal - self.comments = comments - self.context = context - self.sub = sub - self.pos = pos - - def __str__(self): - res = f'DEF_LOOKUP "{self.name}"' - res += f' {self.process_base and "PROCESS_BASE" or "SKIP_BASE"}' - if self.process_marks: - res += " PROCESS_MARKS " - if self.mark_glyph_set: - res += f'MARK_GLYPH_SET "{self.mark_glyph_set}"' - elif isinstance(self.process_marks, str): - res += f'"{self.process_marks}"' - else: - res += "ALL" - else: - res += " SKIP_MARKS" - if self.direction is not None: - res += f" DIRECTION {self.direction}" - if self.reversal: - res += " REVERSAL" - if self.comments is not None: - comments = self.comments.replace("\n", r"\n") - res += f'\nCOMMENTS "{comments}"' - if self.context: - res += "\n" + "\n".join(str(c) for c in self.context) - else: - res += "\nIN_CONTEXT\nEND_CONTEXT" - if self.sub: - res += f"\n{self.sub}" - if self.pos: - res += f"\n{self.pos}" - return res - - -class SubstitutionDefinition(Statement): - def __init__(self, mapping, location=None): - Statement.__init__(self, location) - self.mapping = mapping - - def __str__(self): - res = "AS_SUBSTITUTION\n" - for src, dst in self.mapping.items(): - src = "".join(str(s) for s in src) - dst = "".join(str(d) for d in dst) - res += f"SUB{src}\nWITH{dst}\nEND_SUB\n" - res += "END_SUBSTITUTION" - return res - - -class SubstitutionSingleDefinition(SubstitutionDefinition): - pass - - -class SubstitutionMultipleDefinition(SubstitutionDefinition): - pass - - -class SubstitutionLigatureDefinition(SubstitutionDefinition): - pass - - -class SubstitutionReverseChainingSingleDefinition(SubstitutionDefinition): - pass - - -class PositionAttachDefinition(Statement): - def __init__(self, coverage, coverage_to, location=None): - Statement.__init__(self, location) - self.coverage = coverage - self.coverage_to = coverage_to - - def __str__(self): - coverage = "".join(str(c) for c in self.coverage) - res = f"AS_POSITION\nATTACH{coverage}\nTO" - for coverage, anchor in self.coverage_to: - coverage = "".join(str(c) for c in coverage) - res += f'{coverage} AT ANCHOR "{anchor}"' - res += "\nEND_ATTACH\nEND_POSITION" - return res - - -class PositionAttachCursiveDefinition(Statement): - def __init__(self, coverages_exit, coverages_enter, location=None): - Statement.__init__(self, location) - self.coverages_exit = coverages_exit - self.coverages_enter = coverages_enter - - def __str__(self): - res = "AS_POSITION\nATTACH_CURSIVE" - for coverage in self.coverages_exit: - coverage = "".join(str(c) for c in coverage) - res += f"\nEXIT {coverage}" - for coverage in self.coverages_enter: - coverage = "".join(str(c) for c in coverage) - res += f"\nENTER {coverage}" - res += "\nEND_ATTACH\nEND_POSITION" - return res - - -class PositionAdjustPairDefinition(Statement): - def __init__(self, coverages_1, coverages_2, adjust_pair, location=None): - Statement.__init__(self, location) - self.coverages_1 = coverages_1 - self.coverages_2 = coverages_2 - self.adjust_pair = adjust_pair - - def __str__(self): - res = "AS_POSITION\nADJUST_PAIR\n" - for coverage in self.coverages_1: - coverage = " ".join(str(c) for c in coverage) - res += f" FIRST {coverage}" - res += "\n" - for coverage in self.coverages_2: - coverage = " ".join(str(c) for c in coverage) - res += f" SECOND {coverage}" - res += "\n" - for (id_1, id_2), (pos_1, pos_2) in self.adjust_pair.items(): - res += f" {id_1} {id_2} BY{pos_1}{pos_2}\n" - res += "\nEND_ADJUST\nEND_POSITION" - return res - - -class PositionAdjustSingleDefinition(Statement): - def __init__(self, adjust_single, location=None): - Statement.__init__(self, location) - self.adjust_single = adjust_single - - def __str__(self): - res = "AS_POSITION\nADJUST_SINGLE" - for coverage, pos in self.adjust_single: - coverage = "".join(str(c) for c in coverage) - res += f"{coverage} BY{pos}" - res += "\nEND_ADJUST\nEND_POSITION" - return res - - -class ContextDefinition(Statement): - def __init__(self, ex_or_in, left=None, right=None, location=None): - Statement.__init__(self, location) - self.ex_or_in = ex_or_in - self.left = left if left is not None else [] - self.right = right if right is not None else [] - - def __str__(self): - res = self.ex_or_in + "\n" - for coverage in self.left: - coverage = "".join(str(c) for c in coverage) - res += f" LEFT{coverage}\n" - for coverage in self.right: - coverage = "".join(str(c) for c in coverage) - res += f" RIGHT{coverage}\n" - res += "END_CONTEXT" - return res - - -class AnchorDefinition(Statement): - def __init__(self, name, gid, glyph_name, component, locked, pos, location=None): - Statement.__init__(self, location) - self.name = name - self.gid = gid - self.glyph_name = glyph_name - self.component = component - self.locked = locked - self.pos = pos - - def __str__(self): - locked = self.locked and " LOCKED" or "" - return ( - f'DEF_ANCHOR "{self.name}"' - f" ON {self.gid}" - f" GLYPH {self.glyph_name}" - f" COMPONENT {self.component}" - f"{locked}" - f" AT {self.pos} END_ANCHOR" - ) - - -class SettingDefinition(Statement): - def __init__(self, name, value, location=None): - Statement.__init__(self, location) - self.name = name - self.value = value - - def __str__(self): - if self.value is True: - return f"{self.name}" - if isinstance(self.value, (tuple, list)): - value = " ".join(str(v) for v in self.value) - return f"{self.name} {value}" - return f"{self.name} {self.value}" diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/Column-2853eb31.css b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/Column-2853eb31.css deleted file mode 100644 index 8657e4c7112cc9a8232f875b00f9cf9aaac5e9f6..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/Column-2853eb31.css +++ /dev/null @@ -1 +0,0 @@ -div.svelte-vt1mxs{display:flex;position:relative;flex-direction:column}div.svelte-vt1mxs>*,div.svelte-vt1mxs>.form>*{width:var(--size-full)}.gap.svelte-vt1mxs{gap:var(--layout-gap)}.hide.svelte-vt1mxs{display:none}.compact.svelte-vt1mxs>*,.compact.svelte-vt1mxs .box{border-radius:0}.compact.svelte-vt1mxs,.panel.svelte-vt1mxs{border:solid var(--panel-border-width) var(--panel-border-color);border-radius:var(--container-radius);background:var(--panel-background-fill);padding:var(--spacing-lg)} diff --git "a/spaces/Daextream/Whisper-Auto-Subtitled-Video-Generator/pages/02_\360\237\223\274_Upload_Video_File.py" "b/spaces/Daextream/Whisper-Auto-Subtitled-Video-Generator/pages/02_\360\237\223\274_Upload_Video_File.py" deleted file mode 100644 index 3f004f61b5598979c3e2138590e8b7f515731590..0000000000000000000000000000000000000000 --- "a/spaces/Daextream/Whisper-Auto-Subtitled-Video-Generator/pages/02_\360\237\223\274_Upload_Video_File.py" +++ /dev/null @@ -1,230 +0,0 @@ -import whisper -import streamlit as st -from streamlit_lottie import st_lottie -from utils import write_vtt, write_srt -import ffmpeg -import requests -from typing import Iterator -from io import StringIO -import numpy as np -import pathlib -import os - -st.set_page_config(page_title="Auto Subtitled Video Generator", page_icon=":movie_camera:", layout="wide") - -# Define a function that we can use to load lottie files from a link. -@st.cache(allow_output_mutation=True) -def load_lottieurl(url: str): - r = requests.get(url) - if r.status_code != 200: - return None - return r.json() - - -APP_DIR = pathlib.Path(__file__).parent.absolute() - -LOCAL_DIR = APP_DIR / "local" -LOCAL_DIR.mkdir(exist_ok=True) -save_dir = LOCAL_DIR / "output" -save_dir.mkdir(exist_ok=True) - - -loaded_model = whisper.load_model("base") -current_size = "None" - - -col1, col2 = st.columns([1, 3]) -with col1: - lottie = load_lottieurl("https://assets1.lottiefiles.com/packages/lf20_HjK9Ol.json") - st_lottie(lottie) - -with col2: - st.write(""" - ## Auto Subtitled Video Generator - ##### Upload a video file and get a video with subtitles. - ###### ➠ If you want to transcribe the video in its original language, select the task as "Transcribe" - ###### ➠ If you want to translate the subtitles to English, select the task as "Translate" - ###### I recommend starting with the base model and then experimenting with the larger models, the small and medium models often work well. """) - - -@st.cache(allow_output_mutation=True) -def change_model(current_size, size): - if current_size != size: - loaded_model = whisper.load_model(size) - return loaded_model - else: - raise Exception("Model size is the same as the current size.") - - -@st.cache(allow_output_mutation=True) -def inferecence(loaded_model, uploaded_file, task): - with open(f"{save_dir}/input.mp4", "wb") as f: - f.write(uploaded_file.read()) - audio = ffmpeg.input(f"{save_dir}/input.mp4") - audio = ffmpeg.output(audio, f"{save_dir}/output.wav", acodec="pcm_s16le", ac=1, ar="16k") - ffmpeg.run(audio, overwrite_output=True) - if task == "Transcribe": - options = dict(task="transcribe", best_of=5) - results = loaded_model.transcribe(f"{save_dir}/output.wav", **options) - vtt = getSubs(results["segments"], "vtt", 80) - srt = getSubs(results["segments"], "srt", 80) - lang = results["language"] - return results["text"], vtt, srt, lang - elif task == "Translate": - options = dict(task="translate", best_of=5) - results = loaded_model.transcribe(f"{save_dir}/output.wav", **options) - vtt = getSubs(results["segments"], "vtt", 80) - srt = getSubs(results["segments"], "srt", 80) - lang = results["language"] - return results["text"], vtt, srt, lang - else: - raise ValueError("Task not supported") - - -def getSubs(segments: Iterator[dict], format: str, maxLineWidth: int) -> str: - segmentStream = StringIO() - - if format == 'vtt': - write_vtt(segments, file=segmentStream, maxLineWidth=maxLineWidth) - elif format == 'srt': - write_srt(segments, file=segmentStream, maxLineWidth=maxLineWidth) - else: - raise Exception("Unknown format " + format) - - segmentStream.seek(0) - return segmentStream.read() - - -def generate_subtitled_video(video, audio, transcript): - video_file = ffmpeg.input(video) - audio_file = ffmpeg.input(audio) - ffmpeg.concat(video_file.filter("subtitles", transcript), audio_file, v=1, a=1).output("final.mp4").run(quiet=True, overwrite_output=True) - video_with_subs = open("final.mp4", "rb") - return video_with_subs - - -def main(): - size = st.selectbox("Select Model Size (The larger the model, the more accurate the transcription will be, but it will take longer)", ["tiny", "base", "small", "medium", "large"], index=1) - loaded_model = change_model(current_size, size) - st.write(f"Model is {'multilingual' if loaded_model.is_multilingual else 'English-only'} " - f"and has {sum(np.prod(p.shape) for p in loaded_model.parameters()):,} parameters.") - input_file = st.file_uploader("File", type=["mp4", "avi", "mov", "mkv"]) - # get the name of the input_file - if input_file is not None: - filename = input_file.name[:-4] - else: - filename = None - task = st.selectbox("Select Task", ["Transcribe", "Translate"], index=0) - if task == "Transcribe": - if st.button("Transcribe"): - results = inferecence(loaded_model, input_file, task) - col3, col4 = st.columns(2) - col5, col6, col7, col8 = st.columns(4) - col9, col10 = st.columns(2) - with col3: - st.video(input_file) - - with open("transcript.txt", "w+", encoding='utf8') as f: - f.writelines(results[0]) - f.close() - with open(os.path.join(os.getcwd(), "transcript.txt"), "rb") as f: - datatxt = f.read() - - with open("transcript.vtt", "w+",encoding='utf8') as f: - f.writelines(results[1]) - f.close() - with open(os.path.join(os.getcwd(), "transcript.vtt"), "rb") as f: - datavtt = f.read() - - with open("transcript.srt", "w+",encoding='utf8') as f: - f.writelines(results[2]) - f.close() - with open(os.path.join(os.getcwd(), "transcript.srt"), "rb") as f: - datasrt = f.read() - - with col5: - st.download_button(label="Download Transcript (.txt)", - data=datatxt, - file_name="transcript.txt") - with col6: - st.download_button(label="Download Transcript (.vtt)", - data=datavtt, - file_name="transcript.vtt") - with col7: - st.download_button(label="Download Transcript (.srt)", - data=datasrt, - file_name="transcript.srt") - with col9: - st.success("You can download the transcript in .srt format, edit it (if you need to) and upload it to YouTube to create subtitles for your video.") - with col10: - st.info("Streamlit refreshes after the download button is clicked. The data is cached so you can download the transcript again without having to transcribe the video again.") - - with col4: - with st.spinner("Generating Subtitled Video"): - video_with_subs = generate_subtitled_video(f"{save_dir}/input.mp4", f"{save_dir}/output.wav", "transcript.srt") - st.video(video_with_subs) - st.snow() - with col8: - st.download_button(label="Download Video with Subtitles", - data=video_with_subs, - file_name=f"{filename}_with_subs.mp4") - elif task == "Translate": - if st.button("Translate to English"): - results = inferecence(loaded_model, input_file, task) - col3, col4 = st.columns(2) - col5, col6, col7, col8 = st.columns(4) - col9, col10 = st.columns(2) - with col3: - st.video(input_file) - - with open("transcript.txt", "w+", encoding='utf8') as f: - f.writelines(results[0]) - f.close() - with open(os.path.join(os.getcwd(), "transcript.txt"), "rb") as f: - datatxt = f.read() - - with open("transcript.vtt", "w+",encoding='utf8') as f: - f.writelines(results[1]) - f.close() - with open(os.path.join(os.getcwd(), "transcript.vtt"), "rb") as f: - datavtt = f.read() - - with open("transcript.srt", "w+",encoding='utf8') as f: - f.writelines(results[2]) - f.close() - with open(os.path.join(os.getcwd(), "transcript.srt"), "rb") as f: - datasrt = f.read() - - with col5: - st.download_button(label="Download Transcript (.txt)", - data=datatxt, - file_name="transcript.txt") - with col6: - st.download_button(label="Download Transcript (.vtt)", - data=datavtt, - file_name="transcript.vtt") - with col7: - st.download_button(label="Download Transcript (.srt)", - data=datasrt, - file_name="transcript.srt") - with col9: - st.success("You can download the transcript in .srt format, edit it (if you need to) and upload it to YouTube to create subtitles for your video.") - with col10: - st.info("Streamlit refreshes after the download button is clicked. The data is cached so you can download the transcript again without having to transcribe the video again.") - - with col4: - with st.spinner("Generating Subtitled Video"): - video_with_subs = generate_subtitled_video(f"{save_dir}/input.mp4", f"{save_dir}/output.wav", "transcript.srt") - st.video(video_with_subs) - st.snow() - with col8: - st.download_button(label="Download Video with Subtitles", - data=video_with_subs, - file_name=f"{filename}_with_subs.mp4") - else: - st.error("Please select a task.") - - -if __name__ == "__main__": - main() - st.markdown("###### Made with :heart: by [@BatuhanYılmaz](https://twitter.com/batuhan3326) [![this is an image link](https://i.imgur.com/thJhzOO.png)](https://www.buymeacoffee.com/batuhanylmz)") \ No newline at end of file diff --git a/spaces/DemoLou/moe-tts/modules.py b/spaces/DemoLou/moe-tts/modules.py deleted file mode 100644 index 3484f6a1f4c1c06855c37a1ff4e66c58864acb38..0000000000000000000000000000000000000000 --- a/spaces/DemoLou/moe-tts/modules.py +++ /dev/null @@ -1,390 +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 - - -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): - """ - Dilated 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/Devaholic/fruit-demo/README.md b/spaces/Devaholic/fruit-demo/README.md deleted file mode 100644 index 8afc447ea4d91b65d427f41a3da0be3eb5006ffc..0000000000000000000000000000000000000000 --- a/spaces/Devaholic/fruit-demo/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Fruit Demo -emoji: 🐨 -colorFrom: purple -colorTo: gray -sdk: gradio -sdk_version: 3.0.18 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/convert_weight.py b/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/convert_weight.py deleted file mode 100644 index 09b0a02dc48e3a8736f65bfe337a8c59aa206029..0000000000000000000000000000000000000000 --- a/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/convert_weight.py +++ /dev/null @@ -1,283 +0,0 @@ -import argparse -import os -import sys -import pickle -import math - -import torch -import numpy as np -from torchvision import utils - -from model import Generator, Discriminator - - -def convert_modconv(vars, source_name, target_name, flip=False): - weight = vars[source_name + '/weight'].value().eval() - mod_weight = vars[source_name + '/mod_weight'].value().eval() - mod_bias = vars[source_name + '/mod_bias'].value().eval() - noise = vars[source_name + '/noise_strength'].value().eval() - bias = vars[source_name + '/bias'].value().eval() - - dic = { - 'conv.weight': np.expand_dims(weight.transpose((3, 2, 0, 1)), 0), - 'conv.modulation.weight': mod_weight.transpose((1, 0)), - 'conv.modulation.bias': mod_bias + 1, - 'noise.weight': np.array([noise]), - 'activate.bias': bias, - } - - dic_torch = {} - - for k, v in dic.items(): - dic_torch[target_name + '.' + k] = torch.from_numpy(v) - - if flip: - dic_torch[target_name + '.conv.weight'] = torch.flip( - dic_torch[target_name + '.conv.weight'], [3, 4] - ) - - return dic_torch - - -def convert_conv(vars, source_name, target_name, bias=True, start=0): - weight = vars[source_name + '/weight'].value().eval() - - dic = {'weight': weight.transpose((3, 2, 0, 1))} - - if bias: - dic['bias'] = vars[source_name + '/bias'].value().eval() - - dic_torch = {} - - dic_torch[target_name + f'.{start}.weight'] = torch.from_numpy(dic['weight']) - - if bias: - dic_torch[target_name + f'.{start + 1}.bias'] = torch.from_numpy(dic['bias']) - - return dic_torch - - -def convert_torgb(vars, source_name, target_name): - weight = vars[source_name + '/weight'].value().eval() - mod_weight = vars[source_name + '/mod_weight'].value().eval() - mod_bias = vars[source_name + '/mod_bias'].value().eval() - bias = vars[source_name + '/bias'].value().eval() - - dic = { - 'conv.weight': np.expand_dims(weight.transpose((3, 2, 0, 1)), 0), - 'conv.modulation.weight': mod_weight.transpose((1, 0)), - 'conv.modulation.bias': mod_bias + 1, - 'bias': bias.reshape((1, 3, 1, 1)), - } - - dic_torch = {} - - for k, v in dic.items(): - dic_torch[target_name + '.' + k] = torch.from_numpy(v) - - return dic_torch - - -def convert_dense(vars, source_name, target_name): - weight = vars[source_name + '/weight'].value().eval() - bias = vars[source_name + '/bias'].value().eval() - - dic = {'weight': weight.transpose((1, 0)), 'bias': bias} - - dic_torch = {} - - for k, v in dic.items(): - dic_torch[target_name + '.' + k] = torch.from_numpy(v) - - return dic_torch - - -def update(state_dict, new): - for k, v in new.items(): - if k not in state_dict: - raise KeyError(k + ' is not found') - - if v.shape != state_dict[k].shape: - raise ValueError(f'Shape mismatch: {v.shape} vs {state_dict[k].shape}') - - state_dict[k] = v - - -def discriminator_fill_statedict(statedict, vars, size): - log_size = int(math.log(size, 2)) - - update(statedict, convert_conv(vars, f'{size}x{size}/FromRGB', 'convs.0')) - - conv_i = 1 - - for i in range(log_size - 2, 0, -1): - reso = 4 * 2 ** i - update( - statedict, - convert_conv(vars, f'{reso}x{reso}/Conv0', f'convs.{conv_i}.conv1'), - ) - update( - statedict, - convert_conv( - vars, f'{reso}x{reso}/Conv1_down', f'convs.{conv_i}.conv2', start=1 - ), - ) - update( - statedict, - convert_conv( - vars, f'{reso}x{reso}/Skip', f'convs.{conv_i}.skip', start=1, bias=False - ), - ) - conv_i += 1 - - update(statedict, convert_conv(vars, f'4x4/Conv', 'final_conv')) - update(statedict, convert_dense(vars, f'4x4/Dense0', 'final_linear.0')) - update(statedict, convert_dense(vars, f'Output', 'final_linear.1')) - - return statedict - - -def fill_statedict(state_dict, vars, size): - log_size = int(math.log(size, 2)) - - for i in range(8): - update(state_dict, convert_dense(vars, f'G_mapping/Dense{i}', f'style.{i + 1}')) - - update( - state_dict, - { - 'input.input': torch.from_numpy( - vars['G_synthesis/4x4/Const/const'].value().eval() - ) - }, - ) - - update(state_dict, convert_torgb(vars, 'G_synthesis/4x4/ToRGB', 'to_rgb1')) - - for i in range(log_size - 2): - reso = 4 * 2 ** (i + 1) - update( - state_dict, - convert_torgb(vars, f'G_synthesis/{reso}x{reso}/ToRGB', f'to_rgbs.{i}'), - ) - - update(state_dict, convert_modconv(vars, 'G_synthesis/4x4/Conv', 'conv1')) - - conv_i = 0 - - for i in range(log_size - 2): - reso = 4 * 2 ** (i + 1) - update( - state_dict, - convert_modconv( - vars, - f'G_synthesis/{reso}x{reso}/Conv0_up', - f'convs.{conv_i}', - flip=True, - ), - ) - update( - state_dict, - convert_modconv( - vars, f'G_synthesis/{reso}x{reso}/Conv1', f'convs.{conv_i + 1}' - ), - ) - conv_i += 2 - - for i in range(0, (log_size - 2) * 2 + 1): - update( - state_dict, - { - f'noises.noise_{i}': torch.from_numpy( - vars[f'G_synthesis/noise{i}'].value().eval() - ) - }, - ) - - return state_dict - - -if __name__ == '__main__': - device = 'cuda' if torch.cuda.is_available() else 'cpu' - print('Using PyTorch device', device) - - parser = argparse.ArgumentParser() - parser.add_argument('--repo', type=str, required=True) - parser.add_argument('--gen', action='store_true') - parser.add_argument('--disc', action='store_true') - parser.add_argument('--channel_multiplier', type=int, default=2) - parser.add_argument('path', metavar='PATH') - - args = parser.parse_args() - - sys.path.append(args.repo) - - import dnnlib - from dnnlib import tflib - - tflib.init_tf() - - with open(args.path, 'rb') as f: - generator, discriminator, g_ema = pickle.load(f) - - size = g_ema.output_shape[2] - - g = Generator(size, 512, 8, channel_multiplier=args.channel_multiplier) - state_dict = g.state_dict() - state_dict = fill_statedict(state_dict, g_ema.vars, size) - - g.load_state_dict(state_dict) - - latent_avg = torch.from_numpy(g_ema.vars['dlatent_avg'].value().eval()) - - ckpt = {'g_ema': state_dict, 'latent_avg': latent_avg} - - if args.gen: - g_train = Generator(size, 512, 8, channel_multiplier=args.channel_multiplier) - g_train_state = g_train.state_dict() - g_train_state = fill_statedict(g_train_state, generator.vars, size) - ckpt['g'] = g_train_state - - if args.disc: - disc = Discriminator(size, channel_multiplier=args.channel_multiplier) - d_state = disc.state_dict() - d_state = discriminator_fill_statedict(d_state, discriminator.vars, size) - ckpt['d'] = d_state - - name = os.path.splitext(os.path.basename(args.path))[0] - outpath = os.path.join(os.getcwd(), f'{name}.pt') - print('Saving', outpath) - try: - torch.save(ckpt, outpath, _use_new_zipfile_serialization=False) - except TypeError: - torch.save(ckpt, outpath) - - - print('Generating TF-Torch comparison images') - batch_size = {256: 8, 512: 4, 1024: 2} - n_sample = batch_size.get(size, 4) - - g = g.to(device) - - z = np.random.RandomState(0).randn(n_sample, 512).astype('float32') - - with torch.no_grad(): - img_pt, _ = g( - [torch.from_numpy(z).to(device)], - truncation=0.5, - truncation_latent=latent_avg.to(device), - ) - - img_tf = g_ema.run(z, None, randomize_noise=False) - img_tf = torch.from_numpy(img_tf).to(device) - - img_diff = ((img_pt + 1) / 2).clamp(0.0, 1.0) - ((img_tf.to(device) + 1) / 2).clamp( - 0.0, 1.0 - ) - - img_concat = torch.cat((img_tf, img_pt, img_diff), dim=0) - utils.save_image( - img_concat, name + '.png', nrow=n_sample, normalize=True, range=(-1, 1) - ) - print('Done') - diff --git a/spaces/DragGan/DragGan/stylegan_human/docs/Dataset.md b/spaces/DragGan/DragGan/stylegan_human/docs/Dataset.md deleted file mode 100644 index ef6c56cedab89f3ab09306826240b075af244899..0000000000000000000000000000000000000000 --- a/spaces/DragGan/DragGan/stylegan_human/docs/Dataset.md +++ /dev/null @@ -1,74 +0,0 @@ -# SHHQ Dataset - - -## Overview -SHHQ is a dataset with high-quality full-body human images in a resolution of 1024 × 512. -Since we need to follow a rigorous legal review in our institute, we can not release all of the data at once. - -For now, SHHQ-1.0 with 40K images is released! More data will be released in the later versions. - - -## Data Sources -Images are collected in two main ways: -1) From the Internet. -We developed a crawler tool with an official API, mainly downloading images from Flickr, Pixabay and Pexels. So you need to meet all the following licenses when using the dataset: CC0, [Pixabay License](https://pixabay.com/service/license/), and [Pexels Licenses](https://www.pexels.com/license/). -2) From the data providers. -We purchased images from databases of individual photographers, modeling agencies and other suppliers. -Images were reviewed by our legal team prior to purchase to ensure permission for use in research. - -### Note: -The composition of SHHQ-1.0: - -1) Images obtained from the above sources. -2) Processed 9991 DeepFashion [[1]](#1) images (retain only full body images). -3) 1940 African images from the InFashAI [[2]](#2) dataset to increase data diversity. - -## Data License -We are aware of privacy concerns and seriously treat the license and privacy issues. All released data will be ensured under the license of CC0 and free for research use. Also, persons in the dataset are anonymised without additional private or sensitive metadata. - -## Agreement -The SHHQ is available for non-commercial research purposes only. - -You agree not to reproduce, duplicate, copy, sell, trade, resell or exploit any portion of the images and any portion of the derived data for commercial purposes. - -You agree NOT to further copy, publish or distribute any portion of SHHQ to any third party for any purpose. Except, for internal use at a single site within the same organization it is allowed to make copies of the dataset. - -Shanghai AI Lab reserves the right to terminate your access to the SHHQ at any time. - -## Dataset Preview -For those interested in our dataset, we provide a preview version with 100 images randomly sampled from SHHQ-1.0: [SHHQ-1.0_samples](https://drive.google.com/file/d/1tnNFfmFtzRbYL3qEnNXQ_ShaN9YV5tI5/view?usp=sharing). - -In SHHQ-1.0, we provide aligned raw images along with machine-calculated segmentation masks. Later we are planning to release manually annotated human-parsing version of these 40,000 images. Please stay tuned. - -> We also provide script [bg_white.py](../bg_white.py) to whiten the background of the raw image using its segmentation mask. - -If you want to access the full SHHQ-1.0, please read the following instructions. - -## Model trained using SHHQ-1.0 - -| Structure | 1024x512 | Metric | Scores | 512x256 | Metric | Scores | -| --------- |:----------:| :----------:| :----------:| :-----: | :-----: | :-----: | -| StyleGAN1 | to be released | - | - | to be released | - | - | -| StyleGAN2 | [SHHQ-1.0_sg2_1024.pkl](https://drive.google.com/file/d/1PuvE72xpc69Zq4y58dohuKbG9dFnnjEX/view?usp=sharing) | fid50k_full | 3.56 | [SHHQ-1.0_sg2_512.pkl](https://drive.google.com/file/d/170t2FRWxR8_TG3_y0nVtDBogLPOClnyf/view?usp=sharing) | fid50k_full | 3.68 | -| StyleGAN3 | to be released | - | - |to be released | - | - | - - -## Download Instructions -Please download the SHHQ Dataset Release Agreement from [link](./SHHQ_Dataset_Release_Agreement.pdf). -Read it carefully, complete and sign it appropriately. - -Please send the completed form to Jianglin Fu (arlenefu@outlook.com) and Shikai Li (lishikai@pjlab.org.cn), and cc to Wayne Wu (wuwenyan0503@gmail.com) using institutional email address. The email Subject Title is "SHHQ Dataset Release Agreement". We will verify your request and contact you with the dataset link and password to unzip the image data. - -Note: - -1. We are currently facing large incoming applications, and we need to carefully verify all the applicants, please be patient, and we will reply to you as soon as possible. - -2. The signature in the agreement should be hand-written. - -## References -[1] -Liu, Ziwei and Luo, Ping and Qiu, Shi and Wang, Xiaogang and Tang, Xiaoou. DeepFashion: Powering Robust Clothes Recognition and Retrieval with Rich Annotations. CVPR (2016) - -[2] -Hacheme, Gilles and Sayouti, Noureini. Neural fashion image captioning: Accounting for data diversity. arXiv preprint arXiv:2106.12154 (2021) - diff --git a/spaces/DragGan/DragGan/torch_utils/ops/grid_sample_gradfix.py b/spaces/DragGan/DragGan/torch_utils/ops/grid_sample_gradfix.py deleted file mode 100644 index 979ee831b232c68b8c271be9e376c70c57a31b02..0000000000000000000000000000000000000000 --- a/spaces/DragGan/DragGan/torch_utils/ops/grid_sample_gradfix.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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. - -"""Custom replacement for `torch.nn.functional.grid_sample` that -supports arbitrarily high order gradients between the input and output. -Only works on 2D images and assumes -`mode='bilinear'`, `padding_mode='zeros'`, `align_corners=False`.""" - -import torch - -# pylint: disable=redefined-builtin -# pylint: disable=arguments-differ -# pylint: disable=protected-access - -#---------------------------------------------------------------------------- - -enabled = False # Enable the custom op by setting this to true. - -#---------------------------------------------------------------------------- - -def grid_sample(input, grid): - if _should_use_custom_op(): - return _GridSample2dForward.apply(input, grid) - return torch.nn.functional.grid_sample(input=input, grid=grid, mode='bilinear', padding_mode='zeros', align_corners=False) - -#---------------------------------------------------------------------------- - -def _should_use_custom_op(): - return enabled - -#---------------------------------------------------------------------------- - -class _GridSample2dForward(torch.autograd.Function): - @staticmethod - def forward(ctx, input, grid): - assert input.ndim == 4 - assert grid.ndim == 4 - output = torch.nn.functional.grid_sample(input=input, grid=grid, mode='bilinear', padding_mode='zeros', align_corners=False) - ctx.save_for_backward(input, grid) - return output - - @staticmethod - def backward(ctx, grad_output): - input, grid = ctx.saved_tensors - grad_input, grad_grid = _GridSample2dBackward.apply(grad_output, input, grid) - return grad_input, grad_grid - -#---------------------------------------------------------------------------- - -class _GridSample2dBackward(torch.autograd.Function): - @staticmethod - def forward(ctx, grad_output, input, grid): - op = torch._C._jit_get_operation('aten::grid_sampler_2d_backward') - grad_input, grad_grid = op(grad_output, input, grid, 0, 0, False) - ctx.save_for_backward(grid) - return grad_input, grad_grid - - @staticmethod - def backward(ctx, grad2_grad_input, grad2_grad_grid): - _ = grad2_grad_grid # unused - grid, = ctx.saved_tensors - grad2_grad_output = None - grad2_input = None - grad2_grid = None - - if ctx.needs_input_grad[0]: - grad2_grad_output = _GridSample2dForward.apply(grad2_grad_input, grid) - - assert not ctx.needs_input_grad[2] - return grad2_grad_output, grad2_input, grad2_grid - -#---------------------------------------------------------------------------- diff --git a/spaces/Eightone3D/anything-v3.0/README.md b/spaces/Eightone3D/anything-v3.0/README.md deleted file mode 100644 index 15176bed26d36b4f9566c7102a5655e310f76036..0000000000000000000000000000000000000000 --- a/spaces/Eightone3D/anything-v3.0/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Anything V3.0 -emoji: 🏃 -colorFrom: gray -colorTo: yellow -sdk: gradio -sdk_version: 3.10.1 -app_file: app.py -pinned: false -duplicated_from: akhaliq/anything-v3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/FSDL-Fashion/fashion_img_search/fis/utils/constants.py b/spaces/FSDL-Fashion/fashion_img_search/fis/utils/constants.py deleted file mode 100644 index 7d5cad599138ca21bae7ebdc52f8346f989aec81..0000000000000000000000000000000000000000 --- a/spaces/FSDL-Fashion/fashion_img_search/fis/utils/constants.py +++ /dev/null @@ -1 +0,0 @@ -ORGANISATION = "FSDL-Fashion" diff --git a/spaces/Froleptan/stablediffusion-infinity/utils.py b/spaces/Froleptan/stablediffusion-infinity/utils.py deleted file mode 100644 index bebc4f7f4da8f6de637b148f39aa6a5ef60679c5..0000000000000000000000000000000000000000 --- a/spaces/Froleptan/stablediffusion-infinity/utils.py +++ /dev/null @@ -1,217 +0,0 @@ -from PIL import Image -from PIL import ImageFilter -import cv2 -import numpy as np -import scipy -import scipy.signal -from scipy.spatial import cKDTree - -import os -from perlin2d import * - -patch_match_compiled = True - -try: - from PyPatchMatch import patch_match -except Exception as e: - try: - import patch_match - except Exception as e: - patch_match_compiled = False - -try: - patch_match -except NameError: - print("patch_match compiling failed, will fall back to edge_pad") - patch_match_compiled = False - - - - -def edge_pad(img, mask, mode=1): - if mode == 0: - nmask = mask.copy() - nmask[nmask > 0] = 1 - res0 = 1 - nmask - res1 = nmask - p0 = np.stack(res0.nonzero(), axis=0).transpose() - p1 = np.stack(res1.nonzero(), axis=0).transpose() - min_dists, min_dist_idx = cKDTree(p1).query(p0, 1) - loc = p1[min_dist_idx] - for (a, b), (c, d) in zip(p0, loc): - img[a, b] = img[c, d] - elif mode == 1: - record = {} - kernel = [[1] * 3 for _ in range(3)] - nmask = mask.copy() - nmask[nmask > 0] = 1 - res = scipy.signal.convolve2d( - nmask, kernel, mode="same", boundary="fill", fillvalue=1 - ) - res[nmask < 1] = 0 - res[res == 9] = 0 - res[res > 0] = 1 - ylst, xlst = res.nonzero() - queue = [(y, x) for y, x in zip(ylst, xlst)] - # bfs here - cnt = res.astype(np.float32) - acc = img.astype(np.float32) - step = 1 - h = acc.shape[0] - w = acc.shape[1] - offset = [(1, 0), (-1, 0), (0, 1), (0, -1)] - while queue: - target = [] - for y, x in queue: - val = acc[y][x] - for yo, xo in offset: - yn = y + yo - xn = x + xo - if 0 <= yn < h and 0 <= xn < w and nmask[yn][xn] < 1: - if record.get((yn, xn), step) == step: - acc[yn][xn] = acc[yn][xn] * cnt[yn][xn] + val - cnt[yn][xn] += 1 - acc[yn][xn] /= cnt[yn][xn] - if (yn, xn) not in record: - record[(yn, xn)] = step - target.append((yn, xn)) - step += 1 - queue = target - img = acc.astype(np.uint8) - else: - nmask = mask.copy() - ylst, xlst = nmask.nonzero() - yt, xt = ylst.min(), xlst.min() - yb, xb = ylst.max(), xlst.max() - content = img[yt : yb + 1, xt : xb + 1] - img = np.pad( - content, - ((yt, mask.shape[0] - yb - 1), (xt, mask.shape[1] - xb - 1), (0, 0)), - mode="edge", - ) - return img, mask - - -def perlin_noise(img, mask): - lin = np.linspace(0, 5, mask.shape[0], endpoint=False) - x, y = np.meshgrid(lin, lin) - avg = img.mean(axis=0).mean(axis=0) - # noise=[((perlin(x, y)+1)*128+avg[i]).astype(np.uint8) for i in range(3)] - noise = [((perlin(x, y) + 1) * 0.5 * 255).astype(np.uint8) for i in range(3)] - noise = np.stack(noise, axis=-1) - # mask=skimage.measure.block_reduce(mask,(8,8),np.min) - # mask=mask.repeat(8, axis=0).repeat(8, axis=1) - # mask_image=Image.fromarray(mask) - # mask_image=mask_image.filter(ImageFilter.GaussianBlur(radius = 4)) - # mask=np.array(mask_image) - nmask = mask.copy() - # nmask=nmask/255.0 - nmask[mask > 0] = 1 - img = nmask[:, :, np.newaxis] * img + (1 - nmask[:, :, np.newaxis]) * noise - # img=img.astype(np.uint8) - return img, mask - - -def gaussian_noise(img, mask): - noise = np.random.randn(mask.shape[0], mask.shape[1], 3) - noise = (noise + 1) / 2 * 255 - noise = noise.astype(np.uint8) - nmask = mask.copy() - nmask[mask > 0] = 1 - img = nmask[:, :, np.newaxis] * img + (1 - nmask[:, :, np.newaxis]) * noise - return img, mask - - -def cv2_telea(img, mask): - ret = cv2.inpaint(img, 255 - mask, 5, cv2.INPAINT_TELEA) - return ret, mask - - -def cv2_ns(img, mask): - ret = cv2.inpaint(img, 255 - mask, 5, cv2.INPAINT_NS) - return ret, mask - - -def patch_match_func(img, mask): - ret = patch_match.inpaint(img, mask=255 - mask, patch_size=3) - return ret, mask - - -def mean_fill(img, mask): - avg = img.mean(axis=0).mean(axis=0) - img[mask < 1] = avg - return img, mask - -def g_diffuser(img,mask): - return img, mask - -def dummy_fill(img,mask): - return img,mask -functbl = { - "gaussian": gaussian_noise, - "perlin": perlin_noise, - "edge_pad": edge_pad, - "patchmatch": patch_match_func if patch_match_compiled else edge_pad, - "cv2_ns": cv2_ns, - "cv2_telea": cv2_telea, - "g_diffuser": g_diffuser, - "g_diffuser_lib": dummy_fill, -} - -try: - from postprocess import PhotometricCorrection - correction_func = PhotometricCorrection() -except Exception as e: - print(e, "so PhotometricCorrection is disabled") - class DummyCorrection: - def __init__(self): - self.backend="" - pass - def run(self,a,b,**kwargs): - return b - correction_func=DummyCorrection() - -if "taichi" in correction_func.backend: - import sys - import io - import base64 - from PIL import Image - def base64_to_pil(base64_str): - data = base64.b64decode(str(base64_str)) - pil = Image.open(io.BytesIO(data)) - return pil - - def pil_to_base64(out_pil): - out_buffer = io.BytesIO() - out_pil.save(out_buffer, format="PNG") - out_buffer.seek(0) - base64_bytes = base64.b64encode(out_buffer.read()) - base64_str = base64_bytes.decode("ascii") - return base64_str - from subprocess import Popen, PIPE, STDOUT - class SubprocessCorrection: - def __init__(self): - self.backend=correction_func.backend - self.child= Popen(["python", "postprocess.py"], stdin=PIPE, stdout=PIPE, stderr=STDOUT) - def run(self,img_input,img_inpainted,mode): - if mode=="disabled": - return img_inpainted - base64_str_input = pil_to_base64(img_input) - base64_str_inpainted = pil_to_base64(img_inpainted) - try: - if self.child.poll(): - self.child= Popen(["python", "postprocess.py"], stdin=PIPE, stdout=PIPE, stderr=STDOUT) - self.child.stdin.write(f"{base64_str_input},{base64_str_inpainted},{mode}\n".encode()) - self.child.stdin.flush() - out = self.child.stdout.readline() - base64_str=out.decode().strip() - while base64_str and base64_str[0]=="[": - print(base64_str) - out = self.child.stdout.readline() - base64_str=out.decode().strip() - ret=base64_to_pil(base64_str) - except: - print("[PIE] not working, photometric correction is disabled") - ret=img_inpainted - return ret - correction_func = SubprocessCorrection() diff --git a/spaces/GaenKoki/voicevox/voicevox_engine/full_context_label.py b/spaces/GaenKoki/voicevox/voicevox_engine/full_context_label.py deleted file mode 100644 index 894a56751ad95a979487cf1cbf4e846f8e163d04..0000000000000000000000000000000000000000 --- a/spaces/GaenKoki/voicevox/voicevox_engine/full_context_label.py +++ /dev/null @@ -1,525 +0,0 @@ -import re -from dataclasses import dataclass -from itertools import chain -from typing import Dict, List, Optional - -import pyopenjtalk - - -@dataclass -class Phoneme: - """ - 音素(母音・子音)クラス、音素の元となるcontextを保持する - 音素には、母音や子音以外にも無音(silent/pause)も含まれる - - Attributes - ---------- - contexts: Dict[str, str] - 音素の元 - """ - - contexts: Dict[str, str] - - @classmethod - def from_label(cls, label: str): - """ - pyopenjtalk.extract_fullcontextで得られる音素の元(ラベル)から、Phonemeクラスを作成する - Parameters - ---------- - label : str - pyopenjtalk.extract_fullcontextで得られるラベルを渡す - - Returns - ------- - phoneme: Phoneme - Phonemeクラスを返す - """ - - # フルコンテキストラベルの仕様は、 - # http://hts.sp.nitech.ac.jp/?Download の HTS-2.3のJapanese tar.bz2 (126 MB)をダウンロードして、data/lab_format.pdfを見るとリストが見つかります。 # noqa - contexts = re.search( - r"^(?P.+?)\^(?P.+?)\-(?P.+?)\+(?P.+?)\=(?P.+?)" - r"/A\:(?P.+?)\+(?P.+?)\+(?P.+?)" - r"/B\:(?P.+?)\-(?P.+?)\_(?P.+?)" - r"/C\:(?P.+?)\_(?P.+?)\+(?P.+?)" - r"/D\:(?P.+?)\+(?P.+?)\_(?P.+?)" - r"/E\:(?P.+?)\_(?P.+?)\!(?P.+?)\_(?P.+?)\-(?P.+?)" - r"/F\:(?P.+?)\_(?P.+?)\#(?P.+?)\_(?P.+?)\@(?P.+?)\_(?P.+?)\|(?P.+?)\_(?P.+?)" # noqa - r"/G\:(?P.+?)\_(?P.+?)\%(?P.+?)\_(?P.+?)\_(?P.+?)" - r"/H\:(?P

    .+?)\_(?P

    .+?)" - r"/I\:(?P.+?)\-(?P.+?)\@(?P.+?)\+(?P.+?)\&(?P.+?)\-(?P.+?)\|(?P.+?)\+(?P.+?)" # noqa - r"/J\:(?P.+?)\_(?P.+?)" - r"/K\:(?P.+?)\+(?P.+?)\-(?P.+?)$", - label, - ).groupdict() - return cls(contexts=contexts) - - @property - def label(self): - """ - pyopenjtalk.extract_fullcontextで得られるラベルと等しい - Returns - ------- - lebel: str - ラベルを返す - """ - return ( - "{p1}^{p2}-{p3}+{p4}={p5}" - "/A:{a1}+{a2}+{a3}" - "/B:{b1}-{b2}_{b3}" - "/C:{c1}_{c2}+{c3}" - "/D:{d1}+{d2}_{d3}" - "/E:{e1}_{e2}!{e3}_{e4}-{e5}" - "/F:{f1}_{f2}#{f3}_{f4}@{f5}_{f6}|{f7}_{f8}" - "/G:{g1}_{g2}%{g3}_{g4}_{g5}" - "/H:{h1}_{h2}" - "/I:{i1}-{i2}@{i3}+{i4}&{i5}-{i6}|{i7}+{i8}" - "/J:{j1}_{j2}" - "/K:{k1}+{k2}-{k3}" - ).format(**self.contexts) - - @property - def phoneme(self): - """ - 音素クラスの中で、発声に必要な要素を返す - Returns - ------- - phoneme : str - 発声に必要な要素を返す - """ - return self.contexts["p3"] - - def is_pause(self): - """ - 音素がポーズ(無音、silent/pause)であるかを返す - Returns - ------- - is_pose : bool - 音素がポーズ(無音、silent/pause)であるか(True)否か(False) - """ - return self.contexts["f1"] == "xx" - - def __repr__(self): - return f"" - - -@dataclass -class Mora: - """ - モーラクラス - モーラは1音素(母音や促音「っ」、撥音「ん」など)か、2音素(母音と子音の組み合わせ)で成り立つ - - Attributes - ---------- - consonant : Optional[Phoneme] - 子音 - vowel : Phoneme - 母音 - """ - - consonant: Optional[Phoneme] - vowel: Phoneme - - def set_context(self, key: str, value: str): - """ - Moraクラス内に含まれるPhonemeのcontextのうち、指定されたキーの値を変更する - consonantが存在する場合は、vowelと同じようにcontextを変更する - Parameters - ---------- - key : str - 変更したいcontextのキー - value : str - 変更したいcontextの値 - """ - self.vowel.contexts[key] = value - if self.consonant is not None: - self.consonant.contexts[key] = value - - @property - def phonemes(self): - """ - 音素群を返す - Returns - ------- - phonemes : List[Phoneme] - 母音しかない場合は母音のみ、子音もある場合は子音、母音の順番でPhonemeのリストを返す - """ - if self.consonant is not None: - return [self.consonant, self.vowel] - else: - return [self.vowel] - - @property - def labels(self): - """ - ラベル群を返す - Returns - ------- - labels : List[str] - Moraに含まれるすべてのラベルを返す - """ - return [p.label for p in self.phonemes] - - -@dataclass -class AccentPhrase: - """ - アクセント句クラス - 同じアクセントのMoraを複数保持する - Attributes - ---------- - moras : List[Mora] - 音韻のリスト - accent : int - アクセント - """ - - moras: List[Mora] - accent: int - is_interrogative: bool - - @classmethod - def from_phonemes(cls, phonemes: List[Phoneme]): - """ - PhonemeのリストからAccentPhraseクラスを作成する - Parameters - ---------- - phonemes : List[Phoneme] - phonemeのリストを渡す - - Returns - ------- - accent_phrase : AccentPhrase - AccentPhraseクラスを返す - """ - moras: List[Mora] = [] - - mora_phonemes: List[Phoneme] = [] - for phoneme, next_phoneme in zip(phonemes, phonemes[1:] + [None]): - # workaround for Hihosiba/voicevox_engine#57 - # (py)openjtalk によるアクセント句内のモーラへの附番は 49 番目まで - # 49 番目のモーラについて、続く音素のモーラ番号を単一モーラの特定に使えない - if int(phoneme.contexts["a2"]) == 49: - break - - mora_phonemes.append(phoneme) - - if ( - next_phoneme is None - or phoneme.contexts["a2"] != next_phoneme.contexts["a2"] - ): - if len(mora_phonemes) == 1: - consonant, vowel = None, mora_phonemes[0] - elif len(mora_phonemes) == 2: - consonant, vowel = mora_phonemes[0], mora_phonemes[1] - else: - raise ValueError(mora_phonemes) - mora = Mora(consonant=consonant, vowel=vowel) - moras.append(mora) - mora_phonemes = [] - - accent = int(moras[0].vowel.contexts["f2"]) - # workaround for Hihosiba/voicevox_engine#55 - # アクセント位置とするキー f2 の値がアクセント句内のモーラ数を超える場合がある - accent = accent if accent <= len(moras) else len(moras) - is_interrogative = moras[-1].vowel.contexts["f3"] == "1" - return cls(moras=moras, accent=accent, is_interrogative=is_interrogative) - - def set_context(self, key: str, value: str): - """ - AccentPhraseに間接的に含まれる全てのPhonemeのcontextの、指定されたキーの値を変更する - Parameters - ---------- - key : str - 変更したいcontextのキー - value : str - 変更したいcontextの値 - """ - for mora in self.moras: - mora.set_context(key, value) - - @property - def phonemes(self): - """ - 音素群を返す - Returns - ------- - phonemes : List[Phoneme] - AccentPhraseに間接的に含まれる全てのPhonemeを返す - """ - return list(chain.from_iterable(m.phonemes for m in self.moras)) - - @property - def labels(self): - """ - ラベル群を返す - Returns - ------- - labels : List[str] - AccentPhraseに間接的に含まれる全てのラベルを返す - """ - return [p.label for p in self.phonemes] - - def merge(self, accent_phrase: "AccentPhrase"): - """ - AccentPhraseを合成する - (このクラスが保持するmorasの後ろに、引数として渡されたAccentPhraseのmorasを合成する) - Parameters - ---------- - accent_phrase : AccentPhrase - 合成したいAccentPhraseを渡す - - Returns - ------- - accent_phrase : AccentPhrase - 合成されたAccentPhraseを返す - """ - return AccentPhrase( - moras=self.moras + accent_phrase.moras, - accent=self.accent, - is_interrogative=accent_phrase.is_interrogative, - ) - - -@dataclass -class BreathGroup: - """ - 発声の区切りクラス - アクセントの異なるアクセント句を複数保持する - Attributes - ---------- - accent_phrases : List[AccentPhrase] - アクセント句のリスト - """ - - accent_phrases: List[AccentPhrase] - - @classmethod - def from_phonemes(cls, phonemes: List[Phoneme]): - """ - PhonemeのリストからBreathGroupクラスを作成する - Parameters - ---------- - phonemes : List[Phoneme] - phonemeのリストを渡す - - Returns - ------- - breath_group : BreathGroup - BreathGroupクラスを返す - """ - accent_phrases: List[AccentPhrase] = [] - accent_phonemes: List[Phoneme] = [] - for phoneme, next_phoneme in zip(phonemes, phonemes[1:] + [None]): - accent_phonemes.append(phoneme) - - if ( - next_phoneme is None - or phoneme.contexts["i3"] != next_phoneme.contexts["i3"] - or phoneme.contexts["f5"] != next_phoneme.contexts["f5"] - ): - accent_phrase = AccentPhrase.from_phonemes(accent_phonemes) - accent_phrases.append(accent_phrase) - accent_phonemes = [] - - return cls(accent_phrases=accent_phrases) - - def set_context(self, key: str, value: str): - """ - BreathGroupに間接的に含まれる全てのPhonemeのcontextの、指定されたキーの値を変更する - Parameters - ---------- - key : str - 変更したいcontextのキー - value : str - 変更したいcontextの値 - """ - for accent_phrase in self.accent_phrases: - accent_phrase.set_context(key, value) - - @property - def phonemes(self): - """ - 音素群を返す - Returns - ------- - phonemes : List[Phoneme] - BreathGroupに間接的に含まれる全てのPhonemeを返す - """ - return list( - chain.from_iterable( - accent_phrase.phonemes for accent_phrase in self.accent_phrases - ) - ) - - @property - def labels(self): - """ - ラベル群を返す - Returns - ------- - labels : List[str] - BreathGroupに間接的に含まれる全てのラベルを返す - """ - return [p.label for p in self.phonemes] - - -@dataclass -class Utterance: - """ - 発声クラス - 発声の区切りと無音を複数保持する - Attributes - ---------- - breath_groups : List[BreathGroup] - 発声の区切りのリスト - pauses : List[Phoneme] - 無音のリスト - """ - - breath_groups: List[BreathGroup] - pauses: List[Phoneme] - - @classmethod - def from_phonemes(cls, phonemes: List[Phoneme]): - """ - Phonemeの完全なリストからUtteranceクラスを作成する - Parameters - ---------- - phonemes : List[Phoneme] - phonemeのリストを渡す - - Returns - ------- - utterance : Utterance - Utteranceクラスを返す - """ - pauses: List[Phoneme] = [] - - breath_groups: List[BreathGroup] = [] - group_phonemes: List[Phoneme] = [] - for phoneme in phonemes: - if not phoneme.is_pause(): - group_phonemes.append(phoneme) - - else: - pauses.append(phoneme) - - if len(group_phonemes) > 0: - breath_group = BreathGroup.from_phonemes(group_phonemes) - breath_groups.append(breath_group) - group_phonemes = [] - - return cls(breath_groups=breath_groups, pauses=pauses) - - def set_context(self, key: str, value: str): - """ - Utteranceに間接的に含まれる全てのPhonemeのcontextの、指定されたキーの値を変更する - Parameters - ---------- - key : str - 変更したいcontextのキー - value : str - 変更したいcontextの値 - """ - for breath_group in self.breath_groups: - breath_group.set_context(key, value) - - @property - def phonemes(self): - """ - 音素群を返す - Returns - ------- - phonemes : List[Phoneme] - Utteranceクラスに直接的・間接的に含まれる、全てのPhonemeを返す - """ - accent_phrases = list( - chain.from_iterable( - breath_group.accent_phrases for breath_group in self.breath_groups - ) - ) - for prev, cent, post in zip( - [None] + accent_phrases[:-1], - accent_phrases, - accent_phrases[1:] + [None], - ): - mora_num = len(cent.moras) - accent = cent.accent - - if prev is not None: - prev.set_context("g1", str(mora_num)) - prev.set_context("g2", str(accent)) - - if post is not None: - post.set_context("e1", str(mora_num)) - post.set_context("e2", str(accent)) - - cent.set_context("f1", str(mora_num)) - cent.set_context("f2", str(accent)) - for i_mora, mora in enumerate(cent.moras): - mora.set_context("a1", str(i_mora - accent + 1)) - mora.set_context("a2", str(i_mora + 1)) - mora.set_context("a3", str(mora_num - i_mora)) - - for prev, cent, post in zip( - [None] + self.breath_groups[:-1], - self.breath_groups, - self.breath_groups[1:] + [None], - ): - accent_phrase_num = len(cent.accent_phrases) - - if prev is not None: - prev.set_context("j1", str(accent_phrase_num)) - - if post is not None: - post.set_context("h1", str(accent_phrase_num)) - - cent.set_context("i1", str(accent_phrase_num)) - cent.set_context( - "i5", str(accent_phrases.index(cent.accent_phrases[0]) + 1) - ) - cent.set_context( - "i6", - str(len(accent_phrases) - accent_phrases.index(cent.accent_phrases[0])), - ) - - self.set_context( - "k2", - str( - sum( - [ - len(breath_group.accent_phrases) - for breath_group in self.breath_groups - ] - ) - ), - ) - - phonemes: List[Phoneme] = [] - for i in range(len(self.pauses)): - if self.pauses[i] is not None: - phonemes += [self.pauses[i]] - - if i < len(self.pauses) - 1: - phonemes += self.breath_groups[i].phonemes - - return phonemes - - @property - def labels(self): - """ - ラベル群を返す - Returns - ------- - labels : List[str] - Utteranceクラスに直接的・間接的に含まれる全てのラベルを返す - """ - return [p.label for p in self.phonemes] - - -def extract_full_context_label(text: str): - labels = pyopenjtalk.extract_fullcontext(text) - phonemes = [Phoneme.from_label(label=label) for label in labels] - utterance = Utterance.from_phonemes(phonemes) - return utterance diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/mmseg/core/__init__.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/mmseg/core/__init__.py deleted file mode 100644 index 965605587211b7bf0bd6bc3acdbb33dd49cab023..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/mmseg/core/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .evaluation import * # noqa: F401, F403 -from .seg import * # noqa: F401, F403 -from .utils import * # noqa: F401, F403 diff --git a/spaces/HCMUT-GraduateThesis-HNTThinh/rgbdsod-multimae-demo/s_multimae/evaluation_metrics.py b/spaces/HCMUT-GraduateThesis-HNTThinh/rgbdsod-multimae-demo/s_multimae/evaluation_metrics.py deleted file mode 100644 index 025dd51ca15e941a975abc0f919fc86c38391b72..0000000000000000000000000000000000000000 --- a/spaces/HCMUT-GraduateThesis-HNTThinh/rgbdsod-multimae-demo/s_multimae/evaluation_metrics.py +++ /dev/null @@ -1,64 +0,0 @@ -import numpy as np -from py_sod_metrics import MAE, Emeasure, Fmeasure, Smeasure - -def ndarray_to_basetype(data): - def _to_list_or_scalar(item): - listed_item = item.tolist() - if isinstance(listed_item, list) and len(listed_item) == 1: - listed_item = listed_item[0] - return listed_item - - if isinstance(data, (tuple, list)): - results = [_to_list_or_scalar(item) for item in data] - elif isinstance(data, dict): - results = {k: _to_list_or_scalar(item) for k, item in data.items()} - else: - assert isinstance(data, np.ndarray) - results = _to_list_or_scalar(data) - return results - - -class CalTotalMetric(object): - def __init__(self): - self.mae = MAE() - self.fm = Fmeasure() - self.sm = Smeasure() - self.em = Emeasure() - # self.wfm = WeightedFmeasure() - - def step(self, pre: np.ndarray, gt: np.ndarray): - assert pre.shape == gt.shape - assert pre.dtype == np.uint8 - assert gt.dtype == np.uint8 - - self.mae.step(pre, gt) - self.sm.step(pre, gt) - self.fm.step(pre, gt) - self.em.step(pre, gt) - # self.wfm.step(pre, gt) - - def get_results(self, num_bits: int = 8, return_ndarray: bool = False) -> dict: - fm_info = self.fm.get_results() - fm = fm_info["fm"] - # pr = fm_info["pr"] - # wfm = self.wfm.get_results()["wfm"] - sm = self.sm.get_results()["sm"] - em = self.em.get_results()["em"] - mae = self.mae.get_results()["mae"] - - numerical_results = { - "SM": sm, - "MAE": mae, - "maxE": em["curve"].max(), - # "avgE": em["curve"].mean(), - # "adpE": em["adp"], - "maxF": fm["curve"].max(), - # "avgF": fm["curve"].mean(), - # "adpF": fm["adp"], - # "wFm": wfm, - } - if num_bits is not None and isinstance(num_bits, int): - numerical_results = {k: v.round(num_bits) for k, v in numerical_results.items()} - if not return_ndarray: - numerical_results = ndarray_to_basetype(numerical_results) - return numerical_results \ No newline at end of file diff --git a/spaces/Hahsgsgsy/teston/README.md b/spaces/Hahsgsgsy/teston/README.md deleted file mode 100644 index d46e03d6fcbf8b856bfd15a033a702635338207f..0000000000000000000000000000000000000000 --- a/spaces/Hahsgsgsy/teston/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Teston -emoji: 📉 -colorFrom: gray -colorTo: green -sdk: streamlit -sdk_version: 1.19.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/HarryLee/eCommerceImageCaptioning/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/prepare_lang.sh b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/prepare_lang.sh deleted file mode 100644 index e9a80001eb47d5af863d6aab11a59362a59cef61..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/examples/wav2vec/unsupervised/kaldi_self_train/st/local/prepare_lang.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -sil_prob=0.5 -num_sil_states=3 -num_nonsil_states=1 - -. ./cmd.sh -. ./path.sh -. parse_options.sh - -set -eux - -dict=$1 -data_dir=$2 - -dict_dir=$data_dir/local/dict -tmplm_dir=$data_dir/local/lang_tmp -lm_dir=$data_dir/lang - -mkdir -p $dict_dir $tmplm_dir $lm_dir - -# prepare dict -echo "SIL" > $dict_dir/silence_phones.txt -echo "SIL" > $dict_dir/optional_silence.txt -awk '{print $1}' $dict > $dict_dir/nonsilence_phones.txt - -echo "SIL SIL" > $dict_dir/lexicon.txt -echo " SIL" >> $dict_dir/lexicon.txt -awk '{print $1" "$1}' $dict >> $dict_dir/lexicon.txt - -echo "SIL" > $dict_dir/extra_questions.txt -awk '{printf $1" "} END {printf "\n"}' $dict >> $dict_dir/extra_questions.txt - -# prepare lang -utils/prepare_lang.sh --sil-prob $sil_prob --position-dependent-phones false \ - --num_sil_states $num_sil_states --num_nonsil_states $num_nonsil_states \ - $dict_dir "" $tmplm_dir $lm_dir diff --git a/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/utils/inference/advanced_tts.py b/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/utils/inference/advanced_tts.py deleted file mode 100644 index 6f8e2f5870e0f7dcd28c35c71cde58de6f1ae415..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/utils/inference/advanced_tts.py +++ /dev/null @@ -1,155 +0,0 @@ - -from .tts import TextToMel, MelToWav -from .transliterate import XlitEngine -from .num_to_word_on_sent import normalize_nums - -import re -import numpy as np -from scipy.io.wavfile import write - -from mosestokenizer import * -from indicnlp.tokenize import sentence_tokenize -import argparse - -_INDIC = ["as", "bn", "gu", "hi", "kn", "ml", "mr", "or", "pa", "ta", "te"] -_PURAM_VIRAM_LANGUAGES = ["hi", "or", "bn", "as"] -_TRANSLITERATION_NOT_AVAILABLE_IN = ["en","or"] -#_NUM2WORDS_NOT_AVAILABLE_IN = [] - -def normalize_text(text, lang): - if lang in _PURAM_VIRAM_LANGUAGES: - text = text.replace('|', '।') - text = text.replace('.', '।') - return text - -def split_sentences(paragraph, language): - if language == "en": - with MosesSentenceSplitter(language) as splitter: - return splitter([paragraph]) - elif language in _INDIC: - return sentence_tokenize.sentence_split(paragraph, lang=language) - - - -def load_models(acoustic, vocoder, device): - text_to_mel = TextToMel(glow_model_dir=acoustic, device=device) - mel_to_wav = MelToWav(hifi_model_dir=vocoder, device=device) - return text_to_mel, mel_to_wav - - -def translit(text, lang): - reg = re.compile(r'[a-zA-Z]') - words = [engine.translit_word(word, topk=1)[lang][0] if reg.match(word) else word for word in text.split()] - updated_sent = ' '.join(words) - return updated_sent - - - -def run_tts(text, lang, args): - if lang == 'hi': - text = text.replace('।', '.') # only for hindi models - - if lang == 'en' and text[-1] != '.': - text = text + '. ' - - if args.number_conversion == 1 and lang!='en': - print("Doing number conversion") - text_num_to_word = normalize_nums(text, lang) # converting numbers to words in lang - else: - text_num_to_word = text - - - if args.transliteration == 1 and lang not in _TRANSLITERATION_NOT_AVAILABLE_IN: - print("Doing transliteration") - text_num_to_word_and_transliterated = translit(text_num_to_word, lang) # transliterating english words to lang - else: - text_num_to_word_and_transliterated = text_num_to_word - - final_text = ' ' + text_num_to_word_and_transliterated - print(final_text) - mel = text_to_mel.generate_mel(final_text, args.noise_scale, args.length_scale) - audio, sr = mel_to_wav.generate_wav(mel) - return sr, audio - -def run_tts_paragraph(args): - audio_list = [] - - global text_to_mel - global mel_to_wav - - if args.gender == 'Male': - text_to_mel = text_to_mel_list[1] - mel_to_wav = mel_to_wav_list[1] - else: - text_to_mel = text_to_mel_list[0] - mel_to_wav = mel_to_wav_list[0] - - - if args.split_sentences == 1: - text = normalize_text(args.text, args.lang) - split_sentences_list = split_sentences(text, args.lang) - - for sent in split_sentences_list: - - sr, audio = run_tts(sent, args.lang, args) - audio_list.append(audio) - - concatenated_audio = np.concatenate([i for i in audio_list]) - if args.wav: - write(filename=args.wav, rate=sr, data=concatenated_audio) - return (sr, concatenated_audio) - else: - sr, audio = run_tts(args.text, args.lang, args) - if args.wav: - write(filename=args.wav, rate=sr, data=audio) - return (sr, audio) - - -def load_all_models(args): - global engine - if args.lang not in _TRANSLITERATION_NOT_AVAILABLE_IN: - engine = XlitEngine(args.lang) # loading translit model globally - - global text_to_mel_list - global mel_to_wav_list - - - text_to_mel_list = [] - mel_to_wav_list = [] - - for acoustic, vocoder in zip( args.acoustic.split(',') , args.vocoder.split(',') ): - ttm, mtw = load_models(acoustic, vocoder, args.device) - text_to_mel_list.append(ttm) - mel_to_wav_list.append(mtw) - - try: - args.noise_scale = float(args.noise_scale) - args.length_scale = float(args.length_scale) - except: - pass - - print(args) - - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("-a", "--acoustic", required=True, type=str) - parser.add_argument("-v", "--vocoder", required=True, type=str) - parser.add_argument("-d", "--device", type=str, default="cpu") - parser.add_argument("-t", "--text", type=str, required=True) - parser.add_argument("-w", "--wav", type=str, required=True) - parser.add_argument("-n", "--noise-scale", default='0.667', type=str ) - parser.add_argument("-l", "--length-scale", default='1.0', type=str) - - parser.add_argument("-T", "--transliteration", default=1, type=int) - parser.add_argument("-N", "--number-conversion", default=1, type=int) - parser.add_argument("-S", "--split-sentences", default=1, type=int) - parser.add_argument("-L", "--lang", type=str, required=True) - - args = parser.parse_args() - - load_all_models(args) - run_tts_paragraph(args) - - diff --git a/spaces/Harveenchadha/en_to_indic_translation/legacy/apply_bpe_test_valid_notag.sh b/spaces/Harveenchadha/en_to_indic_translation/legacy/apply_bpe_test_valid_notag.sh deleted file mode 100644 index f152770c4ad7d5c13f72b492d50ffff238ff44f0..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/en_to_indic_translation/legacy/apply_bpe_test_valid_notag.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash - -expdir=$1 # EXPDIR -org_data_dir=$2 -langs=$3 - -#`dirname $0`/env.sh -SUBWORD_NMT_DIR="subword-nmt" -echo "Apply to each language" - -for dset in `echo test dev` -do - echo $dset - - in_dset_dir="$org_data_dir/$dset" - out_dset_dir="$expdir/bpe/$dset" - - for lang in $langs - do - - echo Apply BPE for $dset "-" $lang - - mkdir -p $out_dset_dir - - python $SUBWORD_NMT_DIR/subword_nmt/apply_bpe.py \ - -c $expdir/vocab/bpe_codes.32k.SRC_TGT \ - --vocabulary $expdir/vocab/vocab.SRC \ - --vocabulary-threshold 5 \ - < $in_dset_dir/$dset.$lang \ - > $out_dset_dir/$dset.$lang - - done -done diff --git a/spaces/Hexamind/swarms/README.md b/spaces/Hexamind/swarms/README.md deleted file mode 100644 index db90d4b4daffc07b41cc6e4b279cb08d7c025fbd..0000000000000000000000000000000000000000 --- a/spaces/Hexamind/swarms/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Swarms -emoji: 👁 -colorFrom: yellow -colorTo: pink -sdk: streamlit -sdk_version: 1.21.0 -python_version: "3.10" -app_file: app.py -pinned: false -license: bsd-2-clause ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/ICML2022/OFA/fairseq/examples/speech_text_joint_to_text/README.md b/spaces/ICML2022/OFA/fairseq/examples/speech_text_joint_to_text/README.md deleted file mode 100644 index e071d241e0e02b35d3aac777ac09b4ef3be9119f..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/speech_text_joint_to_text/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# Joint Speech Text training in Fairseq -An extension of Fairseq s2t project with the speech to text task enhanced by the co-trained text to text mapping task. More details about Fairseq s2t can be found [here](../speech_to_text/README.md) - -## Examples -Examples of speech text joint training in fairseq -- [English-to-German MuST-C model](docs/ende-mustc.md) -- [IWSLT 2021 Multilingual Speech Translation](docs/iwslt2021.md) - -## Citation -Please cite as: -``` -@inproceedings{Tang2021AGM, - title={A General Multi-Task Learning Framework to Leverage Text Data for Speech to Text Tasks}, - author={Yun Tang and J. Pino and Changhan Wang and Xutai Ma and Dmitriy Genzel}, - booktitle={ICASSP}, - year={2021} -} - -@inproceedings{Tang2021IST, - title = {Improving Speech Translation by Understanding and Learning from the Auxiliary Text Translation Task}, - author = {Yun Tang and Juan Pino and Xian Li and Changhan Wang and Dmitriy Genzel}, - booktitle = {ACL}, - year = {2021}, -} - -@inproceedings{Tang2021FST, - title = {FST: the FAIR Speech Translation System for the IWSLT21 Multilingual Shared Task}, - author = {Yun Tang and Hongyu Gong and Xian Li and Changhan Wang and Juan Pino and Holger Schwenk and Naman Goyal}, - booktitle = {IWSLT}, - year = {2021}, -} - -@inproceedings{wang2020fairseqs2t, - title = {fairseq S2T: Fast Speech-to-Text Modeling with fairseq}, - author = {Changhan Wang and Yun Tang and Xutai Ma and Anne Wu and Dmytro Okhonko and Juan Pino}, - booktitle = {Proceedings of the 2020 Conference of the Asian Chapter of the Association for Computational Linguistics (AACL): System Demonstrations}, - year = {2020}, -} - -@inproceedings{ott2019fairseq, - title = {fairseq: A Fast, Extensible Toolkit for Sequence Modeling}, - author = {Myle Ott and Sergey Edunov and Alexei Baevski and Angela Fan and Sam Gross and Nathan Ng and David Grangier and Michael Auli}, - booktitle = {Proceedings of NAACL-HLT 2019: Demonstrations}, - year = {2019}, -} -``` diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/modules/dynamicconv_layer/dynamicconv_layer.py b/spaces/ICML2022/OFA/fairseq/fairseq/modules/dynamicconv_layer/dynamicconv_layer.py deleted file mode 100644 index 711ed03483f4089dbe91964a89021b49eeffbedc..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/modules/dynamicconv_layer/dynamicconv_layer.py +++ /dev/null @@ -1,227 +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 dynamicconv_cuda -import torch -import torch.nn.functional as F -from fairseq import utils -from fairseq.incremental_decoding_utils import with_incremental_state -from fairseq.modules.fairseq_dropout import FairseqDropout -from fairseq.modules.unfold import unfold1d -from torch import nn -from torch.autograd import Function - - -class dynamicconvFunction(Function): - @staticmethod - def forward(ctx, x, weights, padding_l): - ctx.padding_l = padding_l - outputs = dynamicconv_cuda.forward(x, weights, padding_l) - variables = [x, weights] - ctx.save_for_backward(*variables) - return outputs[0] - - @staticmethod - def backward(ctx, grad_output): - outputs = dynamicconv_cuda.backward( - grad_output.contiguous(), ctx.padding_l, *ctx.saved_tensors - ) - grad_input, grad_weights = outputs - return grad_input, grad_weights, None - - -@with_incremental_state -class DynamicconvLayer(nn.Module): - def __init__( - self, - input_size, - kernel_size=1, - padding_l=None, - weight_softmax=False, - num_heads=1, - weight_dropout=0.0, - bias=False, - renorm_padding=False, - conv_bias=False, - query_size=None, - ): - - super(DynamicconvLayer, self).__init__() - self.input_size = input_size - self.query_size = input_size if query_size is None else query_size - self.kernel_size = kernel_size - self.padding_l = padding_l - self.num_heads = num_heads - self.weight_softmax = weight_softmax - self.weight_dropout_module = FairseqDropout( - weight_dropout, module_name=self.__class__.__name__ - ) - self.renorm_padding = renorm_padding - self.bias = bias - - self.weight_linear = nn.Linear(input_size, num_heads * kernel_size, bias) - if conv_bias: - self.conv_bias = nn.Parameter(torch.Tensor(input_size)) - else: - self.conv_bias = None - self.reset_parameters() - - def reset_parameters(self): - nn.init.xavier_uniform_(self.weight_linear.weight) - if self.conv_bias is not None: - nn.init.constant_(self.conv_bias, 0.0) - nn.init.constant_(self.weight_linaer.bias, 0.0) - - def forward(self, x, incremental_state=None, query=None, unfold=None): - - T, B, C = x.size() - K, H = self.kernel_size, self.num_heads - # R = C // H - - # during inference time, incremental BMM is faster - if incremental_state is not None: - unfold = ( - x.size(0) > 512 if unfold is None else unfold - ) # use unfold mode as default for long sequence to save memory - unfold = unfold or (incremental_state is not None) - assert query is None - - if query is None: - query = x - if unfold: - output = self._forward_unfolded(x, incremental_state, query) - else: - output = self._forward_expanded(x, incremental_state, query) - - if self.conv_bias is not None: - output = output + self.conv_bias.view(1, 1, -1) - - return output - - # during training time, use CUDA kernel - else: - weight = self.weight_linear(x).view(T, B, H, K) - if self.weight_softmax: - weight = F.softmax(weight, dim=-1) - if self.weight_dropout_module.p: - weight = self.weight_dropout_module(weight) - - weight = weight.permute(1, 2, 3, 0).contiguous() - self.filters = weight - x = x.permute(1, 2, 0).contiguous() - output = dynamicconvFunction.apply(x, weight, self.padding_l).permute( - 2, 0, 1 - ) - if self.conv_bias is not None: - output = output + self.conv_bias.view(1, 1, -1) - return output - - def reorder_incremental_state(self, incremental_state, new_order): - input_buffer = self._get_input_buffer(incremental_state) - if input_buffer is not None: - input_buffer = input_buffer.index_select(1, new_order) - self._set_input_buffer(incremental_state, input_buffer) - - def _get_input_buffer(self, incremental_state): - return utils.get_incremental_state(self, incremental_state, "input_buffer") - - def _set_input_buffer(self, incremental_state, new_buffer): - return utils.set_incremental_state( - self, incremental_state, "input_buffer", new_buffer - ) - - def _forward_unfolded(self, x, incremental_state, query): - """The conventional implementation of convolutions. - Unfolding the input by having a window shifting to the right.""" - T, B, C = x.size() - K, H = self.kernel_size, self.num_heads - R = C // H - assert R * H == C == self.input_size - - weight = self.weight_linear(query).view(T * B * H, -1) - - # renorm_padding is only implemented in _forward_expanded - assert not self.renorm_padding or incremental_state is not None - - if incremental_state is not None: - input_buffer = self._get_input_buffer(incremental_state) - if input_buffer is None: - input_buffer = x.new() - x_unfold = torch.cat([input_buffer, x.unsqueeze(3)], dim=3) - if self.kernel_size > 1: - self._set_input_buffer( - incremental_state, x_unfold[:, :, :, -self.kernel_size + 1 :] - ) - x_unfold = x_unfold.view(T * B * H, R, -1) - else: - padding_l = self.padding_l - if K > T and padding_l == K - 1: - weight = weight.narrow(1, K - T, T) - K, padding_l = T, T - 1 - # unfold the input: T x B x C --> T' x B x C x K - x_unfold = unfold1d(x, K, padding_l, 0) - x_unfold = x_unfold.view(T * B * H, R, K) - - if self.weight_softmax and not self.renorm_padding: - weight = F.softmax(weight, dim=1) - weight = weight.narrow(1, 0, K) - - if incremental_state is not None: - weight = weight[:, -x_unfold.size(2) :] - K = weight.size(1) - - if self.weight_softmax and self.renorm_padding: - weight = F.softmax(weight, dim=1) - - weight = self.weight_dropout_module(weight, inplace=False) - - output = torch.bmm(x_unfold, weight.unsqueeze(2)) # T*B*H x R x 1 - output = output.view(T, B, C) - return output - - def _forward_expanded(self, x, incremental_stat, query): - """Turn the convolution filters into band matrices and do matrix multiplication. - This is faster when the sequence is short, but less memory efficient. - This is not used in the decoder during inference. - """ - T, B, C = x.size() - K, H = self.kernel_size, self.num_heads - R = C // H - assert R * H == C == self.input_size - weight = self.weight_linear(query).view(T * B * H, -1) - - if not self.renorm_padding: - if self.weight_softmax: - weight = F.softmax(weight, dim=1) - weight = self.weight_dropout_module(weight, inplace=False) - weight = weight.narrow(1, 0, K).contiguous() - weight = weight.view(T, B * H, K).transpose(0, 1) - - x = x.view(T, B * H, R).transpose(0, 1) - if self.weight_softmax and self.renorm_padding: - # turn the convolution filters into band matrices - weight_expanded = weight.new(B * H, T, T + K - 1).fill_(float("-inf")) - weight_expanded.as_strided( - (B * H, T, K), (T * (T + K - 1), T + K, 1) - ).copy_(weight) - weight_expanded = weight_expanded.narrow(2, self.padding_l, T) - # normalize the weight over valid positions like self-attention - weight_expanded = F.softmax(weight_expanded, dim=2) - weight_expanded = self.weight_dropout_module(weight_expanded, inplace=False) - else: - P = self.padding_l - # For efficiency, we cut the kernel size and reduce the padding when the kernel is larger than the length - if K > T and P == K - 1: - weight = weight.narrow(2, K - T, T) - K, P = T, T - 1 - # turn the convolution filters into band matrices - weight_expanded = weight.new_zeros(B * H, T, T + K - 1, requires_grad=False) - weight_expanded.as_strided( - (B * H, T, K), (T * (T + K - 1), T + K, 1) - ).copy_(weight) - weight_expanded = weight_expanded.narrow(2, P, T) # B*H x T x T - output = torch.bmm(weight_expanded, x) - output = output.transpose(0, 1).contiguous().view(T, B, C) - return output diff --git a/spaces/Ibtehaj10/cheating-detection-FYP/yolovs5/utils/flask_rest_api/README.md b/spaces/Ibtehaj10/cheating-detection-FYP/yolovs5/utils/flask_rest_api/README.md deleted file mode 100644 index a726acbd92043458311dd949cc09c0195cd35400..0000000000000000000000000000000000000000 --- a/spaces/Ibtehaj10/cheating-detection-FYP/yolovs5/utils/flask_rest_api/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# Flask REST API - -[REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are -commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API -created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/). - -## Requirements - -[Flask](https://palletsprojects.com/p/flask/) is required. Install with: - -```shell -$ pip install Flask -``` - -## Run - -After Flask installation run: - -```shell -$ python3 restapi.py --port 5000 -``` - -Then use [curl](https://curl.se/) to perform a request: - -```shell -$ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s' -``` - -The model inference results are returned as a JSON response: - -```json -[ - { - "class": 0, - "confidence": 0.8900438547, - "height": 0.9318675399, - "name": "person", - "width": 0.3264600933, - "xcenter": 0.7438579798, - "ycenter": 0.5207948685 - }, - { - "class": 0, - "confidence": 0.8440024257, - "height": 0.7155083418, - "name": "person", - "width": 0.6546785235, - "xcenter": 0.427829951, - "ycenter": 0.6334488392 - }, - { - "class": 27, - "confidence": 0.3771208823, - "height": 0.3902671337, - "name": "tie", - "width": 0.0696444362, - "xcenter": 0.3675483763, - "ycenter": 0.7991207838 - }, - { - "class": 27, - "confidence": 0.3527112305, - "height": 0.1540903747, - "name": "tie", - "width": 0.0336618312, - "xcenter": 0.7814827561, - "ycenter": 0.5065554976 - } -] -``` - -An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given -in `example_request.py` diff --git a/spaces/Illumotion/Koboldcpp/ggml-opencl.h b/spaces/Illumotion/Koboldcpp/ggml-opencl.h deleted file mode 100644 index 5edea8c9d78d9460f0892d19b931870eca5ffb73..0000000000000000000000000000000000000000 --- a/spaces/Illumotion/Koboldcpp/ggml-opencl.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "ggml.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void ggml_cl_init(void); - -void ggml_cl_mul(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst); -bool ggml_cl_can_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst); -size_t ggml_cl_mul_mat_get_wsize(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst); -void ggml_cl_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst, void * wdata, size_t wsize); - -void * ggml_cl_host_malloc(size_t size); -void ggml_cl_host_free(void * ptr); - -void ggml_cl_free_data(const struct ggml_tensor* tensor); - -void ggml_cl_transform_tensor(void * data, struct ggml_tensor * tensor); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/spaces/IndicNLP/Demo/app.py b/spaces/IndicNLP/Demo/app.py deleted file mode 100644 index 12b01ab5440e52c0b9ae7f186c0f03dcf8789b09..0000000000000000000000000000000000000000 --- a/spaces/IndicNLP/Demo/app.py +++ /dev/null @@ -1,37 +0,0 @@ -import streamlit as st - -st.title("IndicNLP!") -st.text("This is our Final Year Project,") -st.text("Implementing various features of NLP i.e,") -st.text("Natural Language Processing in Various Indic Languages.") -st.text("To Begin with Hindi,") -st.text("Here are Few Modules we have Implemented :-") - -add_selectbox = st.sidebar.selectbox( - "Which Module would you like to try?", - ("Part-of-Speech Tagging", "Questiom & Answer", "Grammar Checking") -) - -if add_selectbox == "Part-of-Speech Tagging" : - st.header('Part-Of-Speech, PoS-Tagging :- ') - pos_ip = st.text_input('Enter a Statement') - pos_btn = st.button("Process") - if pos_btn: - st.error("work's in progress :construction:, Come again later :smiley:") - -if add_selectbox == "Questiom & Answer" : - st.header('Question & Answering :- ') - text = st.text_area("Text to analyze") - que_ip = st.text_input('Enter the question') - qna_btn = st.button("Answer") - if qna_btn: - st.success("work's in progress :construction:, Come again later :smiley:") - -if add_selectbox == "Grammar Checking" : - st.header('Grammar Correction :- ') - grm_ip = st.text_input('Enter the Statement') - grm_btn = st.button("Check Grammar") - if grm_btn: - st.write("work's in progress :construction:, Come again later :smiley:") - -st.caption('Thank you for Tuning in, Come back for more :heart:') \ No newline at end of file diff --git a/spaces/JMalott/ai_architecture/min_dalle/models/__init__.py b/spaces/JMalott/ai_architecture/min_dalle/models/__init__.py deleted file mode 100644 index 5ac9af02c15d9df224b20d670fc847f73a41018b..0000000000000000000000000000000000000000 --- a/spaces/JMalott/ai_architecture/min_dalle/models/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .dalle_bart_encoder import DalleBartEncoder -from .dalle_bart_decoder import DalleBartDecoder -from .vqgan_detokenizer import VQGanDetokenizer \ No newline at end of file diff --git a/spaces/Jackflack09/diffuse-custom/diffusers/schedulers/scheduling_ddim_flax.py b/spaces/Jackflack09/diffuse-custom/diffusers/schedulers/scheduling_ddim_flax.py deleted file mode 100644 index 157321d4681639c865e77745f9513b9a9a43b466..0000000000000000000000000000000000000000 --- a/spaces/Jackflack09/diffuse-custom/diffusers/schedulers/scheduling_ddim_flax.py +++ /dev/null @@ -1,326 +0,0 @@ -# Copyright 2022 Stanford University Team and The HuggingFace Team. 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. - -# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion -# and https://github.com/hojonathanho/diffusion - -import math -from dataclasses import dataclass -from typing import Optional, Tuple, Union - -import flax -import jax.numpy as jnp - -from ..configuration_utils import ConfigMixin, register_to_config -from ..utils import deprecate -from .scheduling_utils_flax import ( - _FLAX_COMPATIBLE_STABLE_DIFFUSION_SCHEDULERS, - FlaxSchedulerMixin, - FlaxSchedulerOutput, - broadcast_to_shape_from_left, -) - - -def betas_for_alpha_bar(num_diffusion_timesteps, max_beta=0.999) -> jnp.ndarray: - """ - Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of - (1-beta) over time from t = [0,1]. - - Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up - to that part of the diffusion process. - - - Args: - num_diffusion_timesteps (`int`): the number of betas to produce. - max_beta (`float`): the maximum beta to use; use values lower than 1 to - prevent singularities. - - Returns: - betas (`jnp.ndarray`): the betas used by the scheduler to step the model outputs - """ - - def alpha_bar(time_step): - return math.cos((time_step + 0.008) / 1.008 * math.pi / 2) ** 2 - - betas = [] - for i in range(num_diffusion_timesteps): - t1 = i / num_diffusion_timesteps - t2 = (i + 1) / num_diffusion_timesteps - betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) - return jnp.array(betas, dtype=jnp.float32) - - -@flax.struct.dataclass -class DDIMSchedulerState: - # setable values - timesteps: jnp.ndarray - alphas_cumprod: jnp.ndarray - num_inference_steps: Optional[int] = None - - @classmethod - def create(cls, num_train_timesteps: int, alphas_cumprod: jnp.ndarray): - return cls(timesteps=jnp.arange(0, num_train_timesteps)[::-1], alphas_cumprod=alphas_cumprod) - - -@dataclass -class FlaxDDIMSchedulerOutput(FlaxSchedulerOutput): - state: DDIMSchedulerState - - -class FlaxDDIMScheduler(FlaxSchedulerMixin, ConfigMixin): - """ - Denoising diffusion implicit models is a scheduler that extends the denoising procedure introduced in denoising - diffusion probabilistic models (DDPMs) with non-Markovian guidance. - - [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__` - function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`. - [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and - [`~SchedulerMixin.from_pretrained`] functions. - - For more details, see the original paper: https://arxiv.org/abs/2010.02502 - - Args: - num_train_timesteps (`int`): number of diffusion steps used to train the model. - beta_start (`float`): the starting `beta` value of inference. - beta_end (`float`): the final `beta` value. - beta_schedule (`str`): - the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from - `linear`, `scaled_linear`, or `squaredcos_cap_v2`. - trained_betas (`jnp.ndarray`, optional): - option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc. - clip_sample (`bool`, default `True`): - option to clip predicted sample between -1 and 1 for numerical stability. - set_alpha_to_one (`bool`, default `True`): - each diffusion step uses the value of alphas product at that step and at the previous one. For the final - step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`, - otherwise it uses the value of alpha at step 0. - steps_offset (`int`, default `0`): - an offset added to the inference steps. You can use a combination of `offset=1` and - `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in - stable diffusion. - prediction_type (`str`, default `epsilon`): - indicates whether the model predicts the noise (epsilon), or the samples. One of `epsilon`, `sample`. - `v-prediction` is not supported for this scheduler. - - """ - - _compatibles = _FLAX_COMPATIBLE_STABLE_DIFFUSION_SCHEDULERS.copy() - _deprecated_kwargs = ["predict_epsilon"] - - @property - def has_state(self): - return True - - @register_to_config - def __init__( - self, - num_train_timesteps: int = 1000, - beta_start: float = 0.0001, - beta_end: float = 0.02, - beta_schedule: str = "linear", - set_alpha_to_one: bool = True, - steps_offset: int = 0, - prediction_type: str = "epsilon", - **kwargs, - ): - message = ( - "Please make sure to instantiate your scheduler with `prediction_type` instead. E.g. `scheduler =" - " FlaxDDIMScheduler.from_pretrained(, prediction_type='epsilon')`." - ) - predict_epsilon = deprecate("predict_epsilon", "0.11.0", message, take_from=kwargs) - if predict_epsilon is not None: - self.register_to_config(prediction_type="epsilon" if predict_epsilon else "sample") - - if beta_schedule == "linear": - self.betas = jnp.linspace(beta_start, beta_end, num_train_timesteps, dtype=jnp.float32) - elif beta_schedule == "scaled_linear": - # this schedule is very specific to the latent diffusion model. - self.betas = jnp.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=jnp.float32) ** 2 - elif beta_schedule == "squaredcos_cap_v2": - # Glide cosine schedule - self.betas = betas_for_alpha_bar(num_train_timesteps) - else: - raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}") - - self.alphas = 1.0 - self.betas - - # HACK for now - clean up later (PVP) - self._alphas_cumprod = jnp.cumprod(self.alphas, axis=0) - - # At every step in ddim, we are looking into the previous alphas_cumprod - # For the final step, there is no previous alphas_cumprod because we are already at 0 - # `set_alpha_to_one` decides whether we set this parameter simply to one or - # whether we use the final alpha of the "non-previous" one. - self.final_alpha_cumprod = jnp.array(1.0) if set_alpha_to_one else float(self._alphas_cumprod[0]) - - # standard deviation of the initial noise distribution - self.init_noise_sigma = 1.0 - - def scale_model_input( - self, state: DDIMSchedulerState, sample: jnp.ndarray, timestep: Optional[int] = None - ) -> jnp.ndarray: - """ - Args: - state (`PNDMSchedulerState`): the `FlaxPNDMScheduler` state data class instance. - sample (`jnp.ndarray`): input sample - timestep (`int`, optional): current timestep - - Returns: - `jnp.ndarray`: scaled input sample - """ - return sample - - def create_state(self): - return DDIMSchedulerState.create( - num_train_timesteps=self.config.num_train_timesteps, alphas_cumprod=self._alphas_cumprod - ) - - def _get_variance(self, timestep, prev_timestep, alphas_cumprod): - alpha_prod_t = alphas_cumprod[timestep] - alpha_prod_t_prev = jnp.where(prev_timestep >= 0, alphas_cumprod[prev_timestep], self.final_alpha_cumprod) - beta_prod_t = 1 - alpha_prod_t - beta_prod_t_prev = 1 - alpha_prod_t_prev - - variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev) - - return variance - - def set_timesteps( - self, state: DDIMSchedulerState, num_inference_steps: int, shape: Tuple = () - ) -> DDIMSchedulerState: - """ - Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. - - Args: - state (`DDIMSchedulerState`): - the `FlaxDDIMScheduler` state data class instance. - num_inference_steps (`int`): - the number of diffusion steps used when generating samples with a pre-trained model. - """ - offset = self.config.steps_offset - - step_ratio = self.config.num_train_timesteps // num_inference_steps - # creates integer timesteps by multiplying by ratio - # casting to int to avoid issues when num_inference_step is power of 3 - timesteps = (jnp.arange(0, num_inference_steps) * step_ratio).round()[::-1] - timesteps = timesteps + offset - - return state.replace(num_inference_steps=num_inference_steps, timesteps=timesteps) - - def step( - self, - state: DDIMSchedulerState, - model_output: jnp.ndarray, - timestep: int, - sample: jnp.ndarray, - return_dict: bool = True, - ) -> Union[FlaxDDIMSchedulerOutput, Tuple]: - """ - Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion - process from the learned model outputs (most often the predicted noise). - - Args: - state (`DDIMSchedulerState`): the `FlaxDDIMScheduler` state data class instance. - model_output (`jnp.ndarray`): direct output from learned diffusion model. - timestep (`int`): current discrete timestep in the diffusion chain. - sample (`jnp.ndarray`): - current instance of sample being created by diffusion process. - return_dict (`bool`): option for returning tuple rather than FlaxDDIMSchedulerOutput class - - Returns: - [`FlaxDDIMSchedulerOutput`] or `tuple`: [`FlaxDDIMSchedulerOutput`] if `return_dict` is True, otherwise a - `tuple`. When returning a tuple, the first element is the sample tensor. - - """ - if state.num_inference_steps is None: - raise ValueError( - "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" - ) - - # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf - # Ideally, read DDIM paper in-detail understanding - - # Notation ( -> - # - pred_noise_t -> e_theta(x_t, t) - # - pred_original_sample -> f_theta(x_t, t) or x_0 - # - std_dev_t -> sigma_t - # - eta -> η - # - pred_sample_direction -> "direction pointing to x_t" - # - pred_prev_sample -> "x_t-1" - - # TODO(Patrick) - eta is always 0.0 for now, allow to be set in step function - eta = 0.0 - - # 1. get previous step value (=t-1) - prev_timestep = timestep - self.config.num_train_timesteps // state.num_inference_steps - - alphas_cumprod = state.alphas_cumprod - - # 2. compute alphas, betas - alpha_prod_t = alphas_cumprod[timestep] - alpha_prod_t_prev = jnp.where(prev_timestep >= 0, alphas_cumprod[prev_timestep], self.final_alpha_cumprod) - - beta_prod_t = 1 - alpha_prod_t - - # 3. compute predicted original sample from predicted noise also called - # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - if self.config.prediction_type == "epsilon": - pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5) - elif self.config.prediction_type == "sample": - pred_original_sample = model_output - elif self.config.prediction_type == "v_prediction": - pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output - # predict V - model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample - else: - raise ValueError( - f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" - " `v_prediction`" - ) - - # 4. compute variance: "sigma_t(η)" -> see formula (16) - # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) - variance = self._get_variance(timestep, prev_timestep, alphas_cumprod) - std_dev_t = eta * variance ** (0.5) - - # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output - - # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf - prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction - - if not return_dict: - return (prev_sample, state) - - return FlaxDDIMSchedulerOutput(prev_sample=prev_sample, state=state) - - def add_noise( - self, - original_samples: jnp.ndarray, - noise: jnp.ndarray, - timesteps: jnp.ndarray, - ) -> jnp.ndarray: - sqrt_alpha_prod = self.alphas_cumprod[timesteps] ** 0.5 - sqrt_alpha_prod = sqrt_alpha_prod.flatten() - sqrt_alpha_prod = broadcast_to_shape_from_left(sqrt_alpha_prod, original_samples.shape) - - sqrt_one_minus_alpha_prod = (1 - self.alphas_cumprod[timesteps]) ** 0.0 - sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten() - sqrt_one_minus_alpha_prod = broadcast_to_shape_from_left(sqrt_one_minus_alpha_prod, original_samples.shape) - - noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise - return noisy_samples - - def __len__(self): - return self.config.num_train_timesteps diff --git a/spaces/Jeff2323/ai-comic-factory/src/components/ui/accordion.tsx b/spaces/Jeff2323/ai-comic-factory/src/components/ui/accordion.tsx deleted file mode 100644 index 937620af27e5d8ef577f0baca229a9b753ebd017..0000000000000000000000000000000000000000 --- a/spaces/Jeff2323/ai-comic-factory/src/components/ui/accordion.tsx +++ /dev/null @@ -1,60 +0,0 @@ -"use client" - -import * as React from "react" -import * as AccordionPrimitive from "@radix-ui/react-accordion" -import { ChevronDown } from "lucide-react" - -import { cn } from "@/lib/utils" - -const Accordion = AccordionPrimitive.Root - -const AccordionItem = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AccordionItem.displayName = "AccordionItem" - -const AccordionTrigger = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - - svg]:rotate-180", - className - )} - {...props} - > - {children} - - - -)) -AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName - -const AccordionContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - -
    {children}
    -
    -)) -AccordionContent.displayName = AccordionPrimitive.Content.displayName - -export { Accordion, AccordionItem, AccordionTrigger, AccordionContent } diff --git a/spaces/Jikiwi/sovits-models/app.py b/spaces/Jikiwi/sovits-models/app.py deleted file mode 100644 index 2d6c236a564fa5283fa0385477be02d87c8aee35..0000000000000000000000000000000000000000 --- a/spaces/Jikiwi/sovits-models/app.py +++ /dev/null @@ -1,141 +0,0 @@ -import os -import io -import gradio as gr -import librosa -import numpy as np -import utils -from inference.infer_tool import Svc -import logging -import soundfile -import asyncio -import argparse -import edge_tts -import gradio.processing_utils as gr_processing_utils -logging.getLogger('numba').setLevel(logging.WARNING) -logging.getLogger('markdown_it').setLevel(logging.WARNING) -logging.getLogger('urllib3').setLevel(logging.WARNING) -logging.getLogger('matplotlib').setLevel(logging.WARNING) - -limitation = os.getenv("SYSTEM") == "spaces" # limit audio length in huggingface spaces - -audio_postprocess_ori = gr.Audio.postprocess - -def audio_postprocess(self, y): - data = audio_postprocess_ori(self, y) - if data is None: - return None - return gr_processing_utils.encode_url_or_file_to_base64(data["name"]) - - -gr.Audio.postprocess = audio_postprocess -def create_vc_fn(model, sid): - def vc_fn(input_audio, vc_transform, auto_f0, tts_text, tts_voice, tts_mode): - if tts_mode: - if len(tts_text) > 100 and limitation: - return "Text is too long", None - if tts_text is None or tts_voice is None: - return "You need to enter text and select a voice", None - asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3")) - audio, sr = librosa.load("tts.mp3", sr=16000, mono=True) - raw_path = io.BytesIO() - soundfile.write(raw_path, audio, 16000, format="wav") - raw_path.seek(0) - out_audio, out_sr = model.infer(sid, vc_transform, raw_path, - auto_predict_f0=auto_f0, - ) - return "Success", (44100, out_audio.cpu().numpy()) - if input_audio is None: - return "You need to upload an audio", None - sampling_rate, audio = input_audio - duration = audio.shape[0] / sampling_rate - if duration > 20 and limitation: - return "Please upload an audio file that is less than 20 seconds. If you need to generate a longer audio file, please use Colab.", None - audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32) - if len(audio.shape) > 1: - audio = librosa.to_mono(audio.transpose(1, 0)) - if sampling_rate != 16000: - audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000) - raw_path = io.BytesIO() - soundfile.write(raw_path, audio, 16000, format="wav") - raw_path.seek(0) - out_audio, out_sr = model.infer(sid, vc_transform, raw_path, - auto_predict_f0=auto_f0, - ) - return "Success", (44100, out_audio.cpu().numpy()) - return vc_fn - -def change_to_tts_mode(tts_mode): - if tts_mode: - return gr.Audio.update(visible=False), gr.Textbox.update(visible=True), gr.Dropdown.update(visible=True), gr.Checkbox.update(value=True) - else: - return gr.Audio.update(visible=True), gr.Textbox.update(visible=False), gr.Dropdown.update(visible=False), gr.Checkbox.update(value=False) - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('--device', type=str, default='cpu') - parser.add_argument('--api', action="store_true", default=False) - parser.add_argument("--share", action="store_true", default=False, help="share gradio app") - args = parser.parse_args() - hubert_model = utils.get_hubert_model().to(args.device) - models = [] - others = { - "rudolf": "https://huggingface.co/spaces/sayashi/sovits-rudolf", - "teio": "https://huggingface.co/spaces/sayashi/sovits-teio", - "goldship": "https://huggingface.co/spaces/sayashi/sovits-goldship", - "tannhauser": "https://huggingface.co/spaces/sayashi/sovits-tannhauser" - } - voices = [] - tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices()) - for r in tts_voice_list: - voices.append(f"{r['ShortName']}-{r['Gender']}") - for f in os.listdir("models"): - name = f - model = Svc(fr"models/{f}/{f}.pth", f"models/{f}/config.json", device=args.device) - cover = f"models/{f}/cover.png" if os.path.exists(f"models/{f}/cover.png") else None - models.append((name, cover, create_vc_fn(model, name))) - with gr.Blocks() as app: - gr.Markdown( - "#
    Sovits Models\n" - "##
    The input audio should be clean and pure voice without background music.\n" - "![visitor badge](https://visitor-badge.glitch.me/badge?page_id=sayashi.Sovits-Umamusume)\n\n" - "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1wfsBbMzmtLflOJeqc5ZnJiLY7L239hJW?usp=share_link)\n\n" - "[![Duplicate this Space](https://huggingface.co/datasets/huggingface/badges/raw/main/duplicate-this-space-sm-dark.svg)](https://huggingface.co/spaces/sayashi/sovits-models?duplicate=true)\n\n" - "[![Original Repo](https://badgen.net/badge/icon/github?icon=github&label=Original%20Repo)](https://github.com/svc-develop-team/so-vits-svc)" - - ) - with gr.Tabs(): - for (name, cover, vc_fn) in models: - with gr.TabItem(name): - with gr.Row(): - gr.Markdown( - '
    ' - f'' if cover else "" - '
    ' - ) - with gr.Row(): - with gr.Column(): - vc_input = gr.Audio(label="Input audio"+' (less than 20 seconds)' if limitation else '') - vc_transform = gr.Number(label="vc_transform", value=0) - auto_f0 = gr.Checkbox(label="auto_f0", value=False) - tts_mode = gr.Checkbox(label="tts (use edge-tts as input)", value=False) - tts_text = gr.Textbox(visible=False, label="TTS text (100 words limitation)" if limitation else "TTS text") - tts_voice = gr.Dropdown(choices=voices, visible=False) - vc_submit = gr.Button("Generate", variant="primary") - with gr.Column(): - vc_output1 = gr.Textbox(label="Output Message") - vc_output2 = gr.Audio(label="Output Audio") - vc_submit.click(vc_fn, [vc_input, vc_transform, auto_f0, tts_text, tts_voice, tts_mode], [vc_output1, vc_output2]) - tts_mode.change(change_to_tts_mode, [tts_mode], [vc_input, tts_text, tts_voice, auto_f0]) - for category, link in others.items(): - with gr.TabItem(category): - gr.Markdown( - f''' -
    -

    Click to Go

    - - -
    - ''' - ) - app.queue(concurrency_count=1, api_open=args.api).launch(share=args.share) diff --git a/spaces/Joabutt/test/README.md b/spaces/Joabutt/test/README.md deleted file mode 100644 index b33c8bec65236e4de343b87653e91cd1fcbcb859..0000000000000000000000000000000000000000 --- a/spaces/Joabutt/test/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Test -emoji: 📊 -colorFrom: purple -colorTo: yellow -sdk: static -pinned: false -license: wtfpl ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/JohnTan38/GODEL-v1_1-large-seq2seq/app.py b/spaces/JohnTan38/GODEL-v1_1-large-seq2seq/app.py deleted file mode 100644 index d0ed4c5dfcc47d4e739adb591c2585980591755c..0000000000000000000000000000000000000000 --- a/spaces/JohnTan38/GODEL-v1_1-large-seq2seq/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/microsoft/GODEL-v1_1-large-seq2seq").launch() \ No newline at end of file diff --git a/spaces/Kevin676/AutoGPT/benchmark/__init__.py b/spaces/Kevin676/AutoGPT/benchmark/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/KyanChen/RSPrompter/mmdet/utils/__init__.py b/spaces/KyanChen/RSPrompter/mmdet/utils/__init__.py deleted file mode 100644 index 1a8643425631e9e090afa8e0f8dcca3a63e29476..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmdet/utils/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .collect_env import collect_env -from .compat_config import compat_cfg -from .dist_utils import (all_reduce_dict, allreduce_grads, reduce_mean, - sync_random_seed) -from .logger import get_caller_name, log_img_scale -from .memory import AvoidCUDAOOM, AvoidOOM -from .misc import (find_latest_checkpoint, get_test_pipeline_cfg, - update_data_root) -from .replace_cfg_vals import replace_cfg_vals -from .setup_env import (register_all_modules, setup_cache_size_limit_of_dynamo, - setup_multi_processes) -from .split_batch import split_batch -from .typing_utils import (ConfigType, InstanceList, MultiConfig, - OptConfigType, OptInstanceList, OptMultiConfig, - OptPixelList, PixelList, RangeType) - -__all__ = [ - 'collect_env', 'find_latest_checkpoint', 'update_data_root', - 'setup_multi_processes', 'get_caller_name', 'log_img_scale', 'compat_cfg', - 'split_batch', 'register_all_modules', 'replace_cfg_vals', 'AvoidOOM', - 'AvoidCUDAOOM', 'all_reduce_dict', 'allreduce_grads', 'reduce_mean', - 'sync_random_seed', 'ConfigType', 'InstanceList', 'MultiConfig', - 'OptConfigType', 'OptInstanceList', 'OptMultiConfig', 'OptPixelList', - 'PixelList', 'RangeType', 'get_test_pipeline_cfg', - 'setup_cache_size_limit_of_dynamo' -] diff --git a/spaces/KyanChen/RSPrompter/mmpl/utils/boxam_utils.py b/spaces/KyanChen/RSPrompter/mmpl/utils/boxam_utils.py deleted file mode 100644 index 4a46f21c1b5b40e7bc106ae7a15281816ae3efcc..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmpl/utils/boxam_utils.py +++ /dev/null @@ -1,512 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import bisect -import copy -import warnings -from pathlib import Path -from typing import Callable, List, Optional, Tuple, Union - -import cv2 -import numpy as np -import torch -import torch.nn as nn -import torchvision -from mmcv.transforms import Compose -from mmdet.evaluation import get_classes -from mmdet.utils import ConfigType -from mmengine.config import Config -from mmengine.registry import init_default_scope -from mmengine.runner import load_checkpoint -from mmengine.structures import InstanceData -from torch import Tensor - -from mmyolo.registry import MODELS - -try: - from pytorch_grad_cam import (AblationCAM, AblationLayer, - ActivationsAndGradients) - from pytorch_grad_cam import GradCAM as Base_GradCAM - from pytorch_grad_cam import GradCAMPlusPlus as Base_GradCAMPlusPlus - from pytorch_grad_cam.base_cam import BaseCAM - from pytorch_grad_cam.utils.image import scale_cam_image, show_cam_on_image - from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection -except ImportError: - pass - - -def init_detector( - config: Union[str, Path, Config], - checkpoint: Optional[str] = None, - palette: str = 'coco', - device: str = 'cuda:0', - cfg_options: Optional[dict] = None, -) -> nn.Module: - """Initialize a detector from config file. - - Args: - config (str, :obj:`Path`, or :obj:`mmengine.Config`): Config file path, - :obj:`Path`, or the config object. - checkpoint (str, optional): Checkpoint path. If left as None, the model - will not load any weights. - palette (str): Color palette used for visualization. If palette - is stored in checkpoint, use checkpoint's palette first, otherwise - use externally passed palette. Currently, supports 'coco', 'voc', - 'citys' and 'random'. Defaults to coco. - device (str): The device where the anchors will be put on. - Defaults to cuda:0. - cfg_options (dict, optional): Options to override some settings in - the used config. - - Returns: - nn.Module: The constructed detector. - """ - if isinstance(config, (str, Path)): - config = Config.fromfile(config) - elif not isinstance(config, Config): - raise TypeError('config must be a filename or Config object, ' - f'but got {type(config)}') - if cfg_options is not None: - config.merge_from_dict(cfg_options) - elif 'init_cfg' in config.model.backbone: - config.model.backbone.init_cfg = None - - # only change this - # grad based method requires train_cfg - # config.model.train_cfg = None - init_default_scope(config.get('default_scope', 'mmyolo')) - - model = MODELS.build(config.model) - if checkpoint is not None: - checkpoint = load_checkpoint(model, checkpoint, map_location='cpu') - # Weights converted from elsewhere may not have meta fields. - checkpoint_meta = checkpoint.get('meta', {}) - # save the dataset_meta in the model for convenience - if 'dataset_meta' in checkpoint_meta: - # mmdet 3.x, all keys should be lowercase - model.dataset_meta = { - k.lower(): v - for k, v in checkpoint_meta['dataset_meta'].items() - } - elif 'CLASSES' in checkpoint_meta: - # < mmdet 3.x - classes = checkpoint_meta['CLASSES'] - model.dataset_meta = {'classes': classes, 'palette': palette} - else: - warnings.simplefilter('once') - warnings.warn( - 'dataset_meta or class names are not saved in the ' - 'checkpoint\'s meta data, use COCO classes by default.') - model.dataset_meta = { - 'classes': get_classes('coco'), - 'palette': palette - } - - model.cfg = config # save the config in the model for convenience - model.to(device) - model.eval() - return model - - -def reshape_transform(feats: Union[Tensor, List[Tensor]], - max_shape: Tuple[int, int] = (20, 20), - is_need_grad: bool = False): - """Reshape and aggregate feature maps when the input is a multi-layer - feature map. - - Takes these tensors with different sizes, resizes them to a common shape, - and concatenates them. - """ - if len(max_shape) == 1: - max_shape = max_shape * 2 - - if isinstance(feats, torch.Tensor): - feats = [feats] - else: - if is_need_grad: - raise NotImplementedError('The `grad_base` method does not ' - 'support output multi-activation layers') - - max_h = max([im.shape[-2] for im in feats]) - max_w = max([im.shape[-1] for im in feats]) - if -1 in max_shape: - max_shape = (max_h, max_w) - else: - max_shape = (min(max_h, max_shape[0]), min(max_w, max_shape[1])) - - activations = [] - for feat in feats: - activations.append( - torch.nn.functional.interpolate( - torch.abs(feat), max_shape, mode='bilinear')) - - activations = torch.cat(activations, axis=1) - return activations - - -class BoxAMDetectorWrapper(nn.Module): - """Wrap the mmdet model class to facilitate handling of non-tensor - situations during inference.""" - - def __init__(self, - cfg: ConfigType, - checkpoint: str, - score_thr: float, - device: str = 'cuda:0'): - super().__init__() - self.cfg = cfg - self.device = device - self.score_thr = score_thr - self.checkpoint = checkpoint - self.detector = init_detector(self.cfg, self.checkpoint, device=device) - - pipeline_cfg = copy.deepcopy(self.cfg.test_dataloader.dataset.pipeline) - pipeline_cfg[0].type = 'mmdet.LoadImageFromNDArray' - - new_test_pipeline = [] - for pipeline in pipeline_cfg: - if not pipeline['type'].endswith('LoadAnnotations'): - new_test_pipeline.append(pipeline) - self.test_pipeline = Compose(new_test_pipeline) - - self.is_need_loss = False - self.input_data = None - self.image = None - - def need_loss(self, is_need_loss: bool): - """Grad-based methods require loss.""" - self.is_need_loss = is_need_loss - - def set_input_data(self, - image: np.ndarray, - pred_instances: Optional[InstanceData] = None): - """Set the input data to be used in the next step.""" - self.image = image - - if self.is_need_loss: - assert pred_instances is not None - pred_instances = pred_instances.numpy() - data = dict( - img=self.image, - img_id=0, - gt_bboxes=pred_instances.bboxes, - gt_bboxes_labels=pred_instances.labels) - data = self.test_pipeline(data) - else: - data = dict(img=self.image, img_id=0) - data = self.test_pipeline(data) - data['inputs'] = [data['inputs']] - data['data_samples'] = [data['data_samples']] - self.input_data = data - - def __call__(self, *args, **kwargs): - assert self.input_data is not None - if self.is_need_loss: - # Maybe this is a direction that can be optimized - # self.detector.init_weights() - - self.detector.bbox_head.head_module.training = True - if hasattr(self.detector.bbox_head, 'featmap_sizes'): - # Prevent the model algorithm error when calculating loss - self.detector.bbox_head.featmap_sizes = None - - data_ = {} - data_['inputs'] = [self.input_data['inputs']] - data_['data_samples'] = [self.input_data['data_samples']] - data = self.detector.data_preprocessor(data_, training=False) - loss = self.detector._run_forward(data, mode='loss') - - if hasattr(self.detector.bbox_head, 'featmap_sizes'): - self.detector.bbox_head.featmap_sizes = None - - return [loss] - else: - self.detector.bbox_head.head_module.training = False - with torch.no_grad(): - results = self.detector.test_step(self.input_data) - return results - - -class BoxAMDetectorVisualizer: - """Box AM visualization class.""" - - def __init__(self, - method_class, - model: nn.Module, - target_layers: List, - reshape_transform: Optional[Callable] = None, - is_need_grad: bool = False, - extra_params: Optional[dict] = None): - self.target_layers = target_layers - self.reshape_transform = reshape_transform - self.is_need_grad = is_need_grad - - if method_class.__name__ == 'AblationCAM': - batch_size = extra_params.get('batch_size', 1) - ratio_channels_to_ablate = extra_params.get( - 'ratio_channels_to_ablate', 1.) - self.cam = AblationCAM( - model, - target_layers, - use_cuda=True if 'cuda' in model.device else False, - reshape_transform=reshape_transform, - batch_size=batch_size, - ablation_layer=extra_params['ablation_layer'], - ratio_channels_to_ablate=ratio_channels_to_ablate) - else: - self.cam = method_class( - model, - target_layers, - use_cuda=True if 'cuda' in model.device else False, - reshape_transform=reshape_transform, - ) - if self.is_need_grad: - self.cam.activations_and_grads.release() - - self.classes = model.detector.dataset_meta['classes'] - self.COLORS = np.random.uniform(0, 255, size=(len(self.classes), 3)) - - def switch_activations_and_grads(self, model) -> None: - """In the grad-based method, we need to switch - ``ActivationsAndGradients`` layer, otherwise an error will occur.""" - self.cam.model = model - - if self.is_need_grad is True: - self.cam.activations_and_grads = ActivationsAndGradients( - model, self.target_layers, self.reshape_transform) - self.is_need_grad = False - else: - self.cam.activations_and_grads.release() - self.is_need_grad = True - - def __call__(self, img, targets, aug_smooth=False, eigen_smooth=False): - img = torch.from_numpy(img)[None].permute(0, 3, 1, 2) - return self.cam(img, targets, aug_smooth, eigen_smooth)[0, :] - - def show_am(self, - image: np.ndarray, - pred_instance: InstanceData, - grayscale_am: np.ndarray, - with_norm_in_bboxes: bool = False): - """Normalize the AM to be in the range [0, 1] inside every bounding - boxes, and zero outside of the bounding boxes.""" - - boxes = pred_instance.bboxes - labels = pred_instance.labels - - if with_norm_in_bboxes is True: - boxes = boxes.astype(np.int32) - renormalized_am = np.zeros(grayscale_am.shape, dtype=np.float32) - images = [] - for x1, y1, x2, y2 in boxes: - img = renormalized_am * 0 - img[y1:y2, x1:x2] = scale_cam_image( - [grayscale_am[y1:y2, x1:x2].copy()])[0] - images.append(img) - - renormalized_am = np.max(np.float32(images), axis=0) - renormalized_am = scale_cam_image([renormalized_am])[0] - else: - renormalized_am = grayscale_am - - am_image_renormalized = show_cam_on_image( - image / 255, renormalized_am, use_rgb=False) - - image_with_bounding_boxes = self._draw_boxes( - boxes, labels, am_image_renormalized, pred_instance.get('scores')) - return image_with_bounding_boxes - - def _draw_boxes(self, - boxes: List, - labels: List, - image: np.ndarray, - scores: Optional[List] = None): - """draw boxes on image.""" - for i, box in enumerate(boxes): - label = labels[i] - color = self.COLORS[label] - cv2.rectangle(image, (int(box[0]), int(box[1])), - (int(box[2]), int(box[3])), color, 2) - if scores is not None: - score = scores[i] - text = str(self.classes[label]) + ': ' + str( - round(score * 100, 1)) - else: - text = self.classes[label] - - cv2.putText( - image, - text, (int(box[0]), int(box[1] - 5)), - cv2.FONT_HERSHEY_SIMPLEX, - 0.5, - color, - 1, - lineType=cv2.LINE_AA) - return image - - -class DetAblationLayer(AblationLayer): - """Det AblationLayer.""" - - def __init__(self): - super().__init__() - self.activations = None - - def set_next_batch(self, input_batch_index, activations, - num_channels_to_ablate): - """Extract the next batch member from activations, and repeat it - num_channels_to_ablate times.""" - if isinstance(activations, torch.Tensor): - return super().set_next_batch(input_batch_index, activations, - num_channels_to_ablate) - - self.activations = [] - for activation in activations: - activation = activation[ - input_batch_index, :, :, :].clone().unsqueeze(0) - self.activations.append( - activation.repeat(num_channels_to_ablate, 1, 1, 1)) - - def __call__(self, x): - """Go over the activation indices to be ablated, stored in - self.indices.""" - result = self.activations - - if isinstance(result, torch.Tensor): - return super().__call__(x) - - channel_cumsum = np.cumsum([r.shape[1] for r in result]) - num_channels_to_ablate = result[0].size(0) # batch - for i in range(num_channels_to_ablate): - pyramid_layer = bisect.bisect_right(channel_cumsum, - self.indices[i]) - if pyramid_layer > 0: - index_in_pyramid_layer = self.indices[i] - channel_cumsum[ - pyramid_layer - 1] - else: - index_in_pyramid_layer = self.indices[i] - result[pyramid_layer][i, index_in_pyramid_layer, :, :] = -1000 - return result - - -class DetBoxScoreTarget: - """Det Score calculation class. - - In the case of the grad-free method, the calculation method is that - for every original detected bounding box specified in "bboxes", - assign a score on how the current bounding boxes match it, - - 1. In Bbox IoU - 2. In the classification score. - 3. In Mask IoU if ``segms`` exist. - - If there is not a large enough overlap, or the category changed, - assign a score of 0. The total score is the sum of all the box scores. - - In the case of the grad-based method, the calculation method is - the sum of losses after excluding a specific key. - """ - - def __init__(self, - pred_instance: InstanceData, - match_iou_thr: float = 0.5, - device: str = 'cuda:0', - ignore_loss_params: Optional[List] = None): - self.focal_bboxes = pred_instance.bboxes - self.focal_labels = pred_instance.labels - self.match_iou_thr = match_iou_thr - self.device = device - self.ignore_loss_params = ignore_loss_params - if ignore_loss_params is not None: - assert isinstance(self.ignore_loss_params, list) - - def __call__(self, results): - output = torch.tensor([0.], device=self.device) - - if 'loss_cls' in results: - # grad-based method - # results is dict - for loss_key, loss_value in results.items(): - if 'loss' not in loss_key or \ - loss_key in self.ignore_loss_params: - continue - if isinstance(loss_value, list): - output += sum(loss_value) - else: - output += loss_value - return output - else: - # grad-free method - # results is DetDataSample - pred_instances = results.pred_instances - if len(pred_instances) == 0: - return output - - pred_bboxes = pred_instances.bboxes - pred_scores = pred_instances.scores - pred_labels = pred_instances.labels - - for focal_box, focal_label in zip(self.focal_bboxes, - self.focal_labels): - ious = torchvision.ops.box_iou(focal_box[None], - pred_bboxes[..., :4]) - index = ious.argmax() - if ious[0, index] > self.match_iou_thr and pred_labels[ - index] == focal_label: - # TODO: Adaptive adjustment of weights based on algorithms - score = ious[0, index] + pred_scores[index] - output = output + score - return output - - -class SpatialBaseCAM(BaseCAM): - """CAM that maintains spatial information. - - Gradients are often averaged over the spatial dimension in CAM - visualization for classification, but this is unreasonable in detection - tasks. There is no need to average the gradients in the detection task. - """ - - def get_cam_image(self, - input_tensor: torch.Tensor, - target_layer: torch.nn.Module, - targets: List[torch.nn.Module], - activations: torch.Tensor, - grads: torch.Tensor, - eigen_smooth: bool = False) -> np.ndarray: - - weights = self.get_cam_weights(input_tensor, target_layer, targets, - activations, grads) - weighted_activations = weights * activations - if eigen_smooth: - cam = get_2d_projection(weighted_activations) - else: - cam = weighted_activations.sum(axis=1) - return cam - - -class GradCAM(SpatialBaseCAM, Base_GradCAM): - """Gradients are no longer averaged over the spatial dimension.""" - - def get_cam_weights(self, input_tensor, target_layer, target_category, - activations, grads): - return grads - - -class GradCAMPlusPlus(SpatialBaseCAM, Base_GradCAMPlusPlus): - """Gradients are no longer averaged over the spatial dimension.""" - - def get_cam_weights(self, input_tensor, target_layers, target_category, - activations, grads): - grads_power_2 = grads**2 - grads_power_3 = grads_power_2 * grads - # Equation 19 in https://arxiv.org/abs/1710.11063 - sum_activations = np.sum(activations, axis=(2, 3)) - eps = 0.000001 - aij = grads_power_2 / ( - 2 * grads_power_2 + - sum_activations[:, :, None, None] * grads_power_3 + eps) - # Now bring back the ReLU from eq.7 in the paper, - # And zero out aijs where the activations are 0 - aij = np.where(grads != 0, aij, 0) - - weights = np.maximum(grads, 0) * aij - return weights diff --git a/spaces/LanguageBind/LanguageBind/t_cls/zeroshot_cls.py b/spaces/LanguageBind/LanguageBind/t_cls/zeroshot_cls.py deleted file mode 100644 index aac2222a79c47293bf409aa38f1d88f10ed4b024..0000000000000000000000000000000000000000 --- a/spaces/LanguageBind/LanguageBind/t_cls/zeroshot_cls.py +++ /dev/null @@ -1,47 +0,0 @@ - -import json -import logging -import os -from training.distributed import is_master -from .zero_shot import zero_shot_eval - -try: - import wandb -except ImportError: - wandb = None - - - -def evaluate_t_cls(model, data, epoch, args, tb_writer=None): - metrics = {} - if not is_master(args): - return metrics - model.eval() - - zero_shot_metrics = zero_shot_eval(model, data, epoch, args) - metrics.update(zero_shot_metrics) - - if not metrics: - return metrics - - logging.info( - f"Eval Epoch: {epoch} " - + "\t".join([f"{k}: {round(v, 4):.4f}" for k, v in metrics.items()]) - ) - - if args.save_logs: - for name, val in metrics.items(): - if tb_writer is not None: - tb_writer.add_scalar(f"val/t_cls/{args.val_t_cls_data[0].lower()}/{name}", val, epoch) - args.t_cls_output_dir = os.path.join(args.log_base_path, f't_cls/{args.val_t_cls_data[0].lower()}') - os.makedirs(args.t_cls_output_dir, exist_ok=True) - with open(os.path.join(args.t_cls_output_dir, "results.jsonl"), "a+") as f: - f.write(json.dumps(metrics)) - f.write("\n") - - if args.wandb: - assert wandb is not None, 'Please install wandb.' - for name, val in metrics.items(): - wandb.log({f"val/{name}": val, 'epoch': epoch}) - - return metrics diff --git a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_pack/modules.py b/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_pack/modules.py deleted file mode 100644 index 1dda5f2364b71d7c5e98a22fbae92e5528babbe5..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Aesthetic_RVC_Inference_HF/lib/infer/infer_pack/modules.py +++ /dev/null @@ -1,519 +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 - -from lib.infer.infer_pack import commons -from lib.infer.infer_pack.commons import init_weights, get_padding -from lib.infer.infer_pack.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.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 - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -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.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/LaynzKunz/RVC-Inference-webui-grado-colab-huggingafce/rmvpe.py b/spaces/LaynzKunz/RVC-Inference-webui-grado-colab-huggingafce/rmvpe.py deleted file mode 100644 index 3ad346141340e03bdbaa20121e1ed435bb3da57a..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/RVC-Inference-webui-grado-colab-huggingafce/rmvpe.py +++ /dev/null @@ -1,432 +0,0 @@ -import sys, torch, numpy as np, traceback, pdb -import torch.nn as nn -from time import time as ttime -import torch.nn.functional as F - - -class BiGRU(nn.Module): - def __init__(self, input_features, hidden_features, num_layers): - super(BiGRU, self).__init__() - self.gru = nn.GRU( - input_features, - hidden_features, - num_layers=num_layers, - batch_first=True, - bidirectional=True, - ) - - def forward(self, x): - return self.gru(x)[0] - - -class ConvBlockRes(nn.Module): - def __init__(self, in_channels, out_channels, momentum=0.01): - super(ConvBlockRes, self).__init__() - self.conv = nn.Sequential( - nn.Conv2d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=(1, 1), - padding=(1, 1), - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - nn.Conv2d( - in_channels=out_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=(1, 1), - padding=(1, 1), - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - ) - if in_channels != out_channels: - self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1)) - self.is_shortcut = True - else: - self.is_shortcut = False - - def forward(self, x): - if self.is_shortcut: - return self.conv(x) + self.shortcut(x) - else: - return self.conv(x) + x - - -class Encoder(nn.Module): - def __init__( - self, - in_channels, - in_size, - n_encoders, - kernel_size, - n_blocks, - out_channels=16, - momentum=0.01, - ): - super(Encoder, self).__init__() - self.n_encoders = n_encoders - self.bn = nn.BatchNorm2d(in_channels, momentum=momentum) - self.layers = nn.ModuleList() - self.latent_channels = [] - for i in range(self.n_encoders): - self.layers.append( - ResEncoderBlock( - in_channels, out_channels, kernel_size, n_blocks, momentum=momentum - ) - ) - self.latent_channels.append([out_channels, in_size]) - in_channels = out_channels - out_channels *= 2 - in_size //= 2 - self.out_size = in_size - self.out_channel = out_channels - - def forward(self, x): - concat_tensors = [] - x = self.bn(x) - for i in range(self.n_encoders): - _, x = self.layers[i](x) - concat_tensors.append(_) - return x, concat_tensors - - -class ResEncoderBlock(nn.Module): - def __init__( - self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01 - ): - super(ResEncoderBlock, self).__init__() - self.n_blocks = n_blocks - self.conv = nn.ModuleList() - self.conv.append(ConvBlockRes(in_channels, out_channels, momentum)) - for i in range(n_blocks - 1): - self.conv.append(ConvBlockRes(out_channels, out_channels, momentum)) - self.kernel_size = kernel_size - if self.kernel_size is not None: - self.pool = nn.AvgPool2d(kernel_size=kernel_size) - - def forward(self, x): - for i in range(self.n_blocks): - x = self.conv[i](x) - if self.kernel_size is not None: - return x, self.pool(x) - else: - return x - - -class Intermediate(nn.Module): # - def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01): - super(Intermediate, self).__init__() - self.n_inters = n_inters - self.layers = nn.ModuleList() - self.layers.append( - ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum) - ) - for i in range(self.n_inters - 1): - self.layers.append( - ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum) - ) - - def forward(self, x): - for i in range(self.n_inters): - x = self.layers[i](x) - return x - - -class ResDecoderBlock(nn.Module): - def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01): - super(ResDecoderBlock, self).__init__() - out_padding = (0, 1) if stride == (1, 2) else (1, 1) - self.n_blocks = n_blocks - self.conv1 = nn.Sequential( - nn.ConvTranspose2d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=(3, 3), - stride=stride, - padding=(1, 1), - output_padding=out_padding, - bias=False, - ), - nn.BatchNorm2d(out_channels, momentum=momentum), - nn.ReLU(), - ) - self.conv2 = nn.ModuleList() - self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum)) - for i in range(n_blocks - 1): - self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum)) - - def forward(self, x, concat_tensor): - x = self.conv1(x) - x = torch.cat((x, concat_tensor), dim=1) - for i in range(self.n_blocks): - x = self.conv2[i](x) - return x - - -class Decoder(nn.Module): - def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01): - super(Decoder, self).__init__() - self.layers = nn.ModuleList() - self.n_decoders = n_decoders - for i in range(self.n_decoders): - out_channels = in_channels // 2 - self.layers.append( - ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum) - ) - in_channels = out_channels - - def forward(self, x, concat_tensors): - for i in range(self.n_decoders): - x = self.layers[i](x, concat_tensors[-1 - i]) - return x - - -class DeepUnet(nn.Module): - def __init__( - self, - kernel_size, - n_blocks, - en_de_layers=5, - inter_layers=4, - in_channels=1, - en_out_channels=16, - ): - super(DeepUnet, self).__init__() - self.encoder = Encoder( - in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels - ) - self.intermediate = Intermediate( - self.encoder.out_channel // 2, - self.encoder.out_channel, - inter_layers, - n_blocks, - ) - self.decoder = Decoder( - self.encoder.out_channel, en_de_layers, kernel_size, n_blocks - ) - - def forward(self, x): - x, concat_tensors = self.encoder(x) - x = self.intermediate(x) - x = self.decoder(x, concat_tensors) - return x - - -class E2E(nn.Module): - def __init__( - self, - n_blocks, - n_gru, - kernel_size, - en_de_layers=5, - inter_layers=4, - in_channels=1, - en_out_channels=16, - ): - super(E2E, self).__init__() - self.unet = DeepUnet( - kernel_size, - n_blocks, - en_de_layers, - inter_layers, - in_channels, - en_out_channels, - ) - self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1)) - if n_gru: - self.fc = nn.Sequential( - BiGRU(3 * 128, 256, n_gru), - nn.Linear(512, 360), - nn.Dropout(0.25), - nn.Sigmoid(), - ) - else: - self.fc = nn.Sequential( - nn.Linear(3 * N_MELS, N_CLASS), nn.Dropout(0.25), nn.Sigmoid() - ) - - def forward(self, mel): - mel = mel.transpose(-1, -2).unsqueeze(1) - x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2) - x = self.fc(x) - return x - - -from librosa.filters import mel - - -class MelSpectrogram(torch.nn.Module): - def __init__( - self, - is_half, - n_mel_channels, - sampling_rate, - win_length, - hop_length, - n_fft=None, - mel_fmin=0, - mel_fmax=None, - clamp=1e-5, - ): - super().__init__() - n_fft = win_length if n_fft is None else n_fft - self.hann_window = {} - mel_basis = mel( - sr=sampling_rate, - n_fft=n_fft, - n_mels=n_mel_channels, - fmin=mel_fmin, - fmax=mel_fmax, - htk=True, - ) - mel_basis = torch.from_numpy(mel_basis).float() - self.register_buffer("mel_basis", mel_basis) - self.n_fft = win_length if n_fft is None else n_fft - self.hop_length = hop_length - self.win_length = win_length - self.sampling_rate = sampling_rate - self.n_mel_channels = n_mel_channels - self.clamp = clamp - self.is_half = is_half - - def forward(self, audio, keyshift=0, speed=1, center=True): - factor = 2 ** (keyshift / 12) - n_fft_new = int(np.round(self.n_fft * factor)) - win_length_new = int(np.round(self.win_length * factor)) - hop_length_new = int(np.round(self.hop_length * speed)) - keyshift_key = str(keyshift) + "_" + str(audio.device) - if keyshift_key not in self.hann_window: - self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to( - audio.device - ) - fft = torch.stft( - audio, - n_fft=n_fft_new, - hop_length=hop_length_new, - win_length=win_length_new, - window=self.hann_window[keyshift_key], - center=center, - return_complex=True, - ) - magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2)) - if keyshift != 0: - size = self.n_fft // 2 + 1 - resize = magnitude.size(1) - if resize < size: - magnitude = F.pad(magnitude, (0, 0, 0, size - resize)) - magnitude = magnitude[:, :size, :] * self.win_length / win_length_new - mel_output = torch.matmul(self.mel_basis, magnitude) - if self.is_half == True: - mel_output = mel_output.half() - log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp)) - return log_mel_spec - - -class RMVPE: - def __init__(self, model_path, is_half, device=None): - self.resample_kernel = {} - model = E2E(4, 1, (2, 2)) - ckpt = torch.load(model_path, map_location="cpu") - model.load_state_dict(ckpt) - model.eval() - if is_half == True: - model = model.half() - self.model = model - self.resample_kernel = {} - self.is_half = is_half - if device is None: - device = "cuda" if torch.cuda.is_available() else "cpu" - self.device = device - self.mel_extractor = MelSpectrogram( - is_half, 128, 16000, 1024, 160, None, 30, 8000 - ).to(device) - self.model = self.model.to(device) - cents_mapping = 20 * np.arange(360) + 1997.3794084376191 - self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368 - - def mel2hidden(self, mel): - with torch.no_grad(): - n_frames = mel.shape[-1] - mel = F.pad( - mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect" - ) - hidden = self.model(mel) - return hidden[:, :n_frames] - - def decode(self, hidden, thred=0.03): - cents_pred = self.to_local_average_cents(hidden, thred=thred) - f0 = 10 * (2 ** (cents_pred / 1200)) - f0[f0 == 10] = 0 - # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred]) - return f0 - - def infer_from_audio(self, audio, thred=0.03): - audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0) - # torch.cuda.synchronize() - # t0=ttime() - mel = self.mel_extractor(audio, center=True) - # torch.cuda.synchronize() - # t1=ttime() - hidden = self.mel2hidden(mel) - # torch.cuda.synchronize() - # t2=ttime() - hidden = hidden.squeeze(0).cpu().numpy() - if self.is_half == True: - hidden = hidden.astype("float32") - f0 = self.decode(hidden, thred=thred) - # torch.cuda.synchronize() - # t3=ttime() - # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0)) - return f0 - - def to_local_average_cents(self, salience, thred=0.05): - # t0 = ttime() - center = np.argmax(salience, axis=1) # 帧长#index - salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368 - # t1 = ttime() - center += 4 - todo_salience = [] - todo_cents_mapping = [] - starts = center - 4 - ends = center + 5 - for idx in range(salience.shape[0]): - todo_salience.append(salience[:, starts[idx] : ends[idx]][idx]) - todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]]) - # t2 = ttime() - todo_salience = np.array(todo_salience) # 帧长,9 - todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9 - product_sum = np.sum(todo_salience * todo_cents_mapping, 1) - weight_sum = np.sum(todo_salience, 1) # 帧长 - devided = product_sum / weight_sum # 帧长 - # t3 = ttime() - maxx = np.max(salience, axis=1) # 帧长 - devided[maxx <= thred] = 0 - # t4 = ttime() - # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3)) - return devided - - -# if __name__ == '__main__': -# audio, sampling_rate = sf.read("卢本伟语录~1.wav") -# if len(audio.shape) > 1: -# audio = librosa.to_mono(audio.transpose(1, 0)) -# audio_bak = audio.copy() -# if sampling_rate != 16000: -# audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000) -# model_path = "/bili-coeus/jupyter/jupyterhub-liujing04/vits_ch/test-RMVPE/weights/rmvpe_llc_half.pt" -# thred = 0.03 # 0.01 -# device = 'cuda' if torch.cuda.is_available() else 'cpu' -# rmvpe = RMVPE(model_path,is_half=False, device=device) -# t0=ttime() -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# f0 = rmvpe.infer_from_audio(audio, thred=thred) -# t1=ttime() -# print(f0.shape,t1-t0) diff --git a/spaces/LecJackS/wolfram-alpha-query/README.md b/spaces/LecJackS/wolfram-alpha-query/README.md deleted file mode 100644 index 36afbbfb45ed3b8b1fed48f16a5285dac3487567..0000000000000000000000000000000000000000 --- a/spaces/LecJackS/wolfram-alpha-query/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Wolfram Alpha Query -colorFrom: indigo -colorTo: red -sdk: static -pinned: true -license: openrail -tags: -- tool ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/LinkSoul/AutoAgents/Dockerfile b/spaces/LinkSoul/AutoAgents/Dockerfile deleted file mode 100644 index 29edb36ca82a5080e2d2314c3d1a8a787993394d..0000000000000000000000000000000000000000 --- a/spaces/LinkSoul/AutoAgents/Dockerfile +++ /dev/null @@ -1,31 +0,0 @@ -FROM tiangolo/uwsgi-nginx:python3.10 - -ENV LISTEN_PORT 7860 -ENV USE_HTML_ROOT /app/autoagents/frontend/app - -EXPOSE 7860 - -RUN chown -R 1000 /app /etc/nginx /usr/local/lib/python3.10/site-packages /usr/local/bin /var/log /var/run /etc/supervisor/conf.d /run /tmp /etc/uwsgi /var/cache /entrypoint.sh - -# Set up a new user named "user" with user ID 1000 -RUN useradd -m -u 1000 user - -# Switch to the "user" user -USER user - -# Set home to the user's home directory -ENV HOME=/home/user \ - PATH=/home/user/.local/bin:$PATH - -# Install Python dependencies and install autoagents -RUN git clone https://github.com/LinkSoul-AI/AutoAgents autoagents && \ - cd autoagents && \ - pip install -r requirements.txt --user && \ - python setup.py install && \ - pip cache purge && \ - cp docker/prestart.sh /app/prestart.sh && \ - cp docker/entrypoint.sh /entrypoint.sh && \ - chmod +x /entrypoint.sh && \ - sed -i 's/nodaemon=true/nodaemon=true\nuser=user/g' /etc/supervisor/conf.d/supervisord.conf && \ - sed -i 's/nginx/user/g' /etc/uwsgi/uwsgi.ini && \ - sed -i 's/nginx;/user;/g' /etc/nginx/nginx.conf \ No newline at end of file diff --git a/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/inference/interact/fbrs/model/modeling/hrnet_ocr.py b/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/inference/interact/fbrs/model/modeling/hrnet_ocr.py deleted file mode 100644 index e5f8eff39c5a7e10ed712f96929644b325a90660..0000000000000000000000000000000000000000 --- a/spaces/Make-A-Protagonist/Make-A-Protagonist-inference/Make-A-Protagonist/experts/XMem/inference/interact/fbrs/model/modeling/hrnet_ocr.py +++ /dev/null @@ -1,399 +0,0 @@ -import os -import numpy as np -import torch -import torch.nn as nn -import torch._utils -import torch.nn.functional as F -from .ocr import SpatialOCR_Module, SpatialGather_Module -from .resnetv1b import BasicBlockV1b, BottleneckV1b - -relu_inplace = True - - -class HighResolutionModule(nn.Module): - def __init__(self, num_branches, blocks, num_blocks, num_inchannels, - num_channels, fuse_method,multi_scale_output=True, - norm_layer=nn.BatchNorm2d, align_corners=True): - super(HighResolutionModule, self).__init__() - self._check_branches(num_branches, num_blocks, num_inchannels, num_channels) - - self.num_inchannels = num_inchannels - self.fuse_method = fuse_method - self.num_branches = num_branches - self.norm_layer = norm_layer - self.align_corners = align_corners - - self.multi_scale_output = multi_scale_output - - self.branches = self._make_branches( - num_branches, blocks, num_blocks, num_channels) - self.fuse_layers = self._make_fuse_layers() - self.relu = nn.ReLU(inplace=relu_inplace) - - def _check_branches(self, num_branches, num_blocks, num_inchannels, num_channels): - if num_branches != len(num_blocks): - error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format( - num_branches, len(num_blocks)) - raise ValueError(error_msg) - - if num_branches != len(num_channels): - error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format( - num_branches, len(num_channels)) - raise ValueError(error_msg) - - if num_branches != len(num_inchannels): - error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format( - num_branches, len(num_inchannels)) - raise ValueError(error_msg) - - def _make_one_branch(self, branch_index, block, num_blocks, num_channels, - stride=1): - downsample = None - if stride != 1 or \ - self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion: - downsample = nn.Sequential( - nn.Conv2d(self.num_inchannels[branch_index], - num_channels[branch_index] * block.expansion, - kernel_size=1, stride=stride, bias=False), - self.norm_layer(num_channels[branch_index] * block.expansion), - ) - - layers = [] - layers.append(block(self.num_inchannels[branch_index], - num_channels[branch_index], stride, - downsample=downsample, norm_layer=self.norm_layer)) - self.num_inchannels[branch_index] = \ - num_channels[branch_index] * block.expansion - for i in range(1, num_blocks[branch_index]): - layers.append(block(self.num_inchannels[branch_index], - num_channels[branch_index], - norm_layer=self.norm_layer)) - - return nn.Sequential(*layers) - - def _make_branches(self, num_branches, block, num_blocks, num_channels): - branches = [] - - for i in range(num_branches): - branches.append( - self._make_one_branch(i, block, num_blocks, num_channels)) - - return nn.ModuleList(branches) - - def _make_fuse_layers(self): - if self.num_branches == 1: - return None - - num_branches = self.num_branches - num_inchannels = self.num_inchannels - fuse_layers = [] - for i in range(num_branches if self.multi_scale_output else 1): - fuse_layer = [] - for j in range(num_branches): - if j > i: - fuse_layer.append(nn.Sequential( - nn.Conv2d(in_channels=num_inchannels[j], - out_channels=num_inchannels[i], - kernel_size=1, - bias=False), - self.norm_layer(num_inchannels[i]))) - elif j == i: - fuse_layer.append(None) - else: - conv3x3s = [] - for k in range(i - j): - if k == i - j - 1: - num_outchannels_conv3x3 = num_inchannels[i] - conv3x3s.append(nn.Sequential( - nn.Conv2d(num_inchannels[j], - num_outchannels_conv3x3, - kernel_size=3, stride=2, padding=1, bias=False), - self.norm_layer(num_outchannels_conv3x3))) - else: - num_outchannels_conv3x3 = num_inchannels[j] - conv3x3s.append(nn.Sequential( - nn.Conv2d(num_inchannels[j], - num_outchannels_conv3x3, - kernel_size=3, stride=2, padding=1, bias=False), - self.norm_layer(num_outchannels_conv3x3), - nn.ReLU(inplace=relu_inplace))) - fuse_layer.append(nn.Sequential(*conv3x3s)) - fuse_layers.append(nn.ModuleList(fuse_layer)) - - return nn.ModuleList(fuse_layers) - - def get_num_inchannels(self): - return self.num_inchannels - - def forward(self, x): - if self.num_branches == 1: - return [self.branches[0](x[0])] - - for i in range(self.num_branches): - x[i] = self.branches[i](x[i]) - - x_fuse = [] - for i in range(len(self.fuse_layers)): - y = x[0] if i == 0 else self.fuse_layers[i][0](x[0]) - for j in range(1, self.num_branches): - if i == j: - y = y + x[j] - elif j > i: - width_output = x[i].shape[-1] - height_output = x[i].shape[-2] - y = y + F.interpolate( - self.fuse_layers[i][j](x[j]), - size=[height_output, width_output], - mode='bilinear', align_corners=self.align_corners) - else: - y = y + self.fuse_layers[i][j](x[j]) - x_fuse.append(self.relu(y)) - - return x_fuse - - -class HighResolutionNet(nn.Module): - def __init__(self, width, num_classes, ocr_width=256, small=False, - norm_layer=nn.BatchNorm2d, align_corners=True): - super(HighResolutionNet, self).__init__() - self.norm_layer = norm_layer - self.width = width - self.ocr_width = ocr_width - self.align_corners = align_corners - - self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False) - self.bn1 = norm_layer(64) - self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1, bias=False) - self.bn2 = norm_layer(64) - self.relu = nn.ReLU(inplace=relu_inplace) - - num_blocks = 2 if small else 4 - - stage1_num_channels = 64 - self.layer1 = self._make_layer(BottleneckV1b, 64, stage1_num_channels, blocks=num_blocks) - stage1_out_channel = BottleneckV1b.expansion * stage1_num_channels - - self.stage2_num_branches = 2 - num_channels = [width, 2 * width] - num_inchannels = [ - num_channels[i] * BasicBlockV1b.expansion for i in range(len(num_channels))] - self.transition1 = self._make_transition_layer( - [stage1_out_channel], num_inchannels) - self.stage2, pre_stage_channels = self._make_stage( - BasicBlockV1b, num_inchannels=num_inchannels, num_modules=1, num_branches=self.stage2_num_branches, - num_blocks=2 * [num_blocks], num_channels=num_channels) - - self.stage3_num_branches = 3 - num_channels = [width, 2 * width, 4 * width] - num_inchannels = [ - num_channels[i] * BasicBlockV1b.expansion for i in range(len(num_channels))] - self.transition2 = self._make_transition_layer( - pre_stage_channels, num_inchannels) - self.stage3, pre_stage_channels = self._make_stage( - BasicBlockV1b, num_inchannels=num_inchannels, - num_modules=3 if small else 4, num_branches=self.stage3_num_branches, - num_blocks=3 * [num_blocks], num_channels=num_channels) - - self.stage4_num_branches = 4 - num_channels = [width, 2 * width, 4 * width, 8 * width] - num_inchannels = [ - num_channels[i] * BasicBlockV1b.expansion for i in range(len(num_channels))] - self.transition3 = self._make_transition_layer( - pre_stage_channels, num_inchannels) - self.stage4, pre_stage_channels = self._make_stage( - BasicBlockV1b, num_inchannels=num_inchannels, num_modules=2 if small else 3, - num_branches=self.stage4_num_branches, - num_blocks=4 * [num_blocks], num_channels=num_channels) - - last_inp_channels = np.int32(np.sum(pre_stage_channels)) - ocr_mid_channels = 2 * ocr_width - ocr_key_channels = ocr_width - - self.conv3x3_ocr = nn.Sequential( - nn.Conv2d(last_inp_channels, ocr_mid_channels, - kernel_size=3, stride=1, padding=1), - norm_layer(ocr_mid_channels), - nn.ReLU(inplace=relu_inplace), - ) - self.ocr_gather_head = SpatialGather_Module(num_classes) - - self.ocr_distri_head = SpatialOCR_Module(in_channels=ocr_mid_channels, - key_channels=ocr_key_channels, - out_channels=ocr_mid_channels, - scale=1, - dropout=0.05, - norm_layer=norm_layer, - align_corners=align_corners) - self.cls_head = nn.Conv2d( - ocr_mid_channels, num_classes, kernel_size=1, stride=1, padding=0, bias=True) - - self.aux_head = nn.Sequential( - nn.Conv2d(last_inp_channels, last_inp_channels, - kernel_size=1, stride=1, padding=0), - norm_layer(last_inp_channels), - nn.ReLU(inplace=relu_inplace), - nn.Conv2d(last_inp_channels, num_classes, - kernel_size=1, stride=1, padding=0, bias=True) - ) - - def _make_transition_layer( - self, num_channels_pre_layer, num_channels_cur_layer): - num_branches_cur = len(num_channels_cur_layer) - num_branches_pre = len(num_channels_pre_layer) - - transition_layers = [] - for i in range(num_branches_cur): - if i < num_branches_pre: - if num_channels_cur_layer[i] != num_channels_pre_layer[i]: - transition_layers.append(nn.Sequential( - nn.Conv2d(num_channels_pre_layer[i], - num_channels_cur_layer[i], - kernel_size=3, - stride=1, - padding=1, - bias=False), - self.norm_layer(num_channels_cur_layer[i]), - nn.ReLU(inplace=relu_inplace))) - else: - transition_layers.append(None) - else: - conv3x3s = [] - for j in range(i + 1 - num_branches_pre): - inchannels = num_channels_pre_layer[-1] - outchannels = num_channels_cur_layer[i] \ - if j == i - num_branches_pre else inchannels - conv3x3s.append(nn.Sequential( - nn.Conv2d(inchannels, outchannels, - kernel_size=3, stride=2, padding=1, bias=False), - self.norm_layer(outchannels), - nn.ReLU(inplace=relu_inplace))) - transition_layers.append(nn.Sequential(*conv3x3s)) - - return nn.ModuleList(transition_layers) - - def _make_layer(self, block, inplanes, planes, blocks, stride=1): - downsample = None - if stride != 1 or inplanes != planes * block.expansion: - downsample = nn.Sequential( - nn.Conv2d(inplanes, planes * block.expansion, - kernel_size=1, stride=stride, bias=False), - self.norm_layer(planes * block.expansion), - ) - - layers = [] - layers.append(block(inplanes, planes, stride, - downsample=downsample, norm_layer=self.norm_layer)) - inplanes = planes * block.expansion - for i in range(1, blocks): - layers.append(block(inplanes, planes, norm_layer=self.norm_layer)) - - return nn.Sequential(*layers) - - def _make_stage(self, block, num_inchannels, - num_modules, num_branches, num_blocks, num_channels, - fuse_method='SUM', - multi_scale_output=True): - modules = [] - for i in range(num_modules): - # multi_scale_output is only used last module - if not multi_scale_output and i == num_modules - 1: - reset_multi_scale_output = False - else: - reset_multi_scale_output = True - modules.append( - HighResolutionModule(num_branches, - block, - num_blocks, - num_inchannels, - num_channels, - fuse_method, - reset_multi_scale_output, - norm_layer=self.norm_layer, - align_corners=self.align_corners) - ) - num_inchannels = modules[-1].get_num_inchannels() - - return nn.Sequential(*modules), num_inchannels - - def forward(self, x): - feats = self.compute_hrnet_feats(x) - out_aux = self.aux_head(feats) - feats = self.conv3x3_ocr(feats) - - context = self.ocr_gather_head(feats, out_aux) - feats = self.ocr_distri_head(feats, context) - out = self.cls_head(feats) - - return [out, out_aux] - - def compute_hrnet_feats(self, x): - x = self.conv1(x) - x = self.bn1(x) - x = self.relu(x) - x = self.conv2(x) - x = self.bn2(x) - x = self.relu(x) - x = self.layer1(x) - - x_list = [] - for i in range(self.stage2_num_branches): - if self.transition1[i] is not None: - x_list.append(self.transition1[i](x)) - else: - x_list.append(x) - y_list = self.stage2(x_list) - - x_list = [] - for i in range(self.stage3_num_branches): - if self.transition2[i] is not None: - if i < self.stage2_num_branches: - x_list.append(self.transition2[i](y_list[i])) - else: - x_list.append(self.transition2[i](y_list[-1])) - else: - x_list.append(y_list[i]) - y_list = self.stage3(x_list) - - x_list = [] - for i in range(self.stage4_num_branches): - if self.transition3[i] is not None: - if i < self.stage3_num_branches: - x_list.append(self.transition3[i](y_list[i])) - else: - x_list.append(self.transition3[i](y_list[-1])) - else: - x_list.append(y_list[i]) - x = self.stage4(x_list) - - # Upsampling - x0_h, x0_w = x[0].size(2), x[0].size(3) - x1 = F.interpolate(x[1], size=(x0_h, x0_w), - mode='bilinear', align_corners=self.align_corners) - x2 = F.interpolate(x[2], size=(x0_h, x0_w), - mode='bilinear', align_corners=self.align_corners) - x3 = F.interpolate(x[3], size=(x0_h, x0_w), - mode='bilinear', align_corners=self.align_corners) - - return torch.cat([x[0], x1, x2, x3], 1) - - def load_pretrained_weights(self, pretrained_path=''): - model_dict = self.state_dict() - - if not os.path.exists(pretrained_path): - print(f'\nFile "{pretrained_path}" does not exist.') - print('You need to specify the correct path to the pre-trained weights.\n' - 'You can download the weights for HRNet from the repository:\n' - 'https://github.com/HRNet/HRNet-Image-Classification') - exit(1) - pretrained_dict = torch.load(pretrained_path, map_location={'cuda:0': 'cpu'}) - pretrained_dict = {k.replace('last_layer', 'aux_head').replace('model.', ''): v for k, v in - pretrained_dict.items()} - - print('model_dict-pretrained_dict:', sorted(list(set(model_dict) - set(pretrained_dict)))) - print('pretrained_dict-model_dict:', sorted(list(set(pretrained_dict) - set(model_dict)))) - - pretrained_dict = {k: v for k, v in pretrained_dict.items() - if k in model_dict.keys()} - - model_dict.update(pretrained_dict) - self.load_state_dict(model_dict) diff --git a/spaces/Manjushri/AudioGen-CPU/README.md b/spaces/Manjushri/AudioGen-CPU/README.md deleted file mode 100644 index 42da8cc4f4798a134d05350b324791f2a23e1855..0000000000000000000000000000000000000000 --- a/spaces/Manjushri/AudioGen-CPU/README.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: AudioGen -python_version: '3.9' -tags: -- audio generation -- language models -- LLMs -app_file: app.py -emoji: 🔊 -colorFrom: white -colorTo: blue -sdk: gradio -sdk_version: 3.34.0 -pinned: false -license: cc-by-nc-4.0 -duplicated_from: cocktailpeanut/AudioGen ---- diff --git a/spaces/Marshalls/testmtd/shelltest.sh b/spaces/Marshalls/testmtd/shelltest.sh deleted file mode 100644 index 0e0be8a554a937e8a3d40fc2f8c5bede2a4a880b..0000000000000000000000000000000000000000 --- a/spaces/Marshalls/testmtd/shelltest.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -echo $(nproc) diff --git a/spaces/MathysL/AutoGPT4/autogpt/commands/improve_code.py b/spaces/MathysL/AutoGPT4/autogpt/commands/improve_code.py deleted file mode 100644 index e3440d8b7c6ee8cb62d73df48623ab757c973c59..0000000000000000000000000000000000000000 --- a/spaces/MathysL/AutoGPT4/autogpt/commands/improve_code.py +++ /dev/null @@ -1,29 +0,0 @@ -from __future__ import annotations - -import json - -from autogpt.llm_utils import call_ai_function - - -def improve_code(suggestions: list[str], code: str) -> str: - """ - A function that takes in code and suggestions and returns a response from create - chat completion api call. - - Parameters: - suggestions (List): A list of suggestions around what needs to be improved. - code (str): Code to be improved. - Returns: - A result string from create chat completion. Improved code in response. - """ - - function_string = ( - "def generate_improved_code(suggestions: List[str], code: str) -> str:" - ) - args = [json.dumps(suggestions), code] - description_string = ( - "Improves the provided code based on the suggestions" - " provided, making no other changes." - ) - - return call_ai_function(function_string, args, description_string) diff --git a/spaces/Matthew1917/text_generator/README.md b/spaces/Matthew1917/text_generator/README.md deleted file mode 100644 index 636220b1fea5f640cc0bbefe06241c65b3e55290..0000000000000000000000000000000000000000 --- a/spaces/Matthew1917/text_generator/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Text Generator -emoji: 🐠 -colorFrom: purple -colorTo: gray -sdk: gradio -sdk_version: 3.11.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/Mountchicken/MAERec-Gradio/mmocr/datasets/preparers/packers/textrecog_packer.py b/spaces/Mountchicken/MAERec-Gradio/mmocr/datasets/preparers/packers/textrecog_packer.py deleted file mode 100644 index 6af70064aa7303d494c6d51121ece8c6e4cd06da..0000000000000000000000000000000000000000 --- a/spaces/Mountchicken/MAERec-Gradio/mmocr/datasets/preparers/packers/textrecog_packer.py +++ /dev/null @@ -1,175 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import os.path as osp -from typing import Dict, List, Tuple - -import mmcv -from mmengine import mkdir_or_exist - -from mmocr.registry import DATA_PACKERS -from mmocr.utils import bbox2poly, crop_img, poly2bbox, warp_img -from .base import BasePacker - - -@DATA_PACKERS.register_module() -class TextRecogPacker(BasePacker): - """Text recogntion packer. It is used to pack the parsed annotation info - to: - - .. code-block:: python - - { - "metainfo": - { - "dataset_type": "TextRecogDataset", - "task_name": "textrecog", - }, - "data_list": - [ - { - "img_path": "textrecog_imgs/train/test_img.jpg", - "instances": - [ - { - "text": "GRAND" - } - ] - } - ] - } - """ - - def pack_instance(self, sample: Tuple) -> Dict: - """Pack the text info to a recognition instance. - - Args: - samples (Tuple): A tuple of (img_name, text). - split (str): The split of the instance. - - Returns: - Dict: The packed instance. - """ - - img_name, text = sample - img_name = osp.relpath(img_name, self.data_root) - packed_instance = dict(instances=[dict(text=text)], img_path=img_name) - - return packed_instance - - def add_meta(self, sample: List) -> Dict: - """Add meta information to the sample. - - Args: - sample (List): A list of samples of the dataset. - - Returns: - Dict: A dict contains the meta information and samples. - """ - meta = { - 'metainfo': { - 'dataset_type': 'TextRecogDataset', - 'task_name': 'textrecog' - }, - 'data_list': sample - } - return meta - - -@DATA_PACKERS.register_module() -class TextRecogCropPacker(TextRecogPacker): - """Text recognition packer with image cropper. It is used to pack the - parsed annotation info and crop out the word images from the full-size - ones. - - Args: - crop_with_warp (bool): Whether to crop the text from the original - image using opencv warpPerspective. - jitter (bool): (Applicable when crop_with_warp=True) - Whether to jitter the box. - jitter_ratio_x (float): (Applicable when crop_with_warp=True) - Horizontal jitter ratio relative to the height. - jitter_ratio_y (float): (Applicable when crop_with_warp=True) - Vertical jitter ratio relative to the height. - long_edge_pad_ratio (float): (Applicable when crop_with_warp=False) - The ratio of padding the long edge of the cropped image. - Defaults to 0.1. - short_edge_pad_ratio (float): (Applicable when crop_with_warp=False) - The ratio of padding the short edge of the cropped image. - Defaults to 0.05. - """ - - def __init__(self, - crop_with_warp: bool = False, - jitter: bool = False, - jitter_ratio_x: float = 0.0, - jitter_ratio_y: float = 0.0, - long_edge_pad_ratio: float = 0.0, - short_edge_pad_ratio: float = 0.0, - **kwargs): - super().__init__(**kwargs) - self.crop_with_warp = crop_with_warp - self.jitter = jitter - self.jrx = jitter_ratio_x - self.jry = jitter_ratio_y - self.lepr = long_edge_pad_ratio - self.sepr = short_edge_pad_ratio - # Crop converter crops the images of textdet to patches - self.cropped_img_dir = 'textrecog_imgs' - self.crop_save_path = osp.join(self.data_root, self.cropped_img_dir) - mkdir_or_exist(self.crop_save_path) - mkdir_or_exist(osp.join(self.crop_save_path, self.split)) - - def pack_instance(self, sample: Tuple) -> List: - """Crop patches from image. - - Args: - samples (Tuple): A tuple of (img_name, text). - - Return: - List: The list of cropped patches. - """ - - def get_box(instance: Dict) -> List: - if 'box' in instance: - return bbox2poly(instance['box']).tolist() - if 'poly' in instance: - return bbox2poly(poly2bbox(instance['poly'])).tolist() - - def get_poly(instance: Dict) -> List: - if 'poly' in instance: - return instance['poly'] - if 'box' in instance: - return bbox2poly(instance['box']).tolist() - - data_list = [] - img_path, instances = sample - img = mmcv.imread(img_path) - for i, instance in enumerate(instances): - if instance['ignore']: - continue - if self.crop_with_warp: - poly = get_poly(instance) - patch = warp_img(img, poly, self.jitter, self.jrx, self.jry) - else: - box = get_box(instance) - patch = crop_img(img, box, self.lepr, self.sepr) - if patch.shape[0] == 0 or patch.shape[1] == 0: - continue - text = instance['text'] - patch_name = osp.splitext( - osp.basename(img_path))[0] + f'_{i}' + osp.splitext( - osp.basename(img_path))[1] - dst_path = osp.join(self.crop_save_path, self.split, patch_name) - mmcv.imwrite(patch, dst_path) - rec_instance = dict( - instances=[dict(text=text)], - img_path=osp.join(self.cropped_img_dir, self.split, - patch_name)) - data_list.append(rec_instance) - - return data_list - - def add_meta(self, sample: List) -> Dict: - # Since the TextRecogCropConverter packs all of the patches in a single - # image into a list, we need to flatten the list. - sample = [item for sublist in sample for item in sublist] - return super().add_meta(sample) diff --git a/spaces/MrBodean/VoiceClone/utils/logmmse.py b/spaces/MrBodean/VoiceClone/utils/logmmse.py deleted file mode 100644 index 58cc4502fa5ba0670678c3edaf5ba1587b8b58ea..0000000000000000000000000000000000000000 --- a/spaces/MrBodean/VoiceClone/utils/logmmse.py +++ /dev/null @@ -1,247 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2015 braindead -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# -# -# This code was extracted from the logmmse package (https://pypi.org/project/logmmse/) and I -# simply modified the interface to meet my needs. - - -import numpy as np -import math -from scipy.special import expn -from collections import namedtuple - -NoiseProfile = namedtuple("NoiseProfile", "sampling_rate window_size len1 len2 win n_fft noise_mu2") - - -def profile_noise(noise, sampling_rate, window_size=0): - """ - Creates a profile of the noise in a given waveform. - - :param noise: a waveform containing noise ONLY, as a numpy array of floats or ints. - :param sampling_rate: the sampling rate of the audio - :param window_size: the size of the window the logmmse algorithm operates on. A default value - will be picked if left as 0. - :return: a NoiseProfile object - """ - noise, dtype = to_float(noise) - noise += np.finfo(np.float64).eps - - if window_size == 0: - window_size = int(math.floor(0.02 * sampling_rate)) - - if window_size % 2 == 1: - window_size = window_size + 1 - - perc = 50 - len1 = int(math.floor(window_size * perc / 100)) - len2 = int(window_size - len1) - - win = np.hanning(window_size) - win = win * len2 / np.sum(win) - n_fft = 2 * window_size - - noise_mean = np.zeros(n_fft) - n_frames = len(noise) // window_size - for j in range(0, window_size * n_frames, window_size): - noise_mean += np.absolute(np.fft.fft(win * noise[j:j + window_size], n_fft, axis=0)) - noise_mu2 = (noise_mean / n_frames) ** 2 - - return NoiseProfile(sampling_rate, window_size, len1, len2, win, n_fft, noise_mu2) - - -def denoise(wav, noise_profile: NoiseProfile, eta=0.15): - """ - Cleans the noise from a speech waveform given a noise profile. The waveform must have the - same sampling rate as the one used to create the noise profile. - - :param wav: a speech waveform as a numpy array of floats or ints. - :param noise_profile: a NoiseProfile object that was created from a similar (or a segment of - the same) waveform. - :param eta: voice threshold for noise update. While the voice activation detection value is - below this threshold, the noise profile will be continuously updated throughout the audio. - Set to 0 to disable updating the noise profile. - :return: the clean wav as a numpy array of floats or ints of the same length. - """ - wav, dtype = to_float(wav) - wav += np.finfo(np.float64).eps - p = noise_profile - - nframes = int(math.floor(len(wav) / p.len2) - math.floor(p.window_size / p.len2)) - x_final = np.zeros(nframes * p.len2) - - aa = 0.98 - mu = 0.98 - ksi_min = 10 ** (-25 / 10) - - x_old = np.zeros(p.len1) - xk_prev = np.zeros(p.len1) - noise_mu2 = p.noise_mu2 - for k in range(0, nframes * p.len2, p.len2): - insign = p.win * wav[k:k + p.window_size] - - spec = np.fft.fft(insign, p.n_fft, axis=0) - sig = np.absolute(spec) - sig2 = sig ** 2 - - gammak = np.minimum(sig2 / noise_mu2, 40) - - if xk_prev.all() == 0: - ksi = aa + (1 - aa) * np.maximum(gammak - 1, 0) - else: - ksi = aa * xk_prev / noise_mu2 + (1 - aa) * np.maximum(gammak - 1, 0) - ksi = np.maximum(ksi_min, ksi) - - log_sigma_k = gammak * ksi/(1 + ksi) - np.log(1 + ksi) - vad_decision = np.sum(log_sigma_k) / p.window_size - if vad_decision < eta: - noise_mu2 = mu * noise_mu2 + (1 - mu) * sig2 - - a = ksi / (1 + ksi) - vk = a * gammak - ei_vk = 0.5 * expn(1, np.maximum(vk, 1e-8)) - hw = a * np.exp(ei_vk) - sig = sig * hw - xk_prev = sig ** 2 - xi_w = np.fft.ifft(hw * spec, p.n_fft, axis=0) - xi_w = np.real(xi_w) - - x_final[k:k + p.len2] = x_old + xi_w[0:p.len1] - x_old = xi_w[p.len1:p.window_size] - - output = from_float(x_final, dtype) - output = np.pad(output, (0, len(wav) - len(output)), mode="constant") - return output - - -## Alternative VAD algorithm to webrctvad. It has the advantage of not requiring to install that -## darn package and it also works for any sampling rate. Maybe I'll eventually use it instead of -## webrctvad -# def vad(wav, sampling_rate, eta=0.15, window_size=0): -# """ -# TODO: fix doc -# Creates a profile of the noise in a given waveform. -# -# :param wav: a waveform containing noise ONLY, as a numpy array of floats or ints. -# :param sampling_rate: the sampling rate of the audio -# :param window_size: the size of the window the logmmse algorithm operates on. A default value -# will be picked if left as 0. -# :param eta: voice threshold for noise update. While the voice activation detection value is -# below this threshold, the noise profile will be continuously updated throughout the audio. -# Set to 0 to disable updating the noise profile. -# """ -# wav, dtype = to_float(wav) -# wav += np.finfo(np.float64).eps -# -# if window_size == 0: -# window_size = int(math.floor(0.02 * sampling_rate)) -# -# if window_size % 2 == 1: -# window_size = window_size + 1 -# -# perc = 50 -# len1 = int(math.floor(window_size * perc / 100)) -# len2 = int(window_size - len1) -# -# win = np.hanning(window_size) -# win = win * len2 / np.sum(win) -# n_fft = 2 * window_size -# -# wav_mean = np.zeros(n_fft) -# n_frames = len(wav) // window_size -# for j in range(0, window_size * n_frames, window_size): -# wav_mean += np.absolute(np.fft.fft(win * wav[j:j + window_size], n_fft, axis=0)) -# noise_mu2 = (wav_mean / n_frames) ** 2 -# -# wav, dtype = to_float(wav) -# wav += np.finfo(np.float64).eps -# -# nframes = int(math.floor(len(wav) / len2) - math.floor(window_size / len2)) -# vad = np.zeros(nframes * len2, dtype=np.bool) -# -# aa = 0.98 -# mu = 0.98 -# ksi_min = 10 ** (-25 / 10) -# -# xk_prev = np.zeros(len1) -# noise_mu2 = noise_mu2 -# for k in range(0, nframes * len2, len2): -# insign = win * wav[k:k + window_size] -# -# spec = np.fft.fft(insign, n_fft, axis=0) -# sig = np.absolute(spec) -# sig2 = sig ** 2 -# -# gammak = np.minimum(sig2 / noise_mu2, 40) -# -# if xk_prev.all() == 0: -# ksi = aa + (1 - aa) * np.maximum(gammak - 1, 0) -# else: -# ksi = aa * xk_prev / noise_mu2 + (1 - aa) * np.maximum(gammak - 1, 0) -# ksi = np.maximum(ksi_min, ksi) -# -# log_sigma_k = gammak * ksi / (1 + ksi) - np.log(1 + ksi) -# vad_decision = np.sum(log_sigma_k) / window_size -# if vad_decision < eta: -# noise_mu2 = mu * noise_mu2 + (1 - mu) * sig2 -# print(vad_decision) -# -# a = ksi / (1 + ksi) -# vk = a * gammak -# ei_vk = 0.5 * expn(1, np.maximum(vk, 1e-8)) -# hw = a * np.exp(ei_vk) -# sig = sig * hw -# xk_prev = sig ** 2 -# -# vad[k:k + len2] = vad_decision >= eta -# -# vad = np.pad(vad, (0, len(wav) - len(vad)), mode="constant") -# return vad - - -def to_float(_input): - if _input.dtype == np.float64: - return _input, _input.dtype - elif _input.dtype == np.float32: - return _input.astype(np.float64), _input.dtype - elif _input.dtype == np.uint8: - return (_input - 128) / 128., _input.dtype - elif _input.dtype == np.int16: - return _input / 32768., _input.dtype - elif _input.dtype == np.int32: - return _input / 2147483648., _input.dtype - raise ValueError('Unsupported wave file format') - - -def from_float(_input, dtype): - if dtype == np.float64: - return _input, np.float64 - elif dtype == np.float32: - return _input.astype(np.float32) - elif dtype == np.uint8: - return ((_input * 128) + 128).astype(np.uint8) - elif dtype == np.int16: - return (_input * 32768).astype(np.int16) - elif dtype == np.int32: - print(_input) - return (_input * 2147483648).astype(np.int32) - raise ValueError('Unsupported wave file format') diff --git a/spaces/NCTCMumbai/NCTC/models/official/nlp/albert/export_albert_tfhub_test.py b/spaces/NCTCMumbai/NCTC/models/official/nlp/albert/export_albert_tfhub_test.py deleted file mode 100644 index 4973090365b7ce6527ef1e4458e3f334ea1a5d1b..0000000000000000000000000000000000000000 --- a/spaces/NCTCMumbai/NCTC/models/official/nlp/albert/export_albert_tfhub_test.py +++ /dev/null @@ -1,89 +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. -# ============================================================================== -"""Tests official.nlp.albert.export_albert_tfhub.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import os - -import numpy as np - -import tensorflow as tf -import tensorflow_hub as hub - -from official.nlp.albert import configs -from official.nlp.albert import export_albert_tfhub - - -class ExportAlbertTfhubTest(tf.test.TestCase): - - def test_export_albert_tfhub(self): - # Exports a savedmodel for TF-Hub - albert_config = configs.AlbertConfig( - vocab_size=100, - embedding_size=8, - hidden_size=16, - intermediate_size=32, - max_position_embeddings=128, - num_attention_heads=2, - num_hidden_layers=1) - bert_model, encoder = export_albert_tfhub.create_albert_model(albert_config) - model_checkpoint_dir = os.path.join(self.get_temp_dir(), "checkpoint") - checkpoint = tf.train.Checkpoint(model=encoder) - checkpoint.save(os.path.join(model_checkpoint_dir, "test")) - model_checkpoint_path = tf.train.latest_checkpoint(model_checkpoint_dir) - - sp_model_file = os.path.join(self.get_temp_dir(), "sp_tokenizer.model") - with tf.io.gfile.GFile(sp_model_file, "w") as f: - f.write("dummy content") - - hub_destination = os.path.join(self.get_temp_dir(), "hub") - export_albert_tfhub.export_albert_tfhub( - albert_config, - model_checkpoint_path, - hub_destination, - sp_model_file=sp_model_file) - - # Restores a hub KerasLayer. - hub_layer = hub.KerasLayer(hub_destination, trainable=True) - - if hasattr(hub_layer, "resolved_object"): - with tf.io.gfile.GFile( - hub_layer.resolved_object.sp_model_file.asset_path.numpy()) as f: - self.assertEqual("dummy content", f.read()) - # Checks the hub KerasLayer. - for source_weight, hub_weight in zip(bert_model.trainable_weights, - hub_layer.trainable_weights): - self.assertAllClose(source_weight.numpy(), hub_weight.numpy()) - - dummy_ids = np.zeros((2, 10), dtype=np.int32) - hub_outputs = hub_layer([dummy_ids, dummy_ids, dummy_ids]) - source_outputs = bert_model([dummy_ids, dummy_ids, dummy_ids]) - - # The outputs of hub module are "pooled_output" and "sequence_output", - # while the outputs of encoder is in reversed order, i.e., - # "sequence_output" and "pooled_output". - encoder_outputs = reversed(encoder([dummy_ids, dummy_ids, dummy_ids])) - self.assertEqual(hub_outputs[0].shape, (2, 16)) - self.assertEqual(hub_outputs[1].shape, (2, 10, 16)) - for source_output, hub_output, encoder_output in zip( - source_outputs, hub_outputs, encoder_outputs): - self.assertAllClose(source_output.numpy(), hub_output.numpy()) - self.assertAllClose(source_output.numpy(), encoder_output.numpy()) - - -if __name__ == "__main__": - tf.test.main() diff --git a/spaces/NCTCMumbai/NCTC/models/official/vision/image_classification/efficientnet/__init__.py b/spaces/NCTCMumbai/NCTC/models/official/vision/image_classification/efficientnet/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/NoCrypt/pixelization/models/__init__.py b/spaces/NoCrypt/pixelization/models/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/speech_recognition/tasks/__init__.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/speech_recognition/tasks/__init__.py deleted file mode 100644 index 7ac3b8dc69639c92cc129294356e9012745e3fb2..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/examples/speech_recognition/tasks/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -import importlib -import os - - -for file in sorted(os.listdir(os.path.dirname(__file__))): - if file.endswith(".py") and not file.startswith("_"): - task_name = file[: file.find(".py")] - importlib.import_module("examples.speech_recognition.tasks." + task_name) diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/audio/data_cfg.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/audio/data_cfg.py deleted file mode 100644 index 95b403ad9c617afb5656131693c92b9cc3befd3b..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/data/audio/data_cfg.py +++ /dev/null @@ -1,139 +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 pathlib import Path -from typing import Dict, Optional - - -class S2TDataConfig(object): - """Wrapper class for data config YAML""" - - def __init__(self, yaml_path: Path): - try: - import yaml - except ImportError: - print("Please install PyYAML: pip install PyYAML") - self.config = {} - if yaml_path.is_file(): - try: - with open(yaml_path) as f: - self.config = yaml.load(f, Loader=yaml.FullLoader) - except Exception as e: - raise Exception( - f"Failed to load config from {yaml_path.as_posix()}: {e}" - ) - else: - raise FileNotFoundError(f"{yaml_path.as_posix()} not found") - self.root = yaml_path.parent - - def _auto_convert_to_abs_path(self, x): - if isinstance(x, str): - if not Path(x).exists() and (self.root / x).exists(): - return (self.root / x).as_posix() - elif isinstance(x, dict): - return {k: self._auto_convert_to_abs_path(v) for k, v in x.items()} - return x - - @property - def vocab_filename(self): - """fairseq vocabulary file under data root""" - return self.config.get("vocab_filename", "dict.txt") - - @property - def speaker_set_filename(self): - """fairseq vocabulary file under data root""" - return self.config.get("speaker_set_filename", None) - - @property - def shuffle(self) -> bool: - """Shuffle dataset samples before batching""" - return self.config.get("shuffle", False) - - @property - def pre_tokenizer(self) -> Dict: - """Pre-tokenizer to apply before subword tokenization. Returning - a dictionary with `tokenizer` providing the tokenizer name and - the other items providing the tokenizer-specific arguments. - Tokenizers are defined in `fairseq.data.encoders.*`""" - tokenizer = self.config.get("pre_tokenizer", {"tokenizer": None}) - return self._auto_convert_to_abs_path(tokenizer) - - @property - def bpe_tokenizer(self) -> Dict: - """Subword tokenizer to apply after pre-tokenization. Returning - a dictionary with `bpe` providing the tokenizer name and - the other items providing the tokenizer-specific arguments. - Tokenizers are defined in `fairseq.data.encoders.*`""" - tokenizer = self.config.get("bpe_tokenizer", {"bpe": None}) - return self._auto_convert_to_abs_path(tokenizer) - - @property - def prepend_tgt_lang_tag(self) -> bool: - """Prepend target lang ID token as the target BOS (e.g. for to-many - multilingual setting). During inference, this requires `--prefix-size 1` - to force BOS to be lang ID token.""" - return self.config.get("prepend_tgt_lang_tag", False) - - @property - def input_feat_per_channel(self): - """The dimension of input features (per audio channel)""" - return self.config.get("input_feat_per_channel", 80) - - @property - def input_channels(self): - """The number of channels in the input audio""" - return self.config.get("input_channels", 1) - - @property - def sample_rate(self): - return self.config.get("sample_rate", 16_000) - - @property - def sampling_alpha(self): - """Hyper-parameter alpha = 1/T for temperature-based resampling. - (alpha = 1 for no resampling)""" - return self.config.get("sampling_alpha", 1.0) - - @property - def use_audio_input(self): - """Needed by the dataset loader to see if the model requires - raw audio as inputs.""" - return self.config.get("use_audio_input", False) - - @property - def use_sample_rate(self): - """Needed by the dataset loader to see if the model requires - raw audio with specific sample rate as inputs.""" - return self.config.get("use_sample_rate", 16000) - - @property - def audio_root(self): - """Audio paths in the manifest TSV can be relative and this provides - the root path. Set this to empty string when using absolute paths.""" - return self.config.get("audio_root", "") - - def get_feature_transforms(self, split, is_train): - """Split-specific feature transforms. Allowing train set - wildcard `_train`, evaluation set wildcard `_eval` and general - wildcard `*` for matching.""" - from copy import deepcopy - - cfg = deepcopy(self.config) - _cur = cfg.get("transforms", {}) - cur = _cur.get(split) - cur = _cur.get("_train") if cur is None and is_train else cur - cur = _cur.get("_eval") if cur is None and not is_train else cur - cur = _cur.get("*") if cur is None else cur - cfg["transforms"] = cur - return cfg - - @property - def global_cmvn_stats_npz(self) -> Optional[str]: - path = self.config.get("global_cmvn", {}).get("stats_npz_path", None) - return self._auto_convert_to_abs_path(path) - - @property - def vocoder(self) -> Optional[Dict[str, str]]: - return self.config.get("vocoder", None) diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/tasks/masked_lm.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/tasks/masked_lm.py deleted file mode 100644 index 0c08132fb742de3d3d1beea0b8fce979ff408ebb..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/fairseq/tasks/masked_lm.py +++ /dev/null @@ -1,255 +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 -import logging -import os - -from omegaconf import MISSING, II, OmegaConf - -import numpy as np -from fairseq import utils -from fairseq.data import ( - Dictionary, - IdDataset, - MaskTokensDataset, - NestedDictionaryDataset, - NumelDataset, - NumSamplesDataset, - PrependTokenDataset, - RightPadDataset, - SortDataset, - TokenBlockDataset, - data_utils, -) -from fairseq.data.encoders.utils import get_whole_word_mask -from fairseq.data.shorten_dataset import maybe_shorten_dataset -from fairseq.dataclass import FairseqDataclass -from fairseq.tasks import FairseqTask, register_task - -from .language_modeling import SAMPLE_BREAK_MODE_CHOICES, SHORTEN_METHOD_CHOICES - - -logger = logging.getLogger(__name__) - - -@dataclass -class MaskedLMConfig(FairseqDataclass): - data: str = field( - default=MISSING, - metadata={ - "help": "colon separated path to data directories list, \ - will be iterated upon during epochs in round-robin manner" - }, - ) - sample_break_mode: SAMPLE_BREAK_MODE_CHOICES = field( - default="none", - metadata={ - "help": 'If omitted or "none", fills each sample with tokens-per-sample ' - 'tokens. If set to "complete", splits samples only at the end ' - "of sentence, but may include multiple sentences per sample. " - '"complete_doc" is similar but respects doc boundaries. ' - 'If set to "eos", includes only one sentence per sample.' - }, - ) - tokens_per_sample: int = field( - default=1024, - metadata={"help": "max number of tokens per sample for LM dataset"}, - ) - mask_prob: float = field( - default=0.15, - metadata={"help": "probability of replacing a token with mask"}, - ) - leave_unmasked_prob: float = field( - default=0.1, - metadata={"help": "probability that a masked token is unmasked"}, - ) - random_token_prob: float = field( - default=0.1, - metadata={"help": "probability of replacing a token with a random token"}, - ) - freq_weighted_replacement: bool = field( - default=False, - metadata={"help": "sample random replacement words based on word frequencies"}, - ) - mask_whole_words: bool = field( - default=False, - metadata={"help": "mask whole words; you may also want to set --bpe"}, - ) - mask_multiple_length: int = field( - default=1, - metadata={"help": "repeat the mask indices multiple times"}, - ) - mask_stdev: float = field( - default=0.0, - metadata={"help": "stdev of the mask length"}, - ) - shorten_method: SHORTEN_METHOD_CHOICES = field( - default="none", - metadata={ - "help": "if not none, shorten sequences that exceed --tokens-per-sample" - }, - ) - shorten_data_split_list: str = field( - default="", - metadata={ - "help": "comma-separated list of dataset splits to apply shortening to, " - 'e.g., "train,valid" (default: all dataset splits)' - }, - ) - seed: int = II("common.seed") - - -@register_task("masked_lm", dataclass=MaskedLMConfig) -class MaskedLMTask(FairseqTask): - - cfg: MaskedLMConfig - - """Task for training masked language models (e.g., BERT, RoBERTa).""" - - def __init__(self, cfg: MaskedLMConfig, dictionary): - super().__init__(cfg) - self.dictionary = dictionary - - # add mask token - self.mask_idx = dictionary.add_symbol("") - - @classmethod - def setup_task(cls, cfg: MaskedLMConfig, **kwargs): - paths = utils.split_paths(cfg.data) - assert len(paths) > 0 - dictionary = Dictionary.load(os.path.join(paths[0], "dict.txt")) - logger.info("dictionary: {} types".format(len(dictionary))) - return cls(cfg, dictionary) - - def load_dataset(self, split, epoch=1, combine=False, **kwargs): - """Load a given dataset split. - - Args: - split (str): name of the split (e.g., train, valid, test) - """ - paths = utils.split_paths(self.cfg.data) - assert len(paths) > 0 - data_path = paths[(epoch - 1) % len(paths)] - split_path = os.path.join(data_path, split) - - dataset = data_utils.load_indexed_dataset( - split_path, - self.source_dictionary, - combine=combine, - ) - if dataset is None: - raise FileNotFoundError( - "Dataset not found: {} ({})".format(split, split_path) - ) - - dataset = maybe_shorten_dataset( - dataset, - split, - self.cfg.shorten_data_split_list, - self.cfg.shorten_method, - self.cfg.tokens_per_sample, - self.cfg.seed, - ) - - # create continuous blocks of tokens - dataset = TokenBlockDataset( - dataset, - dataset.sizes, - self.cfg.tokens_per_sample - 1, # one less for - pad=self.source_dictionary.pad(), - eos=self.source_dictionary.eos(), - break_mode=self.cfg.sample_break_mode, - ) - logger.info("loaded {} blocks from: {}".format(len(dataset), split_path)) - - # prepend beginning-of-sentence token (, equiv. to [CLS] in BERT) - dataset = PrependTokenDataset(dataset, self.source_dictionary.bos()) - - # create masked input and targets - mask_whole_words = ( - get_whole_word_mask(self.args, self.source_dictionary) - if self.cfg.mask_whole_words - else None - ) - - src_dataset, tgt_dataset = MaskTokensDataset.apply_mask( - dataset, - self.source_dictionary, - pad_idx=self.source_dictionary.pad(), - mask_idx=self.mask_idx, - seed=self.cfg.seed, - mask_prob=self.cfg.mask_prob, - leave_unmasked_prob=self.cfg.leave_unmasked_prob, - random_token_prob=self.cfg.random_token_prob, - freq_weighted_replacement=self.cfg.freq_weighted_replacement, - mask_whole_words=mask_whole_words, - mask_multiple_length=self.cfg.mask_multiple_length, - mask_stdev=self.cfg.mask_stdev, - ) - - with data_utils.numpy_seed(self.cfg.seed): - shuffle = np.random.permutation(len(src_dataset)) - - self.datasets[split] = SortDataset( - NestedDictionaryDataset( - { - "id": IdDataset(), - "net_input": { - "src_tokens": RightPadDataset( - src_dataset, - pad_idx=self.source_dictionary.pad(), - ), - "src_lengths": NumelDataset(src_dataset, reduce=False), - }, - "target": RightPadDataset( - tgt_dataset, - pad_idx=self.source_dictionary.pad(), - ), - "nsentences": NumSamplesDataset(), - "ntokens": NumelDataset(src_dataset, reduce=True), - }, - sizes=[src_dataset.sizes], - ), - sort_order=[ - shuffle, - src_dataset.sizes, - ], - ) - - def build_dataset_for_inference(self, src_tokens, src_lengths, sort=True): - src_dataset = RightPadDataset( - TokenBlockDataset( - src_tokens, - src_lengths, - self.cfg.tokens_per_sample - 1, # one less for - pad=self.source_dictionary.pad(), - eos=self.source_dictionary.eos(), - break_mode="eos", - ), - pad_idx=self.source_dictionary.pad(), - ) - src_dataset = PrependTokenDataset(src_dataset, self.source_dictionary.bos()) - src_dataset = NestedDictionaryDataset( - { - "id": IdDataset(), - "net_input": { - "src_tokens": src_dataset, - "src_lengths": NumelDataset(src_dataset, reduce=False), - }, - }, - sizes=src_lengths, - ) - if sort: - src_dataset = SortDataset(src_dataset, sort_order=[src_lengths]) - return src_dataset - - @property - def source_dictionary(self): - return self.dictionary - - @property - def target_dictionary(self): - return self.dictionary diff --git a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/scripts/split_train_valid_docs.py b/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/scripts/split_train_valid_docs.py deleted file mode 100644 index ff159785284a13b44626b207d84430c592acaf8f..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Generic_Interface/fairseq/scripts/split_train_valid_docs.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env python3 -# 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. -""" -Split a large file into a train and valid set while respecting document -boundaries. Documents should be separated by a single empty line. -""" - -import argparse -import random -import sys - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("input") - parser.add_argument("sample_output", help="train output file") - parser.add_argument("remainder_output", help="valid output file") - parser.add_argument("-k", type=int, help="remainder size") - parser.add_argument( - "--lines", action="store_true", help="split lines instead of docs" - ) - args = parser.parse_args() - - assert args.k is not None - - sample = [] - remainder = [] - num_docs = [0] - - def update_sample(doc): - if len(sample) < args.k: - sample.append(doc.copy()) - else: - i = num_docs[0] - j = random.randrange(i + 1) - if j < args.k: - remainder.append(sample[j]) - sample[j] = doc.copy() - else: - remainder.append(doc.copy()) - num_docs[0] += 1 - doc.clear() - - with open(args.input, "r", encoding="utf-8") as h: - doc = [] - for i, line in enumerate(h): - if line.strip() == "": # empty line indicates new document - update_sample(doc) - else: - doc.append(line) - if args.lines: - update_sample(doc) - if i % 1000000 == 0: - print(i, file=sys.stderr, end="", flush=True) - elif i % 100000 == 0: - print(".", file=sys.stderr, end="", flush=True) - if len(doc) > 0: - update_sample(doc) - print(file=sys.stderr, flush=True) - - assert len(sample) == args.k - - with open(args.sample_output, "w", encoding="utf-8") as out: - first = True - for doc in sample: - if not first and not args.lines: - out.write("\n") - first = False - for line in doc: - out.write(line) - - with open(args.remainder_output, "w", encoding="utf-8") as out: - first = True - for doc in remainder: - if not first and not args.lines: - out.write("\n") - first = False - for line in doc: - out.write(line) - - -if __name__ == "__main__": - main() diff --git a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/scripts/normalize_text.py b/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/scripts/normalize_text.py deleted file mode 100644 index 9d0ffeb27d038a6b82aaf0f6bdf208af565663f6..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Image_Caption/fairseq/examples/wav2vec/unsupervised/scripts/normalize_text.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python3 -# 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 regex -import sys - - -def main(): - filter_r = regex.compile(r"[^\p{L}\p{N}\p{M}\' \-]") - - for line in sys.stdin: - line = line.strip() - line = filter_r.sub(" ", line) - line = " ".join(line.split()) - print(line) - - -if __name__ == "__main__": - main() diff --git a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/CODE_OF_CONDUCT.md b/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/CODE_OF_CONDUCT.md deleted file mode 100644 index a0cbeaab7650bf08267fbdbc9bb54e845c88f392..0000000000000000000000000000000000000000 --- a/spaces/OFA-Sys/OFA-Visual_Grounding/fairseq/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,77 +0,0 @@ -# Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to make participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, 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. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers 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, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies within all project spaces, and it also applies when -an individual is representing the project or its community in public spaces. -Examples of representing a project or community include using an official -project e-mail address, posting via an official social media account, or acting -as an appointed representative at an online or offline event. Representation of -a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at . All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq - diff --git a/spaces/ORI-Muchim/BarKeYaeTTS/export_model.py b/spaces/ORI-Muchim/BarKeYaeTTS/export_model.py deleted file mode 100644 index 98a49835df5a7a2486e76ddf94fbbb4444b52203..0000000000000000000000000000000000000000 --- a/spaces/ORI-Muchim/BarKeYaeTTS/export_model.py +++ /dev/null @@ -1,13 +0,0 @@ -import torch - -if __name__ == '__main__': - model_path = "saved_model/11/model.pth" - output_path = "saved_model/11/model1.pth" - checkpoint_dict = torch.load(model_path, map_location='cpu') - checkpoint_dict_new = {} - for k, v in checkpoint_dict.items(): - if k == "optimizer": - print("remove optimizer") - continue - checkpoint_dict_new[k] = v - torch.save(checkpoint_dict_new, output_path) diff --git a/spaces/Osborn-bh/ChatGLM3-6B-Osborn/composite_demo/tool_registry.py b/spaces/Osborn-bh/ChatGLM3-6B-Osborn/composite_demo/tool_registry.py deleted file mode 100644 index e54564c53bf772c2e49f3e38882bcc7d15eff40f..0000000000000000000000000000000000000000 --- a/spaces/Osborn-bh/ChatGLM3-6B-Osborn/composite_demo/tool_registry.py +++ /dev/null @@ -1,109 +0,0 @@ -from copy import deepcopy -import inspect -from pprint import pformat -import traceback -from types import GenericAlias -from typing import get_origin, Annotated - -_TOOL_HOOKS = {} -_TOOL_DESCRIPTIONS = {} - -def register_tool(func: callable): - tool_name = func.__name__ - tool_description = inspect.getdoc(func).strip() - python_params = inspect.signature(func).parameters - tool_params = [] - for name, param in python_params.items(): - annotation = param.annotation - if annotation is inspect.Parameter.empty: - raise TypeError(f"Parameter `{name}` missing type annotation") - if get_origin(annotation) != Annotated: - raise TypeError(f"Annotation type for `{name}` must be typing.Annotated") - - typ, (description, required) = annotation.__origin__, annotation.__metadata__ - typ: str = str(typ) if isinstance(typ, GenericAlias) else typ.__name__ - if not isinstance(description, str): - raise TypeError(f"Description for `{name}` must be a string") - if not isinstance(required, bool): - raise TypeError(f"Required for `{name}` must be a bool") - - tool_params.append({ - "name": name, - "description": description, - "type": typ, - "required": required - }) - tool_def = { - "name": tool_name, - "description": tool_description, - "params": tool_params - } - - print("[registered tool] " + pformat(tool_def)) - _TOOL_HOOKS[tool_name] = func - _TOOL_DESCRIPTIONS[tool_name] = tool_def - - return func - -def dispatch_tool(tool_name: str, tool_params: dict) -> str: - if tool_name not in _TOOL_HOOKS: - return f"Tool `{tool_name}` not found. Please use a provided tool." - tool_call = _TOOL_HOOKS[tool_name] - try: - ret = tool_call(**tool_params) - except: - ret = traceback.format_exc() - return str(ret) - -def get_tools() -> dict: - return deepcopy(_TOOL_DESCRIPTIONS) - -# Tool Definitions - -@register_tool -def random_number_generator( - seed: Annotated[int, 'The random seed used by the generator', True], - range: Annotated[tuple[int, int], 'The range of the generated numbers', True], -) -> int: - """ - Generates a random number x, s.t. range[0] <= x < range[1] - """ - if not isinstance(seed, int): - raise TypeError("Seed must be an integer") - if not isinstance(range, tuple): - raise TypeError("Range must be a tuple") - if not isinstance(range[0], int) or not isinstance(range[1], int): - raise TypeError("Range must be a tuple of integers") - - import random - return random.Random(seed).randint(*range) - -@register_tool -def get_weather( - city_name: Annotated[str, 'The name of the city to be queried', True], -) -> str: - """ - Get the current weather for `city_name` - """ - - if not isinstance(city_name, str): - raise TypeError("City name must be a string") - - key_selection = { - "current_condition": ["temp_C", "FeelsLikeC", "humidity", "weatherDesc", "observation_time"], - } - import requests - try: - resp = requests.get(f"https://wttr.in/{city_name}?format=j1") - resp.raise_for_status() - resp = resp.json() - ret = {k: {_v: resp[k][0][_v] for _v in v} for k, v in key_selection.items()} - except: - import traceback - ret = "Error encountered while fetching weather data!\n" + traceback.format_exc() - - return str(ret) - -if __name__ == "__main__": - print(dispatch_tool("get_weather", {"city_name": "beijing"})) - print(get_tools()) diff --git a/spaces/Osborn-bh/ChatGLM3-6B-Osborn/tool_using/cli_demo_tool.py b/spaces/Osborn-bh/ChatGLM3-6B-Osborn/tool_using/cli_demo_tool.py deleted file mode 100644 index 4f157e23785e49867f1aa87211d2ba82c5a9f687..0000000000000000000000000000000000000000 --- a/spaces/Osborn-bh/ChatGLM3-6B-Osborn/tool_using/cli_demo_tool.py +++ /dev/null @@ -1,60 +0,0 @@ -import os -import platform -import signal -from transformers import AutoTokenizer, AutoModel -import readline - -tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm3-6b", trust_remote_code=True) -model = AutoModel.from_pretrained("THUDM/chatglm3-6b", trust_remote_code=True).cuda() -# 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量 -# from utils import load_model_on_gpus -# model = load_model_on_gpus("THUDM/chatglm3-6b", num_gpus=2) -model = model.eval() - -os_name = platform.system() -clear_command = 'cls' if os_name == 'Windows' else 'clear' -stop_stream = False - - -def build_prompt(history): - prompt = "欢迎使用 ChatGLM3-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序" - for query, response in history: - prompt += f"\n\n用户:{query}" - prompt += f"\n\nChatGLM3-6B:{response}" - return prompt - - -def signal_handler(signal, frame): - global stop_stream - stop_stream = True - -tools = [{'name': 'track', 'description': '追踪指定股票的实时价格', 'parameters': {'type': 'object', 'properties': {'symbol': {'description': '需要追踪的股票代码'}}, 'required': []}}, {'name': '/text-to-speech', 'description': '将文本转换为语音', 'parameters': {'type': 'object', 'properties': {'text': {'description': '需要转换成语音的文本'}, 'voice': {'description': '要使用的语音类型(男声、女声等)'}, 'speed': {'description': '语音的速度(快、中等、慢等)'}}, 'required': []}}, {'name': '/image_resizer', 'description': '调整图片的大小和尺寸', 'parameters': {'type': 'object', 'properties': {'image_file': {'description': '需要调整大小的图片文件'}, 'width': {'description': '需要调整的宽度值'}, 'height': {'description': '需要调整的高度值'}}, 'required': []}}, {'name': '/foodimg', 'description': '通过给定的食品名称生成该食品的图片', 'parameters': {'type': 'object', 'properties': {'food_name': {'description': '需要生成图片的食品名称'}}, 'required': []}}] -system_item = {"role": "system", - "content": "Answer the following questions as best as you can. You have access to the following tools:", - "tools": tools} - -def main(): - past_key_values, history = None, [system_item] - role = "user" - global stop_stream - print("欢迎使用 ChatGLM3-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序") - while True: - query = input("\n用户:") if role == "user" else input("\n结果:") - if query.strip() == "stop": - break - if query.strip() == "clear": - past_key_values, history = None, [system_item] - role = "user" - os.system(clear_command) - print("欢迎使用 ChatGLM3-6B 模型,输入内容即可进行对话,clear 清空对话历史,stop 终止程序") - continue - print("\nChatGLM:", end="") - response, history = model.chat(tokenizer, query, history=history, role=role) - print(response, end="", flush=True) - print("") - if isinstance(response, dict): - role = "observation" - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/ops/bbox.py b/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/ops/bbox.py deleted file mode 100644 index 0c4d58b6c91f652933974f519acd3403a833e906..0000000000000000000000000000000000000000 --- a/spaces/PAIR/Text2Video-Zero/annotator/uniformer/mmcv/ops/bbox.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from ..utils import ext_loader - -ext_module = ext_loader.load_ext('_ext', ['bbox_overlaps']) - - -def bbox_overlaps(bboxes1, bboxes2, mode='iou', aligned=False, offset=0): - """Calculate overlap between two set of bboxes. - - If ``aligned`` is ``False``, then calculate the ious between each bbox - of bboxes1 and bboxes2, otherwise the ious between each aligned pair of - bboxes1 and bboxes2. - - Args: - bboxes1 (Tensor): shape (m, 4) in format or empty. - bboxes2 (Tensor): shape (n, 4) in format or empty. - If aligned is ``True``, then m and n must be equal. - mode (str): "iou" (intersection over union) or iof (intersection over - foreground). - - Returns: - ious(Tensor): shape (m, n) if aligned == False else shape (m, 1) - - Example: - >>> bboxes1 = torch.FloatTensor([ - >>> [0, 0, 10, 10], - >>> [10, 10, 20, 20], - >>> [32, 32, 38, 42], - >>> ]) - >>> bboxes2 = torch.FloatTensor([ - >>> [0, 0, 10, 20], - >>> [0, 10, 10, 19], - >>> [10, 10, 20, 20], - >>> ]) - >>> bbox_overlaps(bboxes1, bboxes2) - tensor([[0.5000, 0.0000, 0.0000], - [0.0000, 0.0000, 1.0000], - [0.0000, 0.0000, 0.0000]]) - - Example: - >>> empty = torch.FloatTensor([]) - >>> nonempty = torch.FloatTensor([ - >>> [0, 0, 10, 9], - >>> ]) - >>> assert tuple(bbox_overlaps(empty, nonempty).shape) == (0, 1) - >>> assert tuple(bbox_overlaps(nonempty, empty).shape) == (1, 0) - >>> assert tuple(bbox_overlaps(empty, empty).shape) == (0, 0) - """ - - mode_dict = {'iou': 0, 'iof': 1} - assert mode in mode_dict.keys() - mode_flag = mode_dict[mode] - # Either the boxes are empty or the length of boxes' last dimension is 4 - assert (bboxes1.size(-1) == 4 or bboxes1.size(0) == 0) - assert (bboxes2.size(-1) == 4 or bboxes2.size(0) == 0) - assert offset == 1 or offset == 0 - - rows = bboxes1.size(0) - cols = bboxes2.size(0) - if aligned: - assert rows == cols - - if rows * cols == 0: - return bboxes1.new(rows, 1) if aligned else bboxes1.new(rows, cols) - - if aligned: - ious = bboxes1.new_zeros(rows) - else: - ious = bboxes1.new_zeros((rows, cols)) - ext_module.bbox_overlaps( - bboxes1, bboxes2, ious, mode=mode_flag, aligned=aligned, offset=offset) - return ious diff --git a/spaces/PSLD/PSLD/diffusion-posterior-sampling/sample_condition.py b/spaces/PSLD/PSLD/diffusion-posterior-sampling/sample_condition.py deleted file mode 100644 index 94b27b3bf9ba37b9a5fc43093b88c284c8971494..0000000000000000000000000000000000000000 --- a/spaces/PSLD/PSLD/diffusion-posterior-sampling/sample_condition.py +++ /dev/null @@ -1,121 +0,0 @@ -from functools import partial -import os -import argparse -import yaml - -import torch -import torchvision.transforms as transforms -import matplotlib.pyplot as plt - -from guided_diffusion.condition_methods import get_conditioning_method -from guided_diffusion.measurements import get_noise, get_operator -from guided_diffusion.unet import create_model -from guided_diffusion.gaussian_diffusion import create_sampler -from data.dataloader import get_dataset, get_dataloader -from util.img_utils import clear_color, mask_generator -from util.logger import get_logger - - -def load_yaml(file_path: str) -> dict: - with open(file_path) as f: - config = yaml.load(f, Loader=yaml.FullLoader) - return config - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('--model_config', type=str) - parser.add_argument('--diffusion_config', type=str) - parser.add_argument('--task_config', type=str) - parser.add_argument('--gpu', type=int, default=0) - parser.add_argument('--save_dir', type=str, default='./results') - args = parser.parse_args() - - # logger - logger = get_logger() - - # Device setting - device_str = f"cuda:{args.gpu}" if torch.cuda.is_available() else 'cpu' - logger.info(f"Device set to {device_str}.") - device = torch.device(device_str) - - # Load configurations - model_config = load_yaml(args.model_config) - diffusion_config = load_yaml(args.diffusion_config) - task_config = load_yaml(args.task_config) - - #assert model_config['learn_sigma'] == diffusion_config['learn_sigma'], \ - #"learn_sigma must be the same for model and diffusion configuartion." - - # Load model - model = create_model(**model_config) - model = model.to(device) - model.eval() - - # Prepare Operator and noise - measure_config = task_config['measurement'] - operator = get_operator(device=device, **measure_config['operator']) - noiser = get_noise(**measure_config['noise']) - logger.info(f"Operation: {measure_config['operator']['name']} / Noise: {measure_config['noise']['name']}") - - # Prepare conditioning method - cond_config = task_config['conditioning'] - cond_method = get_conditioning_method(cond_config['method'], operator, noiser, **cond_config['params']) - measurement_cond_fn = cond_method.conditioning - logger.info(f"Conditioning method : {task_config['conditioning']['method']}") - - # Load diffusion sampler - sampler = create_sampler(**diffusion_config) - sample_fn = partial(sampler.p_sample_loop, model=model, measurement_cond_fn=measurement_cond_fn) - - # Working directory - out_path = os.path.join(args.save_dir, measure_config['operator']['name']) - os.makedirs(out_path, exist_ok=True) - for img_dir in ['input', 'recon', 'progress', 'label']: - os.makedirs(os.path.join(out_path, img_dir), exist_ok=True) - - # Prepare dataloader - data_config = task_config['data'] - transform = transforms.Compose([transforms.ToTensor(), - transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) - dataset = get_dataset(**data_config, transforms=transform) - loader = get_dataloader(dataset, batch_size=1, num_workers=0, train=False) - - # Exception) In case of inpainting, we need to generate a mask - if measure_config['operator']['name'] == 'inpainting': - mask_gen = mask_generator( - **measure_config['mask_opt'] - ) - - # Do Inference - for i, ref_img in enumerate(loader): - logger.info(f"Inference for image {i}") - fname = str(i).zfill(5) + '.png' - ref_img = ref_img.to(device) - - # Exception) In case of inpainging, - if measure_config['operator'] ['name'] == 'inpainting': - mask = mask_gen(ref_img) - mask = mask[:, 0, :, :].unsqueeze(dim=0) - measurement_cond_fn = partial(cond_method.conditioning, mask=mask) - sample_fn = partial(sample_fn, measurement_cond_fn=measurement_cond_fn) - - # Forward measurement model (Ax + n) - y = operator.forward(ref_img, mask=mask) - y_n = noiser(y) - - else: - # Forward measurement model (Ax + n) - y = operator.forward(ref_img) - y_n = noiser(y) - - # Sampling - x_start = torch.randn(ref_img.shape, device=device).requires_grad_() - sample = sample_fn(x_start=x_start, measurement=y_n, record=True, save_root=out_path) - - plt.imsave(os.path.join(out_path, 'input', fname), clear_color(y_n)) - plt.imsave(os.path.join(out_path, 'label', fname), clear_color(ref_img)) - plt.imsave(os.path.join(out_path, 'recon', fname), clear_color(sample)) - -if __name__ == '__main__': - main() diff --git a/spaces/PaddlePaddle/UIE-X/header.html b/spaces/PaddlePaddle/UIE-X/header.html deleted file mode 100644 index f72eb598e56735916caade1ce8ddf82b393b1447..0000000000000000000000000000000000000000 --- a/spaces/PaddlePaddle/UIE-X/header.html +++ /dev/null @@ -1,18 +0,0 @@ - \ No newline at end of file diff --git a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/web/request.go b/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/web/request.go deleted file mode 100644 index 61603ca363996ad3fa79ee0e9bcfb6a9d52d561f..0000000000000000000000000000000000000000 Binary files a/spaces/Pattr/DrumClassification/lilypond-2.24.2/lib/guile/2.2/ccache/web/request.go and /dev/null differ diff --git a/spaces/Pravincoder/Loan_Approval_Predictor/app.py b/spaces/Pravincoder/Loan_Approval_Predictor/app.py deleted file mode 100644 index a4491fa68b763a8a344f905b856e79f8ff7aabf7..0000000000000000000000000000000000000000 --- a/spaces/Pravincoder/Loan_Approval_Predictor/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/Promit/BrainSEG/README.md b/spaces/Promit/BrainSEG/README.md deleted file mode 100644 index 2cad746725d2c1eeb7a042273106eee408d91e96..0000000000000000000000000000000000000000 --- a/spaces/Promit/BrainSEG/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: BrainSEG -emoji: 📉 -colorFrom: green -colorTo: gray -sdk: gradio -sdk_version: 3.50.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/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/chardet/sbcharsetprober.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/chardet/sbcharsetprober.py deleted file mode 100644 index 31d70e154a9967c20f7a5c9090e7cf9384672a57..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/chardet/sbcharsetprober.py +++ /dev/null @@ -1,160 +0,0 @@ -######################## BEGIN LICENSE BLOCK ######################## -# The Original Code is Mozilla Universal charset detector code. -# -# The Initial Developer of the Original Code is -# Netscape Communications Corporation. -# Portions created by the Initial Developer are Copyright (C) 2001 -# the Initial Developer. All Rights Reserved. -# -# Contributor(s): -# Mark Pilgrim - port to Python -# Shy Shalom - original C code -# -# This library 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. -# -# This library 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 this library; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -# 02110-1301 USA -######################### END LICENSE BLOCK ######################### - -from collections import namedtuple - -from .charsetprober import CharSetProber -from .enums import CharacterCategory, ProbingState, SequenceLikelihood - -SingleByteCharSetModel = namedtuple( - "SingleByteCharSetModel", - [ - "charset_name", - "language", - "char_to_order_map", - "language_model", - "typical_positive_ratio", - "keep_ascii_letters", - "alphabet", - ], -) - - -class SingleByteCharSetProber(CharSetProber): - SAMPLE_SIZE = 64 - SB_ENOUGH_REL_THRESHOLD = 1024 # 0.25 * SAMPLE_SIZE^2 - POSITIVE_SHORTCUT_THRESHOLD = 0.95 - NEGATIVE_SHORTCUT_THRESHOLD = 0.05 - - def __init__(self, model, is_reversed=False, name_prober=None): - super().__init__() - self._model = model - # TRUE if we need to reverse every pair in the model lookup - self._reversed = is_reversed - # Optional auxiliary prober for name decision - self._name_prober = name_prober - self._last_order = None - self._seq_counters = None - self._total_seqs = None - self._total_char = None - self._control_char = None - self._freq_char = None - self.reset() - - def reset(self): - super().reset() - # char order of last character - self._last_order = 255 - self._seq_counters = [0] * SequenceLikelihood.get_num_categories() - self._total_seqs = 0 - self._total_char = 0 - self._control_char = 0 - # characters that fall in our sampling range - self._freq_char = 0 - - @property - def charset_name(self): - if self._name_prober: - return self._name_prober.charset_name - return self._model.charset_name - - @property - def language(self): - if self._name_prober: - return self._name_prober.language - return self._model.language - - def feed(self, byte_str): - # TODO: Make filter_international_words keep things in self.alphabet - if not self._model.keep_ascii_letters: - byte_str = self.filter_international_words(byte_str) - else: - byte_str = self.remove_xml_tags(byte_str) - if not byte_str: - return self.state - char_to_order_map = self._model.char_to_order_map - language_model = self._model.language_model - for char in byte_str: - order = char_to_order_map.get(char, CharacterCategory.UNDEFINED) - # XXX: This was SYMBOL_CAT_ORDER before, with a value of 250, but - # CharacterCategory.SYMBOL is actually 253, so we use CONTROL - # to make it closer to the original intent. The only difference - # is whether or not we count digits and control characters for - # _total_char purposes. - if order < CharacterCategory.CONTROL: - self._total_char += 1 - if order < self.SAMPLE_SIZE: - self._freq_char += 1 - if self._last_order < self.SAMPLE_SIZE: - self._total_seqs += 1 - if not self._reversed: - lm_cat = language_model[self._last_order][order] - else: - lm_cat = language_model[order][self._last_order] - self._seq_counters[lm_cat] += 1 - self._last_order = order - - charset_name = self._model.charset_name - if self.state == ProbingState.DETECTING: - if self._total_seqs > self.SB_ENOUGH_REL_THRESHOLD: - confidence = self.get_confidence() - if confidence > self.POSITIVE_SHORTCUT_THRESHOLD: - self.logger.debug( - "%s confidence = %s, we have a winner", charset_name, confidence - ) - self._state = ProbingState.FOUND_IT - elif confidence < self.NEGATIVE_SHORTCUT_THRESHOLD: - self.logger.debug( - "%s confidence = %s, below negative shortcut threshold %s", - charset_name, - confidence, - self.NEGATIVE_SHORTCUT_THRESHOLD, - ) - self._state = ProbingState.NOT_ME - - return self.state - - def get_confidence(self): - r = 0.01 - if self._total_seqs > 0: - r = ( - ( - self._seq_counters[SequenceLikelihood.POSITIVE] - + 0.25 * self._seq_counters[SequenceLikelihood.LIKELY] - ) - / self._total_seqs - / self._model.typical_positive_ratio - ) - # The more control characters (proportionnaly to the size - # of the text), the less confident we become in the current - # charset. - r = r * (self._total_char - self._control_char) / self._total_char - r = r * self._freq_char / self._total_char - if r >= 1.0: - r = 0.99 - return r diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/rich/text.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/rich/text.py deleted file mode 100644 index 12037d0cf4f597a51b1fb80a9c1aa983f0910154..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/rich/text.py +++ /dev/null @@ -1,1286 +0,0 @@ -import re -from functools import partial, reduce -from math import gcd -from operator import itemgetter -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Iterable, - List, - NamedTuple, - Optional, - Tuple, - Union, -) - -from ._loop import loop_last -from ._pick import pick_bool -from ._wrap import divide_line -from .align import AlignMethod -from .cells import cell_len, set_cell_size -from .containers import Lines -from .control import strip_control_codes -from .emoji import EmojiVariant -from .jupyter import JupyterMixin -from .measure import Measurement -from .segment import Segment -from .style import Style, StyleType - -if TYPE_CHECKING: # pragma: no cover - from .console import Console, ConsoleOptions, JustifyMethod, OverflowMethod - -DEFAULT_JUSTIFY: "JustifyMethod" = "default" -DEFAULT_OVERFLOW: "OverflowMethod" = "fold" - - -_re_whitespace = re.compile(r"\s+$") - -TextType = Union[str, "Text"] - -GetStyleCallable = Callable[[str], Optional[StyleType]] - - -class Span(NamedTuple): - """A marked up region in some text.""" - - start: int - """Span start index.""" - end: int - """Span end index.""" - style: Union[str, Style] - """Style associated with the span.""" - - def __repr__(self) -> str: - return ( - f"Span({self.start}, {self.end}, {self.style!r})" - if (isinstance(self.style, Style) and self.style._meta) - else f"Span({self.start}, {self.end}, {repr(self.style)})" - ) - - def __bool__(self) -> bool: - return self.end > self.start - - def split(self, offset: int) -> Tuple["Span", Optional["Span"]]: - """Split a span in to 2 from a given offset.""" - - if offset < self.start: - return self, None - if offset >= self.end: - return self, None - - start, end, style = self - span1 = Span(start, min(end, offset), style) - span2 = Span(span1.end, end, style) - return span1, span2 - - def move(self, offset: int) -> "Span": - """Move start and end by a given offset. - - Args: - offset (int): Number of characters to add to start and end. - - Returns: - TextSpan: A new TextSpan with adjusted position. - """ - start, end, style = self - return Span(start + offset, end + offset, style) - - def right_crop(self, offset: int) -> "Span": - """Crop the span at the given offset. - - Args: - offset (int): A value between start and end. - - Returns: - Span: A new (possibly smaller) span. - """ - start, end, style = self - if offset >= end: - return self - return Span(start, min(offset, end), style) - - -class Text(JupyterMixin): - """Text with color / style. - - Args: - text (str, optional): Default unstyled text. Defaults to "". - style (Union[str, Style], optional): Base style for text. Defaults to "". - justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. - overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. - no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None. - end (str, optional): Character to end text with. Defaults to "\\\\n". - tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8. - spans (List[Span], optional). A list of predefined style spans. Defaults to None. - """ - - __slots__ = [ - "_text", - "style", - "justify", - "overflow", - "no_wrap", - "end", - "tab_size", - "_spans", - "_length", - ] - - def __init__( - self, - text: str = "", - style: Union[str, Style] = "", - *, - justify: Optional["JustifyMethod"] = None, - overflow: Optional["OverflowMethod"] = None, - no_wrap: Optional[bool] = None, - end: str = "\n", - tab_size: Optional[int] = 8, - spans: Optional[List[Span]] = None, - ) -> None: - sanitized_text = strip_control_codes(text) - self._text = [sanitized_text] - self.style = style - self.justify: Optional["JustifyMethod"] = justify - self.overflow: Optional["OverflowMethod"] = overflow - self.no_wrap = no_wrap - self.end = end - self.tab_size = tab_size - self._spans: List[Span] = spans or [] - self._length: int = len(sanitized_text) - - def __len__(self) -> int: - return self._length - - def __bool__(self) -> bool: - return bool(self._length) - - def __str__(self) -> str: - return self.plain - - def __repr__(self) -> str: - return f"" - - def __add__(self, other: Any) -> "Text": - if isinstance(other, (str, Text)): - result = self.copy() - result.append(other) - return result - return NotImplemented - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Text): - return NotImplemented - return self.plain == other.plain and self._spans == other._spans - - def __contains__(self, other: object) -> bool: - if isinstance(other, str): - return other in self.plain - elif isinstance(other, Text): - return other.plain in self.plain - return False - - def __getitem__(self, slice: Union[int, slice]) -> "Text": - def get_text_at(offset: int) -> "Text": - _Span = Span - text = Text( - self.plain[offset], - spans=[ - _Span(0, 1, style) - for start, end, style in self._spans - if end > offset >= start - ], - end="", - ) - return text - - if isinstance(slice, int): - return get_text_at(slice) - else: - start, stop, step = slice.indices(len(self.plain)) - if step == 1: - lines = self.divide([start, stop]) - return lines[1] - else: - # This would be a bit of work to implement efficiently - # For now, its not required - raise TypeError("slices with step!=1 are not supported") - - @property - def cell_len(self) -> int: - """Get the number of cells required to render this text.""" - return cell_len(self.plain) - - @property - def markup(self) -> str: - """Get console markup to render this Text. - - Returns: - str: A string potentially creating markup tags. - """ - from .markup import escape - - output: List[str] = [] - - plain = self.plain - markup_spans = [ - (0, False, self.style), - *((span.start, False, span.style) for span in self._spans), - *((span.end, True, span.style) for span in self._spans), - (len(plain), True, self.style), - ] - markup_spans.sort(key=itemgetter(0, 1)) - position = 0 - append = output.append - for offset, closing, style in markup_spans: - if offset > position: - append(escape(plain[position:offset])) - position = offset - if style: - append(f"[/{style}]" if closing else f"[{style}]") - markup = "".join(output) - return markup - - @classmethod - def from_markup( - cls, - text: str, - *, - style: Union[str, Style] = "", - emoji: bool = True, - emoji_variant: Optional[EmojiVariant] = None, - justify: Optional["JustifyMethod"] = None, - overflow: Optional["OverflowMethod"] = None, - end: str = "\n", - ) -> "Text": - """Create Text instance from markup. - - Args: - text (str): A string containing console markup. - emoji (bool, optional): Also render emoji code. Defaults to True. - justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. - overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. - end (str, optional): Character to end text with. Defaults to "\\\\n". - - Returns: - Text: A Text instance with markup rendered. - """ - from .markup import render - - rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant) - rendered_text.justify = justify - rendered_text.overflow = overflow - rendered_text.end = end - return rendered_text - - @classmethod - def from_ansi( - cls, - text: str, - *, - style: Union[str, Style] = "", - justify: Optional["JustifyMethod"] = None, - overflow: Optional["OverflowMethod"] = None, - no_wrap: Optional[bool] = None, - end: str = "\n", - tab_size: Optional[int] = 8, - ) -> "Text": - """Create a Text object from a string containing ANSI escape codes. - - Args: - text (str): A string containing escape codes. - style (Union[str, Style], optional): Base style for text. Defaults to "". - justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. - overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. - no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None. - end (str, optional): Character to end text with. Defaults to "\\\\n". - tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8. - """ - from .ansi import AnsiDecoder - - joiner = Text( - "\n", - justify=justify, - overflow=overflow, - no_wrap=no_wrap, - end=end, - tab_size=tab_size, - style=style, - ) - decoder = AnsiDecoder() - result = joiner.join(line for line in decoder.decode(text)) - return result - - @classmethod - def styled( - cls, - text: str, - style: StyleType = "", - *, - justify: Optional["JustifyMethod"] = None, - overflow: Optional["OverflowMethod"] = None, - ) -> "Text": - """Construct a Text instance with a pre-applied styled. A style applied in this way won't be used - to pad the text when it is justified. - - Args: - text (str): A string containing console markup. - style (Union[str, Style]): Style to apply to the text. Defaults to "". - justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. - overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. - - Returns: - Text: A text instance with a style applied to the entire string. - """ - styled_text = cls(text, justify=justify, overflow=overflow) - styled_text.stylize(style) - return styled_text - - @classmethod - def assemble( - cls, - *parts: Union[str, "Text", Tuple[str, StyleType]], - style: Union[str, Style] = "", - justify: Optional["JustifyMethod"] = None, - overflow: Optional["OverflowMethod"] = None, - no_wrap: Optional[bool] = None, - end: str = "\n", - tab_size: int = 8, - meta: Optional[Dict[str, Any]] = None, - ) -> "Text": - """Construct a text instance by combining a sequence of strings with optional styles. - The positional arguments should be either strings, or a tuple of string + style. - - Args: - style (Union[str, Style], optional): Base style for text. Defaults to "". - justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. - overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. - end (str, optional): Character to end text with. Defaults to "\\\\n". - tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8. - meta (Dict[str, Any], optional). Meta data to apply to text, or None for no meta data. Default to None - - Returns: - Text: A new text instance. - """ - text = cls( - style=style, - justify=justify, - overflow=overflow, - no_wrap=no_wrap, - end=end, - tab_size=tab_size, - ) - append = text.append - _Text = Text - for part in parts: - if isinstance(part, (_Text, str)): - append(part) - else: - append(*part) - if meta: - text.apply_meta(meta) - return text - - @property - def plain(self) -> str: - """Get the text as a single string.""" - if len(self._text) != 1: - self._text[:] = ["".join(self._text)] - return self._text[0] - - @plain.setter - def plain(self, new_text: str) -> None: - """Set the text to a new value.""" - if new_text != self.plain: - sanitized_text = strip_control_codes(new_text) - self._text[:] = [sanitized_text] - old_length = self._length - self._length = len(sanitized_text) - if old_length > self._length: - self._trim_spans() - - @property - def spans(self) -> List[Span]: - """Get a reference to the internal list of spans.""" - return self._spans - - @spans.setter - def spans(self, spans: List[Span]) -> None: - """Set spans.""" - self._spans = spans[:] - - def blank_copy(self, plain: str = "") -> "Text": - """Return a new Text instance with copied meta data (but not the string or spans).""" - copy_self = Text( - plain, - style=self.style, - justify=self.justify, - overflow=self.overflow, - no_wrap=self.no_wrap, - end=self.end, - tab_size=self.tab_size, - ) - return copy_self - - def copy(self) -> "Text": - """Return a copy of this instance.""" - copy_self = Text( - self.plain, - style=self.style, - justify=self.justify, - overflow=self.overflow, - no_wrap=self.no_wrap, - end=self.end, - tab_size=self.tab_size, - ) - copy_self._spans[:] = self._spans - return copy_self - - def stylize( - self, - style: Union[str, Style], - start: int = 0, - end: Optional[int] = None, - ) -> None: - """Apply a style to the text, or a portion of the text. - - Args: - style (Union[str, Style]): Style instance or style definition to apply. - start (int): Start offset (negative indexing is supported). Defaults to 0. - end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None. - - """ - if style: - length = len(self) - if start < 0: - start = length + start - if end is None: - end = length - if end < 0: - end = length + end - if start >= length or end <= start: - # Span not in text or not valid - return - self._spans.append(Span(start, min(length, end), style)) - - def apply_meta( - self, meta: Dict[str, Any], start: int = 0, end: Optional[int] = None - ) -> None: - """Apply meta data to the text, or a portion of the text. - - Args: - meta (Dict[str, Any]): A dict of meta information. - start (int): Start offset (negative indexing is supported). Defaults to 0. - end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None. - - """ - style = Style.from_meta(meta) - self.stylize(style, start=start, end=end) - - def on(self, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Text": - """Apply event handlers (used by Textual project). - - Example: - >>> from rich.text import Text - >>> text = Text("hello world") - >>> text.on(click="view.toggle('world')") - - Args: - meta (Dict[str, Any]): Mapping of meta information. - **handlers: Keyword args are prefixed with "@" to defined handlers. - - Returns: - Text: Self is returned to method may be chained. - """ - meta = {} if meta is None else meta - meta.update({f"@{key}": value for key, value in handlers.items()}) - self.stylize(Style.from_meta(meta)) - return self - - def remove_suffix(self, suffix: str) -> None: - """Remove a suffix if it exists. - - Args: - suffix (str): Suffix to remove. - """ - if self.plain.endswith(suffix): - self.right_crop(len(suffix)) - - def get_style_at_offset(self, console: "Console", offset: int) -> Style: - """Get the style of a character at give offset. - - Args: - console (~Console): Console where text will be rendered. - offset (int): Offset in to text (negative indexing supported) - - Returns: - Style: A Style instance. - """ - # TODO: This is a little inefficient, it is only used by full justify - if offset < 0: - offset = len(self) + offset - get_style = console.get_style - style = get_style(self.style).copy() - for start, end, span_style in self._spans: - if end > offset >= start: - style += get_style(span_style, default="") - return style - - def highlight_regex( - self, - re_highlight: str, - style: Optional[Union[GetStyleCallable, StyleType]] = None, - *, - style_prefix: str = "", - ) -> int: - """Highlight text with a regular expression, where group names are - translated to styles. - - Args: - re_highlight (str): A regular expression. - style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable - which accepts the matched text and returns a style. Defaults to None. - style_prefix (str, optional): Optional prefix to add to style group names. - - Returns: - int: Number of regex matches - """ - count = 0 - append_span = self._spans.append - _Span = Span - plain = self.plain - for match in re.finditer(re_highlight, plain): - get_span = match.span - if style: - start, end = get_span() - match_style = style(plain[start:end]) if callable(style) else style - if match_style is not None and end > start: - append_span(_Span(start, end, match_style)) - - count += 1 - for name in match.groupdict().keys(): - start, end = get_span(name) - if start != -1 and end > start: - append_span(_Span(start, end, f"{style_prefix}{name}")) - return count - - def highlight_words( - self, - words: Iterable[str], - style: Union[str, Style], - *, - case_sensitive: bool = True, - ) -> int: - """Highlight words with a style. - - Args: - words (Iterable[str]): Worlds to highlight. - style (Union[str, Style]): Style to apply. - case_sensitive (bool, optional): Enable case sensitive matchings. Defaults to True. - - Returns: - int: Number of words highlighted. - """ - re_words = "|".join(re.escape(word) for word in words) - add_span = self._spans.append - count = 0 - _Span = Span - for match in re.finditer( - re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE - ): - start, end = match.span(0) - add_span(_Span(start, end, style)) - count += 1 - return count - - def rstrip(self) -> None: - """Strip whitespace from end of text.""" - self.plain = self.plain.rstrip() - - def rstrip_end(self, size: int) -> None: - """Remove whitespace beyond a certain width at the end of the text. - - Args: - size (int): The desired size of the text. - """ - text_length = len(self) - if text_length > size: - excess = text_length - size - whitespace_match = _re_whitespace.search(self.plain) - if whitespace_match is not None: - whitespace_count = len(whitespace_match.group(0)) - self.right_crop(min(whitespace_count, excess)) - - def set_length(self, new_length: int) -> None: - """Set new length of the text, clipping or padding is required.""" - length = len(self) - if length != new_length: - if length < new_length: - self.pad_right(new_length - length) - else: - self.right_crop(length - new_length) - - def __rich_console__( - self, console: "Console", options: "ConsoleOptions" - ) -> Iterable[Segment]: - tab_size: int = console.tab_size or self.tab_size or 8 - justify = self.justify or options.justify or DEFAULT_JUSTIFY - - overflow = self.overflow or options.overflow or DEFAULT_OVERFLOW - - lines = self.wrap( - console, - options.max_width, - justify=justify, - overflow=overflow, - tab_size=tab_size or 8, - no_wrap=pick_bool(self.no_wrap, options.no_wrap, False), - ) - all_lines = Text("\n").join(lines) - yield from all_lines.render(console, end=self.end) - - def __rich_measure__( - self, console: "Console", options: "ConsoleOptions" - ) -> Measurement: - text = self.plain - lines = text.splitlines() - max_text_width = max(cell_len(line) for line in lines) if lines else 0 - words = text.split() - min_text_width = ( - max(cell_len(word) for word in words) if words else max_text_width - ) - return Measurement(min_text_width, max_text_width) - - def render(self, console: "Console", end: str = "") -> Iterable["Segment"]: - """Render the text as Segments. - - Args: - console (Console): Console instance. - end (Optional[str], optional): Optional end character. - - Returns: - Iterable[Segment]: Result of render that may be written to the console. - """ - _Segment = Segment - text = self.plain - if not self._spans: - yield Segment(text) - if end: - yield _Segment(end) - return - get_style = partial(console.get_style, default=Style.null()) - - enumerated_spans = list(enumerate(self._spans, 1)) - style_map = {index: get_style(span.style) for index, span in enumerated_spans} - style_map[0] = get_style(self.style) - - spans = [ - (0, False, 0), - *((span.start, False, index) for index, span in enumerated_spans), - *((span.end, True, index) for index, span in enumerated_spans), - (len(text), True, 0), - ] - spans.sort(key=itemgetter(0, 1)) - - stack: List[int] = [] - stack_append = stack.append - stack_pop = stack.remove - - style_cache: Dict[Tuple[Style, ...], Style] = {} - style_cache_get = style_cache.get - combine = Style.combine - - def get_current_style() -> Style: - """Construct current style from stack.""" - styles = tuple(style_map[_style_id] for _style_id in sorted(stack)) - cached_style = style_cache_get(styles) - if cached_style is not None: - return cached_style - current_style = combine(styles) - style_cache[styles] = current_style - return current_style - - for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]): - if leaving: - stack_pop(style_id) - else: - stack_append(style_id) - if next_offset > offset: - yield _Segment(text[offset:next_offset], get_current_style()) - if end: - yield _Segment(end) - - def join(self, lines: Iterable["Text"]) -> "Text": - """Join text together with this instance as the separator. - - Args: - lines (Iterable[Text]): An iterable of Text instances to join. - - Returns: - Text: A new text instance containing join text. - """ - - new_text = self.blank_copy() - - def iter_text() -> Iterable["Text"]: - if self.plain: - for last, line in loop_last(lines): - yield line - if not last: - yield self - else: - yield from lines - - extend_text = new_text._text.extend - append_span = new_text._spans.append - extend_spans = new_text._spans.extend - offset = 0 - _Span = Span - - for text in iter_text(): - extend_text(text._text) - if text.style: - append_span(_Span(offset, offset + len(text), text.style)) - extend_spans( - _Span(offset + start, offset + end, style) - for start, end, style in text._spans - ) - offset += len(text) - new_text._length = offset - return new_text - - def expand_tabs(self, tab_size: Optional[int] = None) -> None: - """Converts tabs to spaces. - - Args: - tab_size (int, optional): Size of tabs. Defaults to 8. - - """ - if "\t" not in self.plain: - return - pos = 0 - if tab_size is None: - tab_size = self.tab_size - assert tab_size is not None - result = self.blank_copy() - append = result.append - - _style = self.style - for line in self.split("\n", include_separator=True): - parts = line.split("\t", include_separator=True) - for part in parts: - if part.plain.endswith("\t"): - part._text = [part.plain[:-1] + " "] - append(part) - pos += len(part) - spaces = tab_size - ((pos - 1) % tab_size) - 1 - if spaces: - append(" " * spaces, _style) - pos += spaces - else: - append(part) - self._text = [result.plain] - self._length = len(self.plain) - self._spans[:] = result._spans - - def truncate( - self, - max_width: int, - *, - overflow: Optional["OverflowMethod"] = None, - pad: bool = False, - ) -> None: - """Truncate text if it is longer that a given width. - - Args: - max_width (int): Maximum number of characters in text. - overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None, to use self.overflow. - pad (bool, optional): Pad with spaces if the length is less than max_width. Defaults to False. - """ - _overflow = overflow or self.overflow or DEFAULT_OVERFLOW - if _overflow != "ignore": - length = cell_len(self.plain) - if length > max_width: - if _overflow == "ellipsis": - self.plain = set_cell_size(self.plain, max_width - 1) + "…" - else: - self.plain = set_cell_size(self.plain, max_width) - if pad and length < max_width: - spaces = max_width - length - self._text = [f"{self.plain}{' ' * spaces}"] - self._length = len(self.plain) - - def _trim_spans(self) -> None: - """Remove or modify any spans that are over the end of the text.""" - max_offset = len(self.plain) - _Span = Span - self._spans[:] = [ - ( - span - if span.end < max_offset - else _Span(span.start, min(max_offset, span.end), span.style) - ) - for span in self._spans - if span.start < max_offset - ] - - def pad(self, count: int, character: str = " ") -> None: - """Pad left and right with a given number of characters. - - Args: - count (int): Width of padding. - """ - assert len(character) == 1, "Character must be a string of length 1" - if count: - pad_characters = character * count - self.plain = f"{pad_characters}{self.plain}{pad_characters}" - _Span = Span - self._spans[:] = [ - _Span(start + count, end + count, style) - for start, end, style in self._spans - ] - - def pad_left(self, count: int, character: str = " ") -> None: - """Pad the left with a given character. - - Args: - count (int): Number of characters to pad. - character (str, optional): Character to pad with. Defaults to " ". - """ - assert len(character) == 1, "Character must be a string of length 1" - if count: - self.plain = f"{character * count}{self.plain}" - _Span = Span - self._spans[:] = [ - _Span(start + count, end + count, style) - for start, end, style in self._spans - ] - - def pad_right(self, count: int, character: str = " ") -> None: - """Pad the right with a given character. - - Args: - count (int): Number of characters to pad. - character (str, optional): Character to pad with. Defaults to " ". - """ - assert len(character) == 1, "Character must be a string of length 1" - if count: - self.plain = f"{self.plain}{character * count}" - - def align(self, align: AlignMethod, width: int, character: str = " ") -> None: - """Align text to a given width. - - Args: - align (AlignMethod): One of "left", "center", or "right". - width (int): Desired width. - character (str, optional): Character to pad with. Defaults to " ". - """ - self.truncate(width) - excess_space = width - cell_len(self.plain) - if excess_space: - if align == "left": - self.pad_right(excess_space, character) - elif align == "center": - left = excess_space // 2 - self.pad_left(left, character) - self.pad_right(excess_space - left, character) - else: - self.pad_left(excess_space, character) - - def append( - self, text: Union["Text", str], style: Optional[Union[str, "Style"]] = None - ) -> "Text": - """Add text with an optional style. - - Args: - text (Union[Text, str]): A str or Text to append. - style (str, optional): A style name. Defaults to None. - - Returns: - Text: Returns self for chaining. - """ - - if not isinstance(text, (str, Text)): - raise TypeError("Only str or Text can be appended to Text") - - if len(text): - if isinstance(text, str): - sanitized_text = strip_control_codes(text) - self._text.append(sanitized_text) - offset = len(self) - text_length = len(sanitized_text) - if style is not None: - self._spans.append(Span(offset, offset + text_length, style)) - self._length += text_length - elif isinstance(text, Text): - _Span = Span - if style is not None: - raise ValueError( - "style must not be set when appending Text instance" - ) - text_length = self._length - if text.style is not None: - self._spans.append( - _Span(text_length, text_length + len(text), text.style) - ) - self._text.append(text.plain) - self._spans.extend( - _Span(start + text_length, end + text_length, style) - for start, end, style in text._spans - ) - self._length += len(text) - return self - - def append_text(self, text: "Text") -> "Text": - """Append another Text instance. This method is more performant that Text.append, but - only works for Text. - - Returns: - Text: Returns self for chaining. - """ - _Span = Span - text_length = self._length - if text.style is not None: - self._spans.append(_Span(text_length, text_length + len(text), text.style)) - self._text.append(text.plain) - self._spans.extend( - _Span(start + text_length, end + text_length, style) - for start, end, style in text._spans - ) - self._length += len(text) - return self - - def append_tokens( - self, tokens: Iterable[Tuple[str, Optional[StyleType]]] - ) -> "Text": - """Append iterable of str and style. Style may be a Style instance or a str style definition. - - Args: - pairs (Iterable[Tuple[str, Optional[StyleType]]]): An iterable of tuples containing str content and style. - - Returns: - Text: Returns self for chaining. - """ - append_text = self._text.append - append_span = self._spans.append - _Span = Span - offset = len(self) - for content, style in tokens: - append_text(content) - if style is not None: - append_span(_Span(offset, offset + len(content), style)) - offset += len(content) - self._length = offset - return self - - def copy_styles(self, text: "Text") -> None: - """Copy styles from another Text instance. - - Args: - text (Text): A Text instance to copy styles from, must be the same length. - """ - self._spans.extend(text._spans) - - def split( - self, - separator: str = "\n", - *, - include_separator: bool = False, - allow_blank: bool = False, - ) -> Lines: - """Split rich text in to lines, preserving styles. - - Args: - separator (str, optional): String to split on. Defaults to "\\\\n". - include_separator (bool, optional): Include the separator in the lines. Defaults to False. - allow_blank (bool, optional): Return a blank line if the text ends with a separator. Defaults to False. - - Returns: - List[RichText]: A list of rich text, one per line of the original. - """ - assert separator, "separator must not be empty" - - text = self.plain - if separator not in text: - return Lines([self.copy()]) - - if include_separator: - lines = self.divide( - match.end() for match in re.finditer(re.escape(separator), text) - ) - else: - - def flatten_spans() -> Iterable[int]: - for match in re.finditer(re.escape(separator), text): - start, end = match.span() - yield start - yield end - - lines = Lines( - line for line in self.divide(flatten_spans()) if line.plain != separator - ) - - if not allow_blank and text.endswith(separator): - lines.pop() - - return lines - - def divide(self, offsets: Iterable[int]) -> Lines: - """Divide text in to a number of lines at given offsets. - - Args: - offsets (Iterable[int]): Offsets used to divide text. - - Returns: - Lines: New RichText instances between offsets. - """ - _offsets = list(offsets) - - if not _offsets: - return Lines([self.copy()]) - - text = self.plain - text_length = len(text) - divide_offsets = [0, *_offsets, text_length] - line_ranges = list(zip(divide_offsets, divide_offsets[1:])) - - style = self.style - justify = self.justify - overflow = self.overflow - _Text = Text - new_lines = Lines( - _Text( - text[start:end], - style=style, - justify=justify, - overflow=overflow, - ) - for start, end in line_ranges - ) - if not self._spans: - return new_lines - - _line_appends = [line._spans.append for line in new_lines._lines] - line_count = len(line_ranges) - _Span = Span - - for span_start, span_end, style in self._spans: - - lower_bound = 0 - upper_bound = line_count - start_line_no = (lower_bound + upper_bound) // 2 - - while True: - line_start, line_end = line_ranges[start_line_no] - if span_start < line_start: - upper_bound = start_line_no - 1 - elif span_start > line_end: - lower_bound = start_line_no + 1 - else: - break - start_line_no = (lower_bound + upper_bound) // 2 - - if span_end < line_end: - end_line_no = start_line_no - else: - end_line_no = lower_bound = start_line_no - upper_bound = line_count - - while True: - line_start, line_end = line_ranges[end_line_no] - if span_end < line_start: - upper_bound = end_line_no - 1 - elif span_end > line_end: - lower_bound = end_line_no + 1 - else: - break - end_line_no = (lower_bound + upper_bound) // 2 - - for line_no in range(start_line_no, end_line_no + 1): - line_start, line_end = line_ranges[line_no] - new_start = max(0, span_start - line_start) - new_end = min(span_end - line_start, line_end - line_start) - if new_end > new_start: - _line_appends[line_no](_Span(new_start, new_end, style)) - - return new_lines - - def right_crop(self, amount: int = 1) -> None: - """Remove a number of characters from the end of the text.""" - max_offset = len(self.plain) - amount - _Span = Span - self._spans[:] = [ - ( - span - if span.end < max_offset - else _Span(span.start, min(max_offset, span.end), span.style) - ) - for span in self._spans - if span.start < max_offset - ] - self._text = [self.plain[:-amount]] - self._length -= amount - - def wrap( - self, - console: "Console", - width: int, - *, - justify: Optional["JustifyMethod"] = None, - overflow: Optional["OverflowMethod"] = None, - tab_size: int = 8, - no_wrap: Optional[bool] = None, - ) -> Lines: - """Word wrap the text. - - Args: - console (Console): Console instance. - width (int): Number of characters per line. - emoji (bool, optional): Also render emoji code. Defaults to True. - justify (str, optional): Justify method: "default", "left", "center", "full", "right". Defaults to "default". - overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None. - tab_size (int, optional): Default tab size. Defaults to 8. - no_wrap (bool, optional): Disable wrapping, Defaults to False. - - Returns: - Lines: Number of lines. - """ - wrap_justify = justify or self.justify or DEFAULT_JUSTIFY - wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW - - no_wrap = pick_bool(no_wrap, self.no_wrap, False) or overflow == "ignore" - - lines = Lines() - for line in self.split(allow_blank=True): - if "\t" in line: - line.expand_tabs(tab_size) - if no_wrap: - new_lines = Lines([line]) - else: - offsets = divide_line(str(line), width, fold=wrap_overflow == "fold") - new_lines = line.divide(offsets) - for line in new_lines: - line.rstrip_end(width) - if wrap_justify: - new_lines.justify( - console, width, justify=wrap_justify, overflow=wrap_overflow - ) - for line in new_lines: - line.truncate(width, overflow=wrap_overflow) - lines.extend(new_lines) - return lines - - def fit(self, width: int) -> Lines: - """Fit the text in to given width by chopping in to lines. - - Args: - width (int): Maximum characters in a line. - - Returns: - Lines: List of lines. - """ - lines: Lines = Lines() - append = lines.append - for line in self.split(): - line.set_length(width) - append(line) - return lines - - def detect_indentation(self) -> int: - """Auto-detect indentation of code. - - Returns: - int: Number of spaces used to indent code. - """ - - _indentations = { - len(match.group(1)) - for match in re.finditer(r"^( *)(.*)$", self.plain, flags=re.MULTILINE) - } - - try: - indentation = ( - reduce(gcd, [indent for indent in _indentations if not indent % 2]) or 1 - ) - except TypeError: - indentation = 1 - - return indentation - - def with_indent_guides( - self, - indent_size: Optional[int] = None, - *, - character: str = "│", - style: StyleType = "dim green", - ) -> "Text": - """Adds indent guide lines to text. - - Args: - indent_size (Optional[int]): Size of indentation, or None to auto detect. Defaults to None. - character (str, optional): Character to use for indentation. Defaults to "│". - style (Union[Style, str], optional): Style of indent guides. - - Returns: - Text: New text with indentation guides. - """ - - _indent_size = self.detect_indentation() if indent_size is None else indent_size - - text = self.copy() - text.expand_tabs() - indent_line = f"{character}{' ' * (_indent_size - 1)}" - - re_indent = re.compile(r"^( *)(.*)$") - new_lines: List[Text] = [] - add_line = new_lines.append - blank_lines = 0 - for line in text.split(allow_blank=True): - match = re_indent.match(line.plain) - if not match or not match.group(2): - blank_lines += 1 - continue - indent = match.group(1) - full_indents, remaining_space = divmod(len(indent), _indent_size) - new_indent = f"{indent_line * full_indents}{' ' * remaining_space}" - line.plain = new_indent + line.plain[len(new_indent) :] - line.stylize(style, 0, len(new_indent)) - if blank_lines: - new_lines.extend([Text(new_indent, style=style)] * blank_lines) - blank_lines = 0 - add_line(line) - if blank_lines: - new_lines.extend([Text("", style=style)] * blank_lines) - - new_text = text.blank_copy("\n").join(new_lines) - return new_text - - -if __name__ == "__main__": # pragma: no cover - from pip._vendor.rich.console import Console - - text = Text( - """\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n""" - ) - text.highlight_words(["Lorem"], "bold") - text.highlight_words(["ipsum"], "italic") - - console = Console() - - console.rule("justify='left'") - console.print(text, style="red") - console.print() - - console.rule("justify='center'") - console.print(text, style="green", justify="center") - console.print() - - console.rule("justify='right'") - console.print(text, style="blue", justify="right") - console.print() - - console.rule("justify='full'") - console.print(text, style="magenta", justify="full") - console.print() diff --git a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/urllib3/exceptions.py b/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/urllib3/exceptions.py deleted file mode 100644 index cba6f3f560f71b3b15ab6aaf21dde4f1bba1bd00..0000000000000000000000000000000000000000 --- a/spaces/Raspberry-ai/main/.env/lib/python3.11/site-packages/pip/_vendor/urllib3/exceptions.py +++ /dev/null @@ -1,323 +0,0 @@ -from __future__ import absolute_import - -from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead - -# Base Exceptions - - -class HTTPError(Exception): - """Base exception used by this module.""" - - pass - - -class HTTPWarning(Warning): - """Base warning used by this module.""" - - pass - - -class PoolError(HTTPError): - """Base exception for errors caused within a pool.""" - - def __init__(self, pool, message): - self.pool = pool - HTTPError.__init__(self, "%s: %s" % (pool, message)) - - def __reduce__(self): - # For pickling purposes. - return self.__class__, (None, None) - - -class RequestError(PoolError): - """Base exception for PoolErrors that have associated URLs.""" - - def __init__(self, pool, url, message): - self.url = url - PoolError.__init__(self, pool, message) - - def __reduce__(self): - # For pickling purposes. - return self.__class__, (None, self.url, None) - - -class SSLError(HTTPError): - """Raised when SSL certificate fails in an HTTPS connection.""" - - pass - - -class ProxyError(HTTPError): - """Raised when the connection to a proxy fails.""" - - def __init__(self, message, error, *args): - super(ProxyError, self).__init__(message, error, *args) - self.original_error = error - - -class DecodeError(HTTPError): - """Raised when automatic decoding based on Content-Type fails.""" - - pass - - -class ProtocolError(HTTPError): - """Raised when something unexpected happens mid-request/response.""" - - pass - - -#: Renamed to ProtocolError but aliased for backwards compatibility. -ConnectionError = ProtocolError - - -# Leaf Exceptions - - -class MaxRetryError(RequestError): - """Raised when the maximum number of retries is exceeded. - - :param pool: The connection pool - :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool` - :param string url: The requested Url - :param exceptions.Exception reason: The underlying error - - """ - - def __init__(self, pool, url, reason=None): - self.reason = reason - - message = "Max retries exceeded with url: %s (Caused by %r)" % (url, reason) - - RequestError.__init__(self, pool, url, message) - - -class HostChangedError(RequestError): - """Raised when an existing pool gets a request for a foreign host.""" - - def __init__(self, pool, url, retries=3): - message = "Tried to open a foreign host with url: %s" % url - RequestError.__init__(self, pool, url, message) - self.retries = retries - - -class TimeoutStateError(HTTPError): - """Raised when passing an invalid state to a timeout""" - - pass - - -class TimeoutError(HTTPError): - """Raised when a socket timeout error occurs. - - Catching this error will catch both :exc:`ReadTimeoutErrors - ` and :exc:`ConnectTimeoutErrors `. - """ - - pass - - -class ReadTimeoutError(TimeoutError, RequestError): - """Raised when a socket timeout occurs while receiving data from a server""" - - pass - - -# This timeout error does not have a URL attached and needs to inherit from the -# base HTTPError -class ConnectTimeoutError(TimeoutError): - """Raised when a socket timeout occurs while connecting to a server""" - - pass - - -class NewConnectionError(ConnectTimeoutError, PoolError): - """Raised when we fail to establish a new connection. Usually ECONNREFUSED.""" - - pass - - -class EmptyPoolError(PoolError): - """Raised when a pool runs out of connections and no more are allowed.""" - - pass - - -class ClosedPoolError(PoolError): - """Raised when a request enters a pool after the pool has been closed.""" - - pass - - -class LocationValueError(ValueError, HTTPError): - """Raised when there is something wrong with a given URL input.""" - - pass - - -class LocationParseError(LocationValueError): - """Raised when get_host or similar fails to parse the URL input.""" - - def __init__(self, location): - message = "Failed to parse: %s" % location - HTTPError.__init__(self, message) - - self.location = location - - -class URLSchemeUnknown(LocationValueError): - """Raised when a URL input has an unsupported scheme.""" - - def __init__(self, scheme): - message = "Not supported URL scheme %s" % scheme - super(URLSchemeUnknown, self).__init__(message) - - self.scheme = scheme - - -class ResponseError(HTTPError): - """Used as a container for an error reason supplied in a MaxRetryError.""" - - GENERIC_ERROR = "too many error responses" - SPECIFIC_ERROR = "too many {status_code} error responses" - - -class SecurityWarning(HTTPWarning): - """Warned when performing security reducing actions""" - - pass - - -class SubjectAltNameWarning(SecurityWarning): - """Warned when connecting to a host with a certificate missing a SAN.""" - - pass - - -class InsecureRequestWarning(SecurityWarning): - """Warned when making an unverified HTTPS request.""" - - pass - - -class SystemTimeWarning(SecurityWarning): - """Warned when system time is suspected to be wrong""" - - pass - - -class InsecurePlatformWarning(SecurityWarning): - """Warned when certain TLS/SSL configuration is not available on a platform.""" - - pass - - -class SNIMissingWarning(HTTPWarning): - """Warned when making a HTTPS request without SNI available.""" - - pass - - -class DependencyWarning(HTTPWarning): - """ - Warned when an attempt is made to import a module with missing optional - dependencies. - """ - - pass - - -class ResponseNotChunked(ProtocolError, ValueError): - """Response needs to be chunked in order to read it as chunks.""" - - pass - - -class BodyNotHttplibCompatible(HTTPError): - """ - Body should be :class:`http.client.HTTPResponse` like - (have an fp attribute which returns raw chunks) for read_chunked(). - """ - - pass - - -class IncompleteRead(HTTPError, httplib_IncompleteRead): - """ - Response length doesn't match expected Content-Length - - Subclass of :class:`http.client.IncompleteRead` to allow int value - for ``partial`` to avoid creating large objects on streamed reads. - """ - - def __init__(self, partial, expected): - super(IncompleteRead, self).__init__(partial, expected) - - def __repr__(self): - return "IncompleteRead(%i bytes read, %i more expected)" % ( - self.partial, - self.expected, - ) - - -class InvalidChunkLength(HTTPError, httplib_IncompleteRead): - """Invalid chunk length in a chunked response.""" - - def __init__(self, response, length): - super(InvalidChunkLength, self).__init__( - response.tell(), response.length_remaining - ) - self.response = response - self.length = length - - def __repr__(self): - return "InvalidChunkLength(got length %r, %i bytes read)" % ( - self.length, - self.partial, - ) - - -class InvalidHeader(HTTPError): - """The header provided was somehow invalid.""" - - pass - - -class ProxySchemeUnknown(AssertionError, URLSchemeUnknown): - """ProxyManager does not support the supplied scheme""" - - # TODO(t-8ch): Stop inheriting from AssertionError in v2.0. - - def __init__(self, scheme): - # 'localhost' is here because our URL parser parses - # localhost:8080 -> scheme=localhost, remove if we fix this. - if scheme == "localhost": - scheme = None - if scheme is None: - message = "Proxy URL had no scheme, should start with http:// or https://" - else: - message = ( - "Proxy URL had unsupported scheme %s, should use http:// or https://" - % scheme - ) - super(ProxySchemeUnknown, self).__init__(message) - - -class ProxySchemeUnsupported(ValueError): - """Fetching HTTPS resources through HTTPS proxies is unsupported""" - - pass - - -class HeaderParsingError(HTTPError): - """Raised by assert_header_parsing, but we convert it to a log.warning statement.""" - - def __init__(self, defects, unparsed_data): - message = "%s, unparsed data: %r" % (defects or "Unknown", unparsed_data) - super(HeaderParsingError, self).__init__(message) - - -class UnrewindableBodyError(HTTPError): - """urllib3 encountered an error when trying to rewind a body""" - - pass diff --git a/spaces/Realcat/image-matching-webui/third_party/SuperGluePretrainedNetwork/demo_superglue.py b/spaces/Realcat/image-matching-webui/third_party/SuperGluePretrainedNetwork/demo_superglue.py deleted file mode 100644 index c639efd7481052b842c640d4aa23aaf18e0eb449..0000000000000000000000000000000000000000 --- a/spaces/Realcat/image-matching-webui/third_party/SuperGluePretrainedNetwork/demo_superglue.py +++ /dev/null @@ -1,322 +0,0 @@ -#! /usr/bin/env python3 -# -# %BANNER_BEGIN% -# --------------------------------------------------------------------- -# %COPYRIGHT_BEGIN% -# -# Magic Leap, Inc. ("COMPANY") CONFIDENTIAL -# -# Unpublished Copyright (c) 2020 -# Magic Leap, Inc., All Rights Reserved. -# -# NOTICE: All information contained herein is, and remains the property -# of COMPANY. The intellectual and technical concepts contained herein -# are proprietary to COMPANY and may be covered by U.S. and Foreign -# Patents, patents in process, and are protected by trade secret or -# copyright law. Dissemination of this information or reproduction of -# this material is strictly forbidden unless prior written permission is -# obtained from COMPANY. Access to the source code contained herein is -# hereby forbidden to anyone except current COMPANY employees, managers -# or contractors who have executed Confidentiality and Non-disclosure -# agreements explicitly covering such access. -# -# The copyright notice above does not evidence any actual or intended -# publication or disclosure of this source code, which includes -# information that is confidential and/or proprietary, and is a trade -# secret, of COMPANY. ANY REPRODUCTION, MODIFICATION, DISTRIBUTION, -# PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR THROUGH USE OF THIS -# SOURCE CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF COMPANY IS -# STRICTLY PROHIBITED, AND IN VIOLATION OF APPLICABLE LAWS AND -# INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF THIS SOURCE -# CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS -# TO REPRODUCE, DISCLOSE OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE, -# USE, OR SELL ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART. -# -# %COPYRIGHT_END% -# ---------------------------------------------------------------------- -# %AUTHORS_BEGIN% -# -# Originating Authors: Paul-Edouard Sarlin -# Daniel DeTone -# Tomasz Malisiewicz -# -# %AUTHORS_END% -# --------------------------------------------------------------------*/ -# %BANNER_END% - -from pathlib import Path -import argparse -import cv2 -import matplotlib.cm as cm -import torch - -from models.matching import Matching -from models.utils import ( - AverageTimer, - VideoStreamer, - make_matching_plot_fast, - frame2tensor, -) - -torch.set_grad_enabled(False) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="SuperGlue demo", - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - ) - parser.add_argument( - "--input", - type=str, - default="0", - help="ID of a USB webcam, URL of an IP camera, " - "or path to an image directory or movie file", - ) - parser.add_argument( - "--output_dir", - type=str, - default=None, - help="Directory where to write output frames (If None, no output)", - ) - - parser.add_argument( - "--image_glob", - type=str, - nargs="+", - default=["*.png", "*.jpg", "*.jpeg"], - help="Glob if a directory of images is specified", - ) - parser.add_argument( - "--skip", - type=int, - default=1, - help="Images to skip if input is a movie or directory", - ) - parser.add_argument( - "--max_length", - type=int, - default=1000000, - help="Maximum length if input is a movie or directory", - ) - parser.add_argument( - "--resize", - type=int, - nargs="+", - default=[640, 480], - help="Resize the input image before running inference. If two numbers, " - "resize to the exact dimensions, if one number, resize the max " - "dimension, if -1, do not resize", - ) - - parser.add_argument( - "--superglue", - choices={"indoor", "outdoor"}, - default="indoor", - help="SuperGlue weights", - ) - parser.add_argument( - "--max_keypoints", - type=int, - default=-1, - help="Maximum number of keypoints detected by Superpoint" - " ('-1' keeps all keypoints)", - ) - parser.add_argument( - "--keypoint_threshold", - type=float, - default=0.005, - help="SuperPoint keypoint detector confidence threshold", - ) - parser.add_argument( - "--nms_radius", - type=int, - default=4, - help="SuperPoint Non Maximum Suppression (NMS) radius" " (Must be positive)", - ) - parser.add_argument( - "--sinkhorn_iterations", - type=int, - default=20, - help="Number of Sinkhorn iterations performed by SuperGlue", - ) - parser.add_argument( - "--match_threshold", type=float, default=0.2, help="SuperGlue match threshold" - ) - - parser.add_argument( - "--show_keypoints", action="store_true", help="Show the detected keypoints" - ) - parser.add_argument( - "--no_display", - action="store_true", - help="Do not display images to screen. Useful if running remotely", - ) - parser.add_argument( - "--force_cpu", action="store_true", help="Force pytorch to run in CPU mode." - ) - - opt = parser.parse_args() - print(opt) - - if len(opt.resize) == 2 and opt.resize[1] == -1: - opt.resize = opt.resize[0:1] - if len(opt.resize) == 2: - print("Will resize to {}x{} (WxH)".format(opt.resize[0], opt.resize[1])) - elif len(opt.resize) == 1 and opt.resize[0] > 0: - print("Will resize max dimension to {}".format(opt.resize[0])) - elif len(opt.resize) == 1: - print("Will not resize images") - else: - raise ValueError("Cannot specify more than two integers for --resize") - - device = "cuda" if torch.cuda.is_available() and not opt.force_cpu else "cpu" - print('Running inference on device "{}"'.format(device)) - config = { - "superpoint": { - "nms_radius": opt.nms_radius, - "keypoint_threshold": opt.keypoint_threshold, - "max_keypoints": opt.max_keypoints, - }, - "superglue": { - "weights": opt.superglue, - "sinkhorn_iterations": opt.sinkhorn_iterations, - "match_threshold": opt.match_threshold, - }, - } - matching = Matching(config).eval().to(device) - keys = ["keypoints", "scores", "descriptors"] - - vs = VideoStreamer(opt.input, opt.resize, opt.skip, opt.image_glob, opt.max_length) - frame, ret = vs.next_frame() - assert ret, "Error when reading the first frame (try different --input?)" - - frame_tensor = frame2tensor(frame, device) - last_data = matching.superpoint({"image": frame_tensor}) - last_data = {k + "0": last_data[k] for k in keys} - last_data["image0"] = frame_tensor - last_frame = frame - last_image_id = 0 - - if opt.output_dir is not None: - print("==> Will write outputs to {}".format(opt.output_dir)) - Path(opt.output_dir).mkdir(exist_ok=True) - - # Create a window to display the demo. - if not opt.no_display: - cv2.namedWindow("SuperGlue matches", cv2.WINDOW_NORMAL) - cv2.resizeWindow("SuperGlue matches", 640 * 2, 480) - else: - print("Skipping visualization, will not show a GUI.") - - # Print the keyboard help menu. - print( - "==> Keyboard control:\n" - "\tn: select the current frame as the anchor\n" - "\te/r: increase/decrease the keypoint confidence threshold\n" - "\td/f: increase/decrease the match filtering threshold\n" - "\tk: toggle the visualization of keypoints\n" - "\tq: quit" - ) - - timer = AverageTimer() - - while True: - frame, ret = vs.next_frame() - if not ret: - print("Finished demo_superglue.py") - break - timer.update("data") - stem0, stem1 = last_image_id, vs.i - 1 - - frame_tensor = frame2tensor(frame, device) - pred = matching({**last_data, "image1": frame_tensor}) - kpts0 = last_data["keypoints0"][0].cpu().numpy() - kpts1 = pred["keypoints1"][0].cpu().numpy() - matches = pred["matches0"][0].cpu().numpy() - confidence = pred["matching_scores0"][0].cpu().numpy() - timer.update("forward") - - valid = matches > -1 - mkpts0 = kpts0[valid] - mkpts1 = kpts1[matches[valid]] - color = cm.jet(confidence[valid]) - text = [ - "SuperGlue", - "Keypoints: {}:{}".format(len(kpts0), len(kpts1)), - "Matches: {}".format(len(mkpts0)), - ] - k_thresh = matching.superpoint.config["keypoint_threshold"] - m_thresh = matching.superglue.config["match_threshold"] - small_text = [ - "Keypoint Threshold: {:.4f}".format(k_thresh), - "Match Threshold: {:.2f}".format(m_thresh), - "Image Pair: {:06}:{:06}".format(stem0, stem1), - ] - out = make_matching_plot_fast( - last_frame, - frame, - kpts0, - kpts1, - mkpts0, - mkpts1, - color, - text, - path=None, - show_keypoints=opt.show_keypoints, - small_text=small_text, - ) - - if not opt.no_display: - cv2.imshow("SuperGlue matches", out) - key = chr(cv2.waitKey(1) & 0xFF) - if key == "q": - vs.cleanup() - print("Exiting (via q) demo_superglue.py") - break - elif key == "n": # set the current frame as anchor - last_data = {k + "0": pred[k + "1"] for k in keys} - last_data["image0"] = frame_tensor - last_frame = frame - last_image_id = vs.i - 1 - elif key in ["e", "r"]: - # Increase/decrease keypoint threshold by 10% each keypress. - d = 0.1 * (-1 if key == "e" else 1) - matching.superpoint.config["keypoint_threshold"] = min( - max( - 0.0001, - matching.superpoint.config["keypoint_threshold"] * (1 + d), - ), - 1, - ) - print( - "\nChanged the keypoint threshold to {:.4f}".format( - matching.superpoint.config["keypoint_threshold"] - ) - ) - elif key in ["d", "f"]: - # Increase/decrease match threshold by 0.05 each keypress. - d = 0.05 * (-1 if key == "d" else 1) - matching.superglue.config["match_threshold"] = min( - max(0.05, matching.superglue.config["match_threshold"] + d), 0.95 - ) - print( - "\nChanged the match threshold to {:.2f}".format( - matching.superglue.config["match_threshold"] - ) - ) - elif key == "k": - opt.show_keypoints = not opt.show_keypoints - - timer.update("viz") - timer.print() - - if opt.output_dir is not None: - # stem = 'matches_{:06}_{:06}'.format(last_image_id, vs.i-1) - stem = "matches_{:06}_{:06}".format(stem0, stem1) - out_file = str(Path(opt.output_dir, stem + ".png")) - print("\nWriting image to {}".format(out_file)) - cv2.imwrite(out_file, out) - - cv2.destroyAllWindows() - vs.cleanup() diff --git a/spaces/Retinalogic/pastel-mix/README.md b/spaces/Retinalogic/pastel-mix/README.md deleted file mode 100644 index a6b00116cfdc82111195e3ea39a8220f347089fe..0000000000000000000000000000000000000000 --- a/spaces/Retinalogic/pastel-mix/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Pastel Mix -emoji: 🔥 -colorFrom: red -colorTo: pink -sdk: gradio -sdk_version: 3.33.1 -app_file: app.py -pinned: false -license: creativeml-openrail-m ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/configs/_base_/models/ccnet_r50-d8.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/configs/_base_/models/ccnet_r50-d8.py deleted file mode 100644 index 794148f576b9e215c3c6963e73dffe98204b7717..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/configs/_base_/models/ccnet_r50-d8.py +++ /dev/null @@ -1,44 +0,0 @@ -# model settings -norm_cfg = dict(type='SyncBN', requires_grad=True) -model = dict( - type='EncoderDecoder', - pretrained='open-mmlab://resnet50_v1c', - backbone=dict( - type='ResNetV1c', - depth=50, - num_stages=4, - out_indices=(0, 1, 2, 3), - dilations=(1, 1, 2, 4), - strides=(1, 2, 1, 1), - norm_cfg=norm_cfg, - norm_eval=False, - style='pytorch', - contract_dilation=True), - decode_head=dict( - type='CCHead', - in_channels=2048, - in_index=3, - channels=512, - recurrence=2, - dropout_ratio=0.1, - num_classes=19, - 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=1024, - in_index=2, - channels=256, - num_convs=1, - concat_input=False, - dropout_ratio=0.1, - num_classes=19, - 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='whole')) diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/logger/dvclive.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/logger/dvclive.py deleted file mode 100644 index 687cdc58c0336c92b1e4f9a410ba67ebaab2bc7a..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmcv/runner/hooks/logger/dvclive.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from ...dist_utils import master_only -from ..hook import HOOKS -from .base import LoggerHook - - -@HOOKS.register_module() -class DvcliveLoggerHook(LoggerHook): - """Class to log metrics with dvclive. - - It requires `dvclive`_ to be installed. - - Args: - path (str): Directory where dvclive will write TSV log files. - interval (int): Logging interval (every k iterations). - Default 10. - ignore_last (bool): Ignore the log of last iterations in each epoch - if less than `interval`. - Default: True. - reset_flag (bool): Whether to clear the output buffer after logging. - Default: True. - by_epoch (bool): Whether EpochBasedRunner is used. - Default: True. - - .. _dvclive: - https://dvc.org/doc/dvclive - """ - - def __init__(self, - path, - interval=10, - ignore_last=True, - reset_flag=True, - by_epoch=True): - - super(DvcliveLoggerHook, self).__init__(interval, ignore_last, - reset_flag, by_epoch) - self.path = path - self.import_dvclive() - - def import_dvclive(self): - try: - import dvclive - except ImportError: - raise ImportError( - 'Please run "pip install dvclive" to install dvclive') - self.dvclive = dvclive - - @master_only - def before_run(self, runner): - self.dvclive.init(self.path) - - @master_only - def log(self, runner): - tags = self.get_loggable_tags(runner) - if tags: - for k, v in tags.items(): - self.dvclive.log(k, v, step=self.get_iter(runner)) diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/core/bbox/match_costs/match_cost.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/core/bbox/match_costs/match_cost.py deleted file mode 100644 index 38869737d66064ee5adea4b2c8ff26ae091e5f56..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmdet/core/bbox/match_costs/match_cost.py +++ /dev/null @@ -1,184 +0,0 @@ -import torch - -from mmdet.core.bbox.iou_calculators import bbox_overlaps -from mmdet.core.bbox.transforms import bbox_cxcywh_to_xyxy, bbox_xyxy_to_cxcywh -from .builder import MATCH_COST - - -@MATCH_COST.register_module() -class BBoxL1Cost(object): - """BBoxL1Cost. - - Args: - weight (int | float, optional): loss_weight - box_format (str, optional): 'xyxy' for DETR, 'xywh' for Sparse_RCNN - - Examples: - >>> from mmdet.core.bbox.match_costs.match_cost import BBoxL1Cost - >>> import torch - >>> self = BBoxL1Cost() - >>> bbox_pred = torch.rand(1, 4) - >>> gt_bboxes= torch.FloatTensor([[0, 0, 2, 4], [1, 2, 3, 4]]) - >>> factor = torch.tensor([10, 8, 10, 8]) - >>> self(bbox_pred, gt_bboxes, factor) - tensor([[1.6172, 1.6422]]) - """ - - def __init__(self, weight=1., box_format='xyxy'): - self.weight = weight - assert box_format in ['xyxy', 'xywh'] - self.box_format = box_format - - def __call__(self, bbox_pred, gt_bboxes): - """ - Args: - bbox_pred (Tensor): Predicted boxes with normalized coordinates - (cx, cy, w, h), which are all in range [0, 1]. Shape - [num_query, 4]. - gt_bboxes (Tensor): Ground truth boxes with normalized - coordinates (x1, y1, x2, y2). Shape [num_gt, 4]. - - Returns: - torch.Tensor: bbox_cost value with weight - """ - if self.box_format == 'xywh': - gt_bboxes = bbox_xyxy_to_cxcywh(gt_bboxes) - elif self.box_format == 'xyxy': - bbox_pred = bbox_cxcywh_to_xyxy(bbox_pred) - bbox_cost = torch.cdist(bbox_pred, gt_bboxes, p=1) - return bbox_cost * self.weight - - -@MATCH_COST.register_module() -class FocalLossCost(object): - """FocalLossCost. - - Args: - weight (int | float, optional): loss_weight - alpha (int | float, optional): focal_loss alpha - gamma (int | float, optional): focal_loss gamma - eps (float, optional): default 1e-12 - - Examples: - >>> from mmdet.core.bbox.match_costs.match_cost import FocalLossCost - >>> import torch - >>> self = FocalLossCost() - >>> cls_pred = torch.rand(4, 3) - >>> gt_labels = torch.tensor([0, 1, 2]) - >>> factor = torch.tensor([10, 8, 10, 8]) - >>> self(cls_pred, gt_labels) - tensor([[-0.3236, -0.3364, -0.2699], - [-0.3439, -0.3209, -0.4807], - [-0.4099, -0.3795, -0.2929], - [-0.1950, -0.1207, -0.2626]]) - """ - - def __init__(self, weight=1., alpha=0.25, gamma=2, eps=1e-12): - self.weight = weight - self.alpha = alpha - self.gamma = gamma - self.eps = eps - - def __call__(self, cls_pred, gt_labels): - """ - Args: - cls_pred (Tensor): Predicted classification logits, shape - [num_query, num_class]. - gt_labels (Tensor): Label of `gt_bboxes`, shape (num_gt,). - - Returns: - torch.Tensor: cls_cost value with weight - """ - cls_pred = cls_pred.sigmoid() - neg_cost = -(1 - cls_pred + self.eps).log() * ( - 1 - self.alpha) * cls_pred.pow(self.gamma) - pos_cost = -(cls_pred + self.eps).log() * self.alpha * ( - 1 - cls_pred).pow(self.gamma) - cls_cost = pos_cost[:, gt_labels] - neg_cost[:, gt_labels] - return cls_cost * self.weight - - -@MATCH_COST.register_module() -class ClassificationCost(object): - """ClsSoftmaxCost. - - Args: - weight (int | float, optional): loss_weight - - Examples: - >>> from mmdet.core.bbox.match_costs.match_cost import \ - ... ClassificationCost - >>> import torch - >>> self = ClassificationCost() - >>> cls_pred = torch.rand(4, 3) - >>> gt_labels = torch.tensor([0, 1, 2]) - >>> factor = torch.tensor([10, 8, 10, 8]) - >>> self(cls_pred, gt_labels) - tensor([[-0.3430, -0.3525, -0.3045], - [-0.3077, -0.2931, -0.3992], - [-0.3664, -0.3455, -0.2881], - [-0.3343, -0.2701, -0.3956]]) - """ - - def __init__(self, weight=1.): - self.weight = weight - - def __call__(self, cls_pred, gt_labels): - """ - Args: - cls_pred (Tensor): Predicted classification logits, shape - [num_query, num_class]. - gt_labels (Tensor): Label of `gt_bboxes`, shape (num_gt,). - - Returns: - torch.Tensor: cls_cost value with weight - """ - # Following the official DETR repo, contrary to the loss that - # NLL is used, we approximate it in 1 - cls_score[gt_label]. - # The 1 is a constant that doesn't change the matching, - # so it can be omitted. - cls_score = cls_pred.softmax(-1) - cls_cost = -cls_score[:, gt_labels] - return cls_cost * self.weight - - -@MATCH_COST.register_module() -class IoUCost(object): - """IoUCost. - - Args: - iou_mode (str, optional): iou mode such as 'iou' | 'giou' - weight (int | float, optional): loss weight - - Examples: - >>> from mmdet.core.bbox.match_costs.match_cost import IoUCost - >>> import torch - >>> self = IoUCost() - >>> bboxes = torch.FloatTensor([[1,1, 2, 2], [2, 2, 3, 4]]) - >>> gt_bboxes = torch.FloatTensor([[0, 0, 2, 4], [1, 2, 3, 4]]) - >>> self(bboxes, gt_bboxes) - tensor([[-0.1250, 0.1667], - [ 0.1667, -0.5000]]) - """ - - def __init__(self, iou_mode='giou', weight=1.): - self.weight = weight - self.iou_mode = iou_mode - - def __call__(self, bboxes, gt_bboxes): - """ - Args: - bboxes (Tensor): Predicted boxes with unnormalized coordinates - (x1, y1, x2, y2). Shape [num_query, 4]. - gt_bboxes (Tensor): Ground truth boxes with unnormalized - coordinates (x1, y1, x2, y2). Shape [num_gt, 4]. - - Returns: - torch.Tensor: iou_cost value with weight - """ - # overlaps: [num_bboxes, num_gt] - overlaps = bbox_overlaps( - bboxes, gt_bboxes, mode=self.iou_mode, is_aligned=False) - # The 1 is a constant that doesn't change the matching, so omitted. - iou_cost = -overlaps - return iou_cost * self.weight diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmseg/models/utils/__init__.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmseg/models/utils/__init__.py deleted file mode 100644 index 3d3bdd349b9f2ae499a2fcb2ac1d2e3c77befebe..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer/mmseg/models/utils/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -from .drop import DropPath -from .inverted_residual import InvertedResidual, InvertedResidualV3 -from .make_divisible import make_divisible -from .res_layer import ResLayer -from .se_layer import SELayer -from .self_attention_block import SelfAttentionBlock -from .up_conv_block import UpConvBlock -from .weight_init import trunc_normal_ - -__all__ = [ - 'ResLayer', 'SelfAttentionBlock', 'make_divisible', 'InvertedResidual', - 'UpConvBlock', 'InvertedResidualV3', 'SELayer', 'DropPath', 'trunc_normal_' -] diff --git a/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/runner/hooks/memory.py b/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/runner/hooks/memory.py deleted file mode 100644 index 70cf9a838fb314e3bd3c07aadbc00921a81e83ed..0000000000000000000000000000000000000000 --- a/spaces/Robert001/UniControl-Demo/annotator/uniformer_base/mmcv/runner/hooks/memory.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import torch - -from .hook import HOOKS, Hook - - -@HOOKS.register_module() -class EmptyCacheHook(Hook): - - def __init__(self, before_epoch=False, after_epoch=True, after_iter=False): - self._before_epoch = before_epoch - self._after_epoch = after_epoch - self._after_iter = after_iter - - def after_iter(self, runner): - if self._after_iter: - torch.cuda.empty_cache() - - def before_epoch(self, runner): - if self._before_epoch: - torch.cuda.empty_cache() - - def after_epoch(self, runner): - if self._after_epoch: - torch.cuda.empty_cache() diff --git a/spaces/RobotJelly/Text_Or_Image-To-Image_Search/README.md b/spaces/RobotJelly/Text_Or_Image-To-Image_Search/README.md deleted file mode 100644 index 5bdeb3b6e945bf85a92feef4b0f520927e5cdab8..0000000000000000000000000000000000000000 --- a/spaces/RobotJelly/Text_Or_Image-To-Image_Search/README.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Search Text/Image To Image -emoji: 📝🖼️ -colorFrom: pink -colorTo: gray -sdk: gradio -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` - -`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). -Path is relative to the root of the repository. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/Ryzal/rvc-models-new/lib/infer_pack/attentions.py b/spaces/Ryzal/rvc-models-new/lib/infer_pack/attentions.py deleted file mode 100644 index 05501be1871643f78dddbeaa529c96667031a8db..0000000000000000000000000000000000000000 --- a/spaces/Ryzal/rvc-models-new/lib/infer_pack/attentions.py +++ /dev/null @@ -1,417 +0,0 @@ -import copy -import math -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F - -from lib.infer_pack import commons -from lib.infer_pack import modules -from lib.infer_pack.modules import LayerNorm - - -class Encoder(nn.Module): - def __init__( - self, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size=1, - p_dropout=0.0, - window_size=10, - **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.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, - p_dropout=p_dropout, - window_size=window_size, - ) - ) - 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)) - - def forward(self, x, x_mask): - attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.attn_layers[i](x, x, attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class Decoder(nn.Module): - def __init__( - self, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size=1, - p_dropout=0.0, - proximal_bias=False, - proximal_init=True, - **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.proximal_bias = proximal_bias - self.proximal_init = proximal_init - - self.drop = nn.Dropout(p_dropout) - self.self_attn_layers = nn.ModuleList() - self.norm_layers_0 = nn.ModuleList() - self.encdec_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.self_attn_layers.append( - MultiHeadAttention( - hidden_channels, - hidden_channels, - n_heads, - p_dropout=p_dropout, - proximal_bias=proximal_bias, - proximal_init=proximal_init, - ) - ) - self.norm_layers_0.append(LayerNorm(hidden_channels)) - self.encdec_attn_layers.append( - MultiHeadAttention( - hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout - ) - ) - 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, - causal=True, - ) - ) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask, h, h_mask): - """ - x: decoder input - h: encoder output - """ - self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to( - device=x.device, dtype=x.dtype - ) - encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.self_attn_layers[i](x, x, self_attn_mask) - y = self.drop(y) - x = self.norm_layers_0[i](x + y) - - y = self.encdec_attn_layers[i](x, h, encdec_attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class MultiHeadAttention(nn.Module): - def __init__( - self, - channels, - out_channels, - n_heads, - p_dropout=0.0, - window_size=None, - heads_share=True, - 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.p_dropout = p_dropout - self.window_size = window_size - self.heads_share = heads_share - self.block_length = block_length - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - 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) - self.conv_o = nn.Conv1d(channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - 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 - ) - - nn.init.xavier_uniform_(self.conv_q.weight) - nn.init.xavier_uniform_(self.conv_k.weight) - nn.init.xavier_uniform_(self.conv_v.weight) - if proximal_init: - with torch.no_grad(): - self.conv_k.weight.copy_(self.conv_q.weight) - self.conv_k.bias.copy_(self.conv_q.bias) - - 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 / math.sqrt(self.k_channels), key.transpose(-2, -1)) - 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 / math.sqrt(self.k_channels), key_relative_embeddings - ) - scores_local = self._relative_position_to_absolute_position(rel_logits) - 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: - assert ( - t_s == t_t - ), "Local attention is only available for self-attention." - block_mask = ( - torch.ones_like(scores) - .triu(-self.block_length) - .tril(self.block_length) - ) - scores = scores.masked_fill(block_mask == 0, -1e4) - 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, - commons.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, commons.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, commons.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, commons.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, commons.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.0, - activation=None, - causal=False, - ): - 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.causal = causal - - if causal: - self.padding = self._causal_padding - else: - self.padding = self._same_padding - - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size) - self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size) - self.drop = nn.Dropout(p_dropout) - - def forward(self, x, x_mask): - x = self.conv_1(self.padding(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(self.padding(x * x_mask)) - return x * x_mask - - def _causal_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = self.kernel_size - 1 - pad_r = 0 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x - - def _same_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = (self.kernel_size - 1) // 2 - pad_r = self.kernel_size // 2 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x diff --git a/spaces/SQSora/VITS-Umamusume-voice-synthesizer/losses.py b/spaces/SQSora/VITS-Umamusume-voice-synthesizer/losses.py deleted file mode 100644 index fb22a0e834dd87edaa37bb8190eee2c3c7abe0d5..0000000000000000000000000000000000000000 --- a/spaces/SQSora/VITS-Umamusume-voice-synthesizer/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/SQSora/VITS-Umamusume-voice-synthesizer/text/ngu_dialect.py b/spaces/SQSora/VITS-Umamusume-voice-synthesizer/text/ngu_dialect.py deleted file mode 100644 index ce3e12bbf0469426872eed5f681985d3e1be9b26..0000000000000000000000000000000000000000 --- a/spaces/SQSora/VITS-Umamusume-voice-synthesizer/text/ngu_dialect.py +++ /dev/null @@ -1,30 +0,0 @@ -import re -import opencc - - -dialects = {'SZ': 'suzhou', 'WX': 'wuxi', 'CZ': 'changzhou', 'HZ': 'hangzhou', - 'SX': 'shaoxing', 'NB': 'ningbo', 'JJ': 'jingjiang', 'YX': 'yixing', - 'JD': 'jiading', 'ZR': 'zhenru', 'PH': 'pinghu', 'TX': 'tongxiang', - 'JS': 'jiashan', 'HN': 'xiashi', 'LP': 'linping', 'XS': 'xiaoshan', - 'FY': 'fuyang', 'RA': 'ruao', 'CX': 'cixi', 'SM': 'sanmen', - 'TT': 'tiantai', 'WZ': 'wenzhou', 'SC': 'suichang', 'YB': 'youbu'} - -converters = {} - -for dialect in dialects.values(): - try: - converters[dialect] = opencc.OpenCC(dialect) - except: - pass - - -def ngu_dialect_to_ipa(text, dialect): - dialect = dialects[dialect] - text = converters[dialect].convert(text).replace('-','').replace('$',' ') - text = re.sub(r'[、;:]', ',', text) - text = re.sub(r'\s*,\s*', ', ', text) - text = re.sub(r'\s*。\s*', '. ', text) - text = re.sub(r'\s*?\s*', '? ', text) - text = re.sub(r'\s*!\s*', '! ', text) - text = re.sub(r'\s*$', '', text) - return text diff --git a/spaces/Sapphire-356/Video2MC/joints_detectors/Alphapose/SPPE/src/models/layers/DUC.py b/spaces/Sapphire-356/Video2MC/joints_detectors/Alphapose/SPPE/src/models/layers/DUC.py deleted file mode 100644 index 3592661fc875dbaa7fa70e01ef49befa89569ebd..0000000000000000000000000000000000000000 --- a/spaces/Sapphire-356/Video2MC/joints_detectors/Alphapose/SPPE/src/models/layers/DUC.py +++ /dev/null @@ -1,23 +0,0 @@ -import torch.nn as nn -import torch.nn.functional as F - - -class DUC(nn.Module): - ''' - INPUT: inplanes, planes, upscale_factor - OUTPUT: (planes // 4)* ht * wd - ''' - def __init__(self, inplanes, planes, upscale_factor=2): - super(DUC, self).__init__() - self.conv = nn.Conv2d(inplanes, planes, kernel_size=3, padding=1, bias=False) - self.bn = nn.BatchNorm2d(planes) - self.relu = nn.ReLU() - - self.pixel_shuffle = nn.PixelShuffle(upscale_factor) - - def forward(self, x): - x = self.conv(x) - x = self.bn(x) - x = self.relu(x) - x = self.pixel_shuffle(x) - return x diff --git a/spaces/Sarst/VITS-Umamusume-voice-synthesizer2/text/cleaners.py b/spaces/Sarst/VITS-Umamusume-voice-synthesizer2/text/cleaners.py deleted file mode 100644 index c80e113b2b81a66134800dbdaa29c7d96a0152a7..0000000000000000000000000000000000000000 --- a/spaces/Sarst/VITS-Umamusume-voice-synthesizer2/text/cleaners.py +++ /dev/null @@ -1,146 +0,0 @@ -import re - - -def japanese_cleaners(text): - from text.japanese import japanese_to_romaji_with_accent - text = japanese_to_romaji_with_accent(text) - text = re.sub(r'([A-Za-z])$', r'\1.', text) - return text - - -def japanese_cleaners2(text): - return japanese_cleaners(text).replace('ts', 'ʦ').replace('...', '…') - - -def korean_cleaners(text): - '''Pipeline for Korean text''' - from text.korean import latin_to_hangul, number_to_hangul, divide_hangul - text = latin_to_hangul(text) - text = number_to_hangul(text) - text = divide_hangul(text) - text = re.sub(r'([\u3131-\u3163])$', r'\1.', text) - return text - - -def chinese_cleaners(text): - '''Pipeline for Chinese text''' - from text.mandarin import number_to_chinese, chinese_to_bopomofo, latin_to_bopomofo - text = number_to_chinese(text) - text = chinese_to_bopomofo(text) - text = latin_to_bopomofo(text) - text = re.sub(r'([ˉˊˇˋ˙])$', r'\1。', text) - return text - - -def zh_ja_mixture_cleaners(text): - from text.mandarin import chinese_to_romaji - from text.japanese import japanese_to_romaji_with_accent - text = re.sub(r'\[ZH\](.*?)\[ZH\]', - lambda x: chinese_to_romaji(x.group(1))+' ', text) - text = re.sub(r'\[JA\](.*?)\[JA\]', lambda x: japanese_to_romaji_with_accent( - x.group(1)).replace('ts', 'ʦ').replace('u', 'ɯ').replace('...', '…')+' ', text) - text = re.sub(r'\s+$', '', text) - text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text) - return text - - -def sanskrit_cleaners(text): - text = text.replace('॥', '।').replace('ॐ', 'ओम्') - if text[-1] != '।': - text += ' ।' - return text - - -def cjks_cleaners(text): - from text.mandarin import chinese_to_lazy_ipa - from text.japanese import japanese_to_ipa - from text.korean import korean_to_lazy_ipa - from text.sanskrit import devanagari_to_ipa - from text.english import english_to_lazy_ipa - text = re.sub(r'\[ZH\](.*?)\[ZH\]', - lambda x: chinese_to_lazy_ipa(x.group(1))+' ', text) - text = re.sub(r'\[JA\](.*?)\[JA\]', - lambda x: japanese_to_ipa(x.group(1))+' ', text) - text = re.sub(r'\[KO\](.*?)\[KO\]', - lambda x: korean_to_lazy_ipa(x.group(1))+' ', text) - text = re.sub(r'\[SA\](.*?)\[SA\]', - lambda x: devanagari_to_ipa(x.group(1))+' ', text) - text = re.sub(r'\[EN\](.*?)\[EN\]', - lambda x: english_to_lazy_ipa(x.group(1))+' ', text) - text = re.sub(r'\s+$', '', text) - text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text) - return text - - -def cjke_cleaners(text): - from text.mandarin import chinese_to_lazy_ipa - from text.japanese import japanese_to_ipa - from text.korean import korean_to_ipa - from text.english import english_to_ipa2 - text = re.sub(r'\[ZH\](.*?)\[ZH\]', lambda x: chinese_to_lazy_ipa(x.group(1)).replace( - 'ʧ', 'tʃ').replace('ʦ', 'ts').replace('ɥan', 'ɥæn')+' ', text) - text = re.sub(r'\[JA\](.*?)\[JA\]', lambda x: japanese_to_ipa(x.group(1)).replace('ʧ', 'tʃ').replace( - 'ʦ', 'ts').replace('ɥan', 'ɥæn').replace('ʥ', 'dz')+' ', text) - text = re.sub(r'\[KO\](.*?)\[KO\]', - lambda x: korean_to_ipa(x.group(1))+' ', text) - text = re.sub(r'\[EN\](.*?)\[EN\]', lambda x: english_to_ipa2(x.group(1)).replace('ɑ', 'a').replace( - 'ɔ', 'o').replace('ɛ', 'e').replace('ɪ', 'i').replace('ʊ', 'u')+' ', text) - text = re.sub(r'\s+$', '', text) - text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text) - return text - - -def cjke_cleaners2(text): - from text.mandarin import chinese_to_ipa - from text.japanese import japanese_to_ipa2 - from text.korean import korean_to_ipa - from text.english import english_to_ipa2 - text = re.sub(r'\[ZH\](.*?)\[ZH\]', - lambda x: chinese_to_ipa(x.group(1))+' ', text) - text = re.sub(r'\[JA\](.*?)\[JA\]', - lambda x: japanese_to_ipa2(x.group(1))+' ', text) - text = re.sub(r'\[KO\](.*?)\[KO\]', - lambda x: korean_to_ipa(x.group(1))+' ', text) - text = re.sub(r'\[EN\](.*?)\[EN\]', - lambda x: english_to_ipa2(x.group(1))+' ', text) - text = re.sub(r'\s+$', '', text) - text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text) - return text - - -def thai_cleaners(text): - from text.thai import num_to_thai, latin_to_thai - text = num_to_thai(text) - text = latin_to_thai(text) - return text - - -def shanghainese_cleaners(text): - from text.shanghainese import shanghainese_to_ipa - text = shanghainese_to_ipa(text) - text = re.sub(r'([^\.,!\?\-…~])$', r'\1.', text) - return text - - -def chinese_dialect_cleaners(text): - from text.mandarin import chinese_to_ipa2 - from text.japanese import japanese_to_ipa3 - from text.shanghainese import shanghainese_to_ipa - from text.cantonese import cantonese_to_ipa - from text.english import english_to_lazy_ipa2 - from text.ngu_dialect import ngu_dialect_to_ipa - text = re.sub(r'\[ZH\](.*?)\[ZH\]', - lambda x: chinese_to_ipa2(x.group(1))+' ', 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/ServerX/PorcoDiaz/utils/clonerepo_experimental.py b/spaces/ServerX/PorcoDiaz/utils/clonerepo_experimental.py deleted file mode 100644 index b0ae02648c1307562cf48033908edcf2996db5e2..0000000000000000000000000000000000000000 --- a/spaces/ServerX/PorcoDiaz/utils/clonerepo_experimental.py +++ /dev/null @@ -1,253 +0,0 @@ -import os -import subprocess -import shutil -from concurrent.futures import ThreadPoolExecutor, as_completed -from tqdm.notebook import tqdm -from pathlib import Path -import requests - -def run_script(): - def run_cmd(cmd): - process = subprocess.run(cmd, shell=True, check=True, text=True) - return process.stdout - - # Change the current directory to /content/ - os.chdir('/content/') - print("Changing dir to /content/") - - # Your function to edit the file - def edit_file(file_path): - temp_file_path = "/tmp/temp_file.py" - changes_made = False - with open(file_path, "r") as file, open(temp_file_path, "w") as temp_file: - previous_line = "" - second_previous_line = "" - for line in file: - new_line = line.replace("value=160", "value=128") - if new_line != line: - print("Replaced 'value=160' with 'value=128'") - changes_made = True - line = new_line - - new_line = line.replace("crepe hop length: 160", "crepe hop length: 128") - if new_line != line: - print("Replaced 'crepe hop length: 160' with 'crepe hop length: 128'") - changes_made = True - line = new_line - - new_line = line.replace("value=0.88", "value=0.75") - if new_line != line: - print("Replaced 'value=0.88' with 'value=0.75'") - changes_made = True - line = new_line - - if "label=i18n(\"输入源音量包络替换输出音量包络融合比例,越靠近1越使用输出包络\")" in previous_line and "value=1," in line: - new_line = line.replace("value=1,", "value=0.25,") - if new_line != line: - print("Replaced 'value=1,' with 'value=0.25,' based on the condition") - changes_made = True - line = new_line - - if "label=i18n(\"总训练轮数total_epoch\")" in previous_line and "value=20," in line: - new_line = line.replace("value=20,", "value=500,") - if new_line != line: - print("Replaced 'value=20,' with 'value=500,' based on the condition for DEFAULT EPOCH") - changes_made = True - line = new_line - - if 'choices=["pm", "harvest", "dio", "crepe", "crepe-tiny", "mangio-crepe", "mangio-crepe-tiny"], # Fork Feature. Add Crepe-Tiny' in previous_line: - if 'value="pm",' in line: - new_line = line.replace('value="pm",', 'value="mangio-crepe",') - if new_line != line: - print("Replaced 'value=\"pm\",' with 'value=\"mangio-crepe\",' based on the condition") - changes_made = True - line = new_line - - new_line = line.replace('label=i18n("输入训练文件夹路径"), value="E:\\\\语音音频+标注\\\\米津玄师\\\\src"', 'label=i18n("输入训练文件夹路径"), value="/content/dataset/"') - if new_line != line: - print("Replaced 'label=i18n(\"输入训练文件夹路径\"), value=\"E:\\\\语音音频+标注\\\\米津玄师\\\\src\"' with 'label=i18n(\"输入训练文件夹路径\"), value=\"/content/dataset/\"'") - changes_made = True - line = new_line - - if 'label=i18n("是否仅保存最新的ckpt文件以节省硬盘空间"),' in second_previous_line: - if 'value=i18n("否"),' in line: - new_line = line.replace('value=i18n("否"),', 'value=i18n("是"),') - if new_line != line: - print("Replaced 'value=i18n(\"否\"),' with 'value=i18n(\"是\"),' based on the condition for SAVE ONLY LATEST") - changes_made = True - line = new_line - - if 'label=i18n("是否在每次保存时间点将最终小模型保存至weights文件夹"),' in second_previous_line: - if 'value=i18n("否"),' in line: - new_line = line.replace('value=i18n("否"),', 'value=i18n("是"),') - if new_line != line: - print("Replaced 'value=i18n(\"否\"),' with 'value=i18n(\"是\"),' based on the condition for SAVE SMALL WEIGHTS") - changes_made = True - line = new_line - - temp_file.write(line) - second_previous_line = previous_line - previous_line = line - - # After finished, we replace the original file with the temp one - import shutil - shutil.move(temp_file_path, file_path) - - if changes_made: - print("Changes made and file saved successfully.") - else: - print("No changes were needed.") - - # Define the repo path - repo_path = '/content/Applio-RVC-Fork' - - def copy_all_files_in_directory(src_dir, dest_dir): - # Iterate over all files in source directory - for item in Path(src_dir).glob('*'): - if item.is_file(): - # Copy each file to destination directory - shutil.copy(item, dest_dir) - else: - # If it's a directory, make a new directory in the destination and copy the files recursively - new_dest = Path(dest_dir) / item.name - new_dest.mkdir(exist_ok=True) - copy_all_files_in_directory(str(item), str(new_dest)) - - def clone_and_copy_repo(repo_path): - # New repository link - new_repo_link = "https://github.com/IAHispano/Applio-RVC-Fork/" - # Temporary path to clone the repository - temp_repo_path = "/content/temp_Applio-RVC-Fork" - # New folder name - new_folder_name = "Applio-RVC-Fork" - - # Clone the latest code from the new repository to a temporary location - run_cmd(f"git clone {new_repo_link} {temp_repo_path}") - os.chdir(temp_repo_path) - - run_cmd(f"git checkout 3fa4dad3d8961e5ca2522e9e12c0b4ddb71ad402") - run_cmd(f"git checkout f9e606c279cb49420597519b0a83b92be81e42e4") - run_cmd(f"git checkout 9e305588844c5442d58add1061b29beeca89d679") - run_cmd(f"git checkout bf92dc1eb54b4f28d6396a4d1820a25896cc9af8") - run_cmd(f"git checkout c3810e197d3cb98039973b2f723edf967ecd9e61") - run_cmd(f"git checkout a33159efd134c2413b0afe26a76b7dc87926d2de") - run_cmd(f"git checkout 24e251fb62c662e39ac5cf9253cc65deb9be94ec") - run_cmd(f"git checkout ad5667d3017e93232dba85969cddac1322ba2902") - run_cmd(f"git checkout ce9715392cf52dd5a0e18e00d1b5e408f08dbf27") - run_cmd(f"git checkout 7c7da3f2ac68f3bd8f3ad5ca5c700f18ab9f90eb") - run_cmd(f"git checkout 4ac395eab101955e8960b50d772c26f592161764") - run_cmd(f"git checkout b15b358702294c7375761584e5276c811ffab5e8") - run_cmd(f"git checkout 1501793dc490982db9aca84a50647764caa66e51") - run_cmd(f"git checkout 21f7faf57219c75e6ba837062350391a803e9ae2") - run_cmd(f"git checkout b5eb689fbc409b49f065a431817f822f554cebe7") - run_cmd(f"git checkout 7e02fae1ebf24cb151bf6cbe787d06734aa65862") - run_cmd(f"git checkout 6aea5ea18ed0b9a1e03fa5d268d6bc3c616672a9") - run_cmd(f"git checkout f0f9b25717e59116473fb42bd7f9252cfc32b398") - run_cmd(f"git checkout b394de424088a81fc081224bc27338a8651ad3b2") - run_cmd(f"git checkout f1999406a88b80c965d2082340f5ea2bfa9ab67a") - run_cmd(f"git checkout d98a0fa8dc715308dfc73eac5c553b69c6ee072b") - run_cmd(f"git checkout d73267a415fb0eba98477afa43ef71ffd82a7157") - run_cmd(f"git checkout 1a03d01356ae79179e1fb8d8915dc9cc79925742") - run_cmd(f"git checkout 81497bb3115e92c754300c9b3992df428886a3e9") - run_cmd(f"git checkout c5af1f8edcf79cb70f065c0110e279e78e48caf9") - run_cmd(f"git checkout cdb3c90109387fa4dfa92f53c3864c71170ffc77") - - # Edit the file here, before copying - #edit_file(f"{temp_repo_path}/infer-web.py") - - # Copy all files from the cloned repository to the existing path - copy_all_files_in_directory(temp_repo_path, repo_path) - print(f"Copying all {new_folder_name} files from GitHub.") - - # Change working directory back to /content/ - os.chdir('/content/') - print("Changed path back to /content/") - - # Remove the temporary cloned repository - shutil.rmtree(temp_repo_path) - - # Call the function - clone_and_copy_repo(repo_path) - - # Download the credentials file for RVC archive sheet - os.makedirs('/content/Applio-RVC-Fork/stats/', exist_ok=True) - run_cmd("wget -q https://cdn.discordapp.com/attachments/945486970883285045/1114717554481569802/peppy-generator-388800-07722f17a188.json -O /content/Applio-RVC-Fork/stats/peppy-generator-388800-07722f17a188.json") - - # Forcefully delete any existing torchcrepe dependencies downloaded from an earlier run just in case - shutil.rmtree('/content/Applio-RVC-Fork/torchcrepe', ignore_errors=True) - shutil.rmtree('/content/torchcrepe', ignore_errors=True) - - # Download the torchcrepe folder from the maxrmorrison/torchcrepe repository - run_cmd("git clone https://github.com/maxrmorrison/torchcrepe.git") - shutil.move('/content/torchcrepe/torchcrepe', '/content/Applio-RVC-Fork/') - shutil.rmtree('/content/torchcrepe', ignore_errors=True) # Delete the torchcrepe repository folder - - # Change the current directory to /content/Applio-RVC-Fork - os.chdir('/content/Applio-RVC-Fork') - os.makedirs('pretrained', exist_ok=True) - os.makedirs('uvr5_weights', exist_ok=True) - -def download_file(url, filepath): - response = requests.get(url, stream=True) - response.raise_for_status() - - with open(filepath, "wb") as file: - for chunk in response.iter_content(chunk_size=8192): - if chunk: - file.write(chunk) - -def download_pretrained_models(): - pretrained_models = { - "pretrained": [ - "D40k.pth", - "G40k.pth", - "f0D40k.pth", - "f0G40k.pth" - ], - "pretrained_v2": [ - "D40k.pth", - "G40k.pth", - "f0D40k.pth", - "f0G40k.pth", - "f0G48k.pth", - "f0D48k.pth" - ], - "uvr5_weights": [ - "HP2-人声vocals+非人声instrumentals.pth", - "HP5-主旋律人声vocals+其他instrumentals.pth", - "VR-DeEchoNormal.pth", - "VR-DeEchoDeReverb.pth", - "VR-DeEchoAggressive.pth", - "HP5_only_main_vocal.pth", - "HP3_all_vocals.pth", - "HP2_all_vocals.pth" - ] - } - part2 = "I" - base_url = "https://huggingface.co/lj1995/VoiceConversionWebU" + part2 + "/resolve/main/" - base_path = "/content/Applio-RVC-Fork/" - base_pathm = base_path - - # Calculate total number of files to download - total_files = sum(len(files) for files in pretrained_models.values()) + 1 # +1 for hubert_base.pt - - with tqdm(total=total_files, desc="Downloading files") as pbar: - for folder, models in pretrained_models.items(): - folder_path = os.path.join(base_path, folder) - os.makedirs(folder_path, exist_ok=True) - for model in models: - url = base_url + folder + "/" + model - filepath = os.path.join(folder_path, model) - download_file(url, filepath) - pbar.update() - - # Download hubert_base.pt to the base path - hubert_url = base_url + "hubert_base.pt" - hubert_filepath = os.path.join(base_pathm, "hubert_base.pt") - download_file(hubert_url, hubert_filepath) - pbar.update() -def clone_repository(run_download): - with ThreadPoolExecutor(max_workers=2) as executor: - executor.submit(run_script) - if run_download: - executor.submit(download_pretrained_models) diff --git a/spaces/Skyler123/TangGPT/modules/utils.py b/spaces/Skyler123/TangGPT/modules/utils.py deleted file mode 100644 index 23f47d688d9690c6c68ccacc765108ce68d62b76..0000000000000000000000000000000000000000 --- a/spaces/Skyler123/TangGPT/modules/utils.py +++ /dev/null @@ -1,536 +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 - -if TYPE_CHECKING: - from typing import TypedDict - - class DataframeData(TypedDict): - headers: List[str] - data: List[List[str | int | bool]] - - -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 = [] - for non_code, code in zip(non_code_parts, code_blocks + [""]): - if non_code.strip(): - non_code = normalize_markdown(non_code) - if inline_code_pattern.search(non_code): - result.append(markdown(non_code, extensions=["tables"])) - else: - result.append(mdtex2html.convert(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) - result += ALREADY_CONVERTED_MARK - return result - - -def convert_asis(userinput): - return ( - f'

    {html.escape(userinput)}

    ' - + ALREADY_CONVERTED_MARK - ) - - -def detect_converted_mark(userinput): - if userinput.endswith(ALREADY_CONVERTED_MARK): - return True - else: - return False - - -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 construct_token_message(tokens: List[int]): - token_sum = 0 - for i in range(len(tokens)): - token_sum += sum(tokens[: i + 1]) - return f"Token 计数: {sum(tokens)},本次对话累计消耗了 {token_sum} tokens" - - -def delete_first_conversation(history, previous_token_count): - if history: - del history[:2] - del previous_token_count[0] - return ( - history, - previous_token_count, - construct_token_message(previous_token_count), - ) - - -def delete_last_conversation(chatbot, history, previous_token_count): - if len(chatbot) > 0 and standard_error_msg in chatbot[-1][1]: - logging.info("由于包含报错信息,只删除chatbot记录") - chatbot.pop() - return chatbot, history - if len(history) > 0: - logging.info("删除了一组对话历史") - history.pop() - history.pop() - if len(chatbot) > 0: - logging.info("删除了一组chatbot对话") - chatbot.pop() - if len(previous_token_count) > 0: - logging.info("删除了一组对话的token计数记录") - previous_token_count.pop() - return ( - chatbot, - history, - previous_token_count, - construct_token_message(previous_token_count), - ) - - -def save_file(filename, system, history, chatbot, user_name): - logging.info(f"{user_name} 保存对话历史中……") - os.makedirs(HISTORY_DIR / user_name, exist_ok=True) - if filename.endswith(".json"): - json_s = {"system": system, "history": history, "chatbot": chatbot} - print(json_s) - with open(os.path.join(HISTORY_DIR / user_name, filename), "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.info(f"{user_name} 保存对话历史完毕") - return os.path.join(HISTORY_DIR / user_name, filename) - - -def save_chat_history(filename, system, history, chatbot, user_name): - if filename == "": - return - if not filename.endswith(".json"): - filename += ".json" - return save_file(filename, system, history, chatbot, user_name) - - -def export_markdown(filename, system, history, chatbot, user_name): - if filename == "": - return - if not filename.endswith(".md"): - filename += ".md" - return save_file(filename, system, history, chatbot, user_name) - - -def load_chat_history(filename, system, history, chatbot, user_name): - logging.info(f"{user_name} 加载对话历史中……") - if type(filename) != str: - filename = filename.name - try: - with open(os.path.join(HISTORY_DIR / user_name, filename), "r") as f: - json_s = json.load(f) - try: - if type(json_s["history"][0]) == str: - logging.info("历史记录格式为旧版,正在转换……") - new_history = [] - for index, item in enumerate(json_s["history"]): - if index % 2 == 0: - new_history.append(construct_user(item)) - else: - new_history.append(construct_assistant(item)) - json_s["history"] = new_history - logging.info(new_history) - except: - # 没有对话历史 - pass - logging.info(f"{user_name} 加载对话历史完毕") - return filename, json_s["system"], json_s["history"], json_s["chatbot"] - except FileNotFoundError: - logging.info(f"{user_name} 没有找到对话历史文件,不执行任何操作") - return filename, system, history, chatbot - - -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.info(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.info(f"从用户 {user_name} 中获取历史记录文件名列表") - return get_file_names(HISTORY_DIR / user_name, plain) - - -def load_template(filename, mode=0): - logging.info(f"加载模板文件{filename},模式为{mode}(0为返回字典和下拉菜单,1为返回下拉菜单,2为返回字典)") - lines = [] - logging.info("Loading template...") - 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.info("获取模板文件名列表") - return get_file_names(TEMPLATES_DIR, plain, filetypes=[".csv", "json"]) - - -def get_template_content(templates, selection, original_system_prompt): - logging.info(f"应用模板中,选择为{selection},原始系统提示为{original_system_prompt}") - try: - return templates[selection] - except: - return original_system_prompt - - -def reset_state(): - logging.info("重置状态") - return [], [], [], construct_token_message([0]) - - -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 ( - f"获取IP地理位置失败,因为达到了检测IP的速率限制。聊天功能可能仍然可用。" - ) - else: - return f"获取IP地理位置失败。原因:{data['reason']}。你仍然可以使用聊天功能。" - else: - country = data["country_name"] - if country == "China": - text = "**您的IP区域:中国。请立即检查代理设置,在不受支持的地区使用API可能导致账号被封禁。**" - else: - text = f"您的IP区域:{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=True), gr.Button.update(visible=False) - - -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=True), - gr.Button.update(visible=False), - ) - - - -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__} - •  -Commit: {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): - 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 += row_string + "\n" - 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 += f"Sheet: {sheet_name}\n" - - # 处理当前工作表并添加到结果字符串 - result += sheet_to_string(sheet_data) - - # 在不同工作表之间添加分隔符 - result += "\n" + ("-" * 20) + "\n\n" - - return result diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_magic_terminal.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_magic_terminal.py deleted file mode 100644 index 5dfa0f0ed652e637dab0eee8eb9443483405cd19..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_magic_terminal.py +++ /dev/null @@ -1,216 +0,0 @@ -"""Tests for various magic functions specific to the terminal frontend.""" - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- - -import sys -from io import StringIO -from unittest import TestCase - -from IPython.testing import tools as tt -#----------------------------------------------------------------------------- -# Test functions begin -#----------------------------------------------------------------------------- - - -MINIMAL_LAZY_MAGIC = """ -from IPython.core.magic import ( - Magics, - magics_class, - line_magic, - cell_magic, -) - - -@magics_class -class LazyMagics(Magics): - @line_magic - def lazy_line(self, line): - print("Lazy Line") - - @cell_magic - def lazy_cell(self, line, cell): - print("Lazy Cell") - - -def load_ipython_extension(ipython): - ipython.register_magics(LazyMagics) -""" - -def check_cpaste(code, should_fail=False): - """Execute code via 'cpaste' and ensure it was executed, unless - should_fail is set. - """ - ip.user_ns['code_ran'] = False - - src = StringIO() - src.write(code) - src.write('\n--\n') - src.seek(0) - - stdin_save = sys.stdin - sys.stdin = src - - try: - context = tt.AssertPrints if should_fail else tt.AssertNotPrints - with context("Traceback (most recent call last)"): - ip.run_line_magic("cpaste", "") - - if not should_fail: - assert ip.user_ns['code_ran'], "%r failed" % code - finally: - sys.stdin = stdin_save - -def test_cpaste(): - """Test cpaste magic""" - - def runf(): - """Marker function: sets a flag when executed. - """ - ip.user_ns['code_ran'] = True - return 'runf' # return string so '+ runf()' doesn't result in success - - tests = {'pass': ["runf()", - "In [1]: runf()", - "In [1]: if 1:\n ...: runf()", - "> > > runf()", - ">>> runf()", - " >>> runf()", - ], - - 'fail': ["1 + runf()", - "++ runf()", - ]} - - ip.user_ns['runf'] = runf - - for code in tests['pass']: - check_cpaste(code) - - for code in tests['fail']: - check_cpaste(code, should_fail=True) - - - -class PasteTestCase(TestCase): - """Multiple tests for clipboard pasting""" - - def paste(self, txt, flags='-q'): - """Paste input text, by default in quiet mode""" - ip.hooks.clipboard_get = lambda: txt - ip.run_line_magic("paste", flags) - - def setUp(self): - # Inject fake clipboard hook but save original so we can restore it later - self.original_clip = ip.hooks.clipboard_get - - def tearDown(self): - # Restore original hook - ip.hooks.clipboard_get = self.original_clip - - def test_paste(self): - ip.user_ns.pop("x", None) - self.paste("x = 1") - self.assertEqual(ip.user_ns["x"], 1) - ip.user_ns.pop("x") - - def test_paste_pyprompt(self): - ip.user_ns.pop("x", None) - self.paste(">>> x=2") - self.assertEqual(ip.user_ns["x"], 2) - ip.user_ns.pop("x") - - def test_paste_py_multi(self): - self.paste( - """ - >>> x = [1,2,3] - >>> y = [] - >>> for i in x: - ... y.append(i**2) - ... - """ - ) - self.assertEqual(ip.user_ns["x"], [1, 2, 3]) - self.assertEqual(ip.user_ns["y"], [1, 4, 9]) - - def test_paste_py_multi_r(self): - "Now, test that self.paste -r works" - self.test_paste_py_multi() - self.assertEqual(ip.user_ns.pop("x"), [1, 2, 3]) - self.assertEqual(ip.user_ns.pop("y"), [1, 4, 9]) - self.assertFalse("x" in ip.user_ns) - ip.run_line_magic("paste", "-r") - self.assertEqual(ip.user_ns["x"], [1, 2, 3]) - self.assertEqual(ip.user_ns["y"], [1, 4, 9]) - - def test_paste_email(self): - "Test pasting of email-quoted contents" - self.paste( - """\ - >> def foo(x): - >> return x + 1 - >> xx = foo(1.1)""" - ) - self.assertEqual(ip.user_ns["xx"], 2.1) - - def test_paste_email2(self): - "Email again; some programs add a space also at each quoting level" - self.paste( - """\ - > > def foo(x): - > > return x + 1 - > > yy = foo(2.1) """ - ) - self.assertEqual(ip.user_ns["yy"], 3.1) - - def test_paste_email_py(self): - "Email quoting of interactive input" - self.paste( - """\ - >> >>> def f(x): - >> ... return x+1 - >> ... - >> >>> zz = f(2.5) """ - ) - self.assertEqual(ip.user_ns["zz"], 3.5) - - def test_paste_echo(self): - "Also test self.paste echoing, by temporarily faking the writer" - w = StringIO() - old_write = sys.stdout.write - sys.stdout.write = w.write - code = """ - a = 100 - b = 200""" - try: - self.paste(code,'') - out = w.getvalue() - finally: - sys.stdout.write = old_write - self.assertEqual(ip.user_ns["a"], 100) - self.assertEqual(ip.user_ns["b"], 200) - assert out == code + "\n## -- End pasted text --\n" - - def test_paste_leading_commas(self): - "Test multiline strings with leading commas" - tm = ip.magics_manager.registry['TerminalMagics'] - s = '''\ -a = """ -,1,2,3 -"""''' - ip.user_ns.pop("foo", None) - tm.store_or_execute(s, "foo") - self.assertIn("foo", ip.user_ns) - - def test_paste_trailing_question(self): - "Test pasting sources with trailing question marks" - tm = ip.magics_manager.registry['TerminalMagics'] - s = '''\ -def funcfoo(): - if True: #am i true? - return 'fooresult' -''' - ip.user_ns.pop('funcfoo', None) - self.paste(s) - self.assertEqual(ip.user_ns["funcfoo"](), "fooresult") diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_paths.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_paths.py deleted file mode 100644 index 86367b61ecbc591ef9c41a77462ce53442dfea7c..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/core/tests/test_paths.py +++ /dev/null @@ -1,200 +0,0 @@ -import errno -import os -import shutil -import tempfile -import warnings -from unittest.mock import patch - -from tempfile import TemporaryDirectory -from testpath import assert_isdir, assert_isfile, modified_env - -from IPython import paths -from IPython.testing.decorators import skip_win32 - -TMP_TEST_DIR = os.path.realpath(tempfile.mkdtemp()) -HOME_TEST_DIR = os.path.join(TMP_TEST_DIR, "home_test_dir") -XDG_TEST_DIR = os.path.join(HOME_TEST_DIR, "xdg_test_dir") -XDG_CACHE_DIR = os.path.join(HOME_TEST_DIR, "xdg_cache_dir") -IP_TEST_DIR = os.path.join(HOME_TEST_DIR,'.ipython') - -def setup_module(): - """Setup testenvironment for the module: - - - Adds dummy home dir tree - """ - # Do not mask exceptions here. In particular, catching WindowsError is a - # problem because that exception is only defined on Windows... - os.makedirs(IP_TEST_DIR) - os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython')) - os.makedirs(os.path.join(XDG_CACHE_DIR, 'ipython')) - - -def teardown_module(): - """Teardown testenvironment for the module: - - - Remove dummy home dir tree - """ - # Note: we remove the parent test dir, which is the root of all test - # subdirs we may have created. Use shutil instead of os.removedirs, so - # that non-empty directories are all recursively removed. - shutil.rmtree(TMP_TEST_DIR) - -def patch_get_home_dir(dirpath): - return patch.object(paths, 'get_home_dir', return_value=dirpath) - - -def test_get_ipython_dir_1(): - """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions.""" - env_ipdir = os.path.join("someplace", ".ipython") - with patch.object(paths, '_writable_dir', return_value=True), \ - modified_env({'IPYTHONDIR': env_ipdir}): - ipdir = paths.get_ipython_dir() - - assert ipdir == env_ipdir - -def test_get_ipython_dir_2(): - """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions.""" - with patch_get_home_dir('someplace'), \ - patch.object(paths, 'get_xdg_dir', return_value=None), \ - patch.object(paths, '_writable_dir', return_value=True), \ - patch('os.name', "posix"), \ - modified_env({'IPYTHON_DIR': None, - 'IPYTHONDIR': None, - 'XDG_CONFIG_HOME': None - }): - ipdir = paths.get_ipython_dir() - - assert ipdir == os.path.join("someplace", ".ipython") - -def test_get_ipython_dir_3(): - """test_get_ipython_dir_3, use XDG if defined and exists, and .ipython doesn't exist.""" - tmphome = TemporaryDirectory() - try: - with patch_get_home_dir(tmphome.name), \ - patch('os.name', 'posix'), \ - modified_env({ - 'IPYTHON_DIR': None, - 'IPYTHONDIR': None, - 'XDG_CONFIG_HOME': XDG_TEST_DIR, - }), warnings.catch_warnings(record=True) as w: - ipdir = paths.get_ipython_dir() - - assert ipdir == os.path.join(tmphome.name, XDG_TEST_DIR, "ipython") - assert len(w) == 0 - finally: - tmphome.cleanup() - -def test_get_ipython_dir_4(): - """test_get_ipython_dir_4, warn if XDG and home both exist.""" - with patch_get_home_dir(HOME_TEST_DIR), \ - patch('os.name', 'posix'): - try: - os.mkdir(os.path.join(XDG_TEST_DIR, 'ipython')) - except OSError as e: - if e.errno != errno.EEXIST: - raise - - - with modified_env({ - 'IPYTHON_DIR': None, - 'IPYTHONDIR': None, - 'XDG_CONFIG_HOME': XDG_TEST_DIR, - }), warnings.catch_warnings(record=True) as w: - ipdir = paths.get_ipython_dir() - - assert len(w) == 1 - assert "Ignoring" in str(w[0]) - - -def test_get_ipython_dir_5(): - """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist.""" - with patch_get_home_dir(HOME_TEST_DIR), \ - patch('os.name', 'posix'): - try: - os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython')) - except OSError as e: - if e.errno != errno.ENOENT: - raise - - with modified_env({ - 'IPYTHON_DIR': None, - 'IPYTHONDIR': None, - 'XDG_CONFIG_HOME': XDG_TEST_DIR, - }): - ipdir = paths.get_ipython_dir() - - assert ipdir == IP_TEST_DIR - -def test_get_ipython_dir_6(): - """test_get_ipython_dir_6, use home over XDG if defined and neither exist.""" - xdg = os.path.join(HOME_TEST_DIR, 'somexdg') - os.mkdir(xdg) - shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython')) - print(paths._writable_dir) - with patch_get_home_dir(HOME_TEST_DIR), \ - patch.object(paths, 'get_xdg_dir', return_value=xdg), \ - patch('os.name', 'posix'), \ - modified_env({ - 'IPYTHON_DIR': None, - 'IPYTHONDIR': None, - 'XDG_CONFIG_HOME': None, - }), warnings.catch_warnings(record=True) as w: - ipdir = paths.get_ipython_dir() - - assert ipdir == os.path.join(HOME_TEST_DIR, ".ipython") - assert len(w) == 0 - -def test_get_ipython_dir_7(): - """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR""" - home_dir = os.path.normpath(os.path.expanduser('~')) - with modified_env({'IPYTHONDIR': os.path.join('~', 'somewhere')}), \ - patch.object(paths, '_writable_dir', return_value=True): - ipdir = paths.get_ipython_dir() - assert ipdir == os.path.join(home_dir, "somewhere") - - -@skip_win32 -def test_get_ipython_dir_8(): - """test_get_ipython_dir_8, test / home directory""" - if not os.access("/", os.W_OK): - # test only when HOME directory actually writable - return - - with patch.object(paths, "_writable_dir", lambda path: bool(path)), patch.object( - paths, "get_xdg_dir", return_value=None - ), modified_env( - { - "IPYTHON_DIR": None, - "IPYTHONDIR": None, - "HOME": "/", - } - ): - assert paths.get_ipython_dir() == "/.ipython" - - -def test_get_ipython_cache_dir(): - with modified_env({'HOME': HOME_TEST_DIR}): - if os.name == "posix": - # test default - os.makedirs(os.path.join(HOME_TEST_DIR, ".cache")) - with modified_env({'XDG_CACHE_HOME': None}): - ipdir = paths.get_ipython_cache_dir() - assert os.path.join(HOME_TEST_DIR, ".cache", "ipython") == ipdir - assert_isdir(ipdir) - - # test env override - with modified_env({"XDG_CACHE_HOME": XDG_CACHE_DIR}): - ipdir = paths.get_ipython_cache_dir() - assert_isdir(ipdir) - assert ipdir == os.path.join(XDG_CACHE_DIR, "ipython") - else: - assert paths.get_ipython_cache_dir() == paths.get_ipython_dir() - -def test_get_ipython_package_dir(): - ipdir = paths.get_ipython_package_dir() - assert_isdir(ipdir) - - -def test_get_ipython_module_path(): - ipapp_path = paths.get_ipython_module_path('IPython.terminal.ipapp') - assert_isfile(ipapp_path) diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/utils/_process_common.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/utils/_process_common.py deleted file mode 100644 index 2a0b828839bcc32d535cffc7a286a70b8098babe..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/IPython/utils/_process_common.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Common utilities for the various process_* implementations. - -This file is only meant to be imported by the platform-specific implementations -of subprocess utilities, and it contains tools that are common to all of them. -""" - -#----------------------------------------------------------------------------- -# Copyright (C) 2010-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- -import subprocess -import shlex -import sys -import os - -from IPython.utils import py3compat - -#----------------------------------------------------------------------------- -# Function definitions -#----------------------------------------------------------------------------- - -def read_no_interrupt(p): - """Read from a pipe ignoring EINTR errors. - - This is necessary because when reading from pipes with GUI event loops - running in the background, often interrupts are raised that stop the - command from completing.""" - import errno - - try: - return p.read() - except IOError as err: - if err.errno != errno.EINTR: - raise - - -def process_handler(cmd, callback, stderr=subprocess.PIPE): - """Open a command in a shell subprocess and execute a callback. - - This function provides common scaffolding for creating subprocess.Popen() - calls. It creates a Popen object and then calls the callback with it. - - Parameters - ---------- - cmd : str or list - A command to be executed by the system, using :class:`subprocess.Popen`. - If a string is passed, it will be run in the system shell. If a list is - passed, it will be used directly as arguments. - callback : callable - A one-argument function that will be called with the Popen object. - stderr : file descriptor number, optional - By default this is set to ``subprocess.PIPE``, but you can also pass the - value ``subprocess.STDOUT`` to force the subprocess' stderr to go into - the same file descriptor as its stdout. This is useful to read stdout - and stderr combined in the order they are generated. - - Returns - ------- - The return value of the provided callback is returned. - """ - sys.stdout.flush() - sys.stderr.flush() - # On win32, close_fds can't be true when using pipes for stdin/out/err - close_fds = sys.platform != 'win32' - # Determine if cmd should be run with system shell. - shell = isinstance(cmd, str) - # On POSIX systems run shell commands with user-preferred shell. - executable = None - if shell and os.name == 'posix' and 'SHELL' in os.environ: - executable = os.environ['SHELL'] - p = subprocess.Popen(cmd, shell=shell, - executable=executable, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=stderr, - close_fds=close_fds) - - try: - out = callback(p) - except KeyboardInterrupt: - print('^C') - sys.stdout.flush() - sys.stderr.flush() - out = None - finally: - # Make really sure that we don't leave processes behind, in case the - # call above raises an exception - # We start by assuming the subprocess finished (to avoid NameErrors - # later depending on the path taken) - if p.returncode is None: - try: - p.terminate() - p.poll() - except OSError: - pass - # One last try on our way out - if p.returncode is None: - try: - p.kill() - except OSError: - pass - - return out - - -def getoutput(cmd): - """Run a command and return its stdout/stderr as a string. - - Parameters - ---------- - cmd : str or list - A command to be executed in the system shell. - - Returns - ------- - output : str - A string containing the combination of stdout and stderr from the - subprocess, in whatever order the subprocess originally wrote to its - file descriptors (so the order of the information in this string is the - correct order as would be seen if running the command in a terminal). - """ - out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT) - if out is None: - return '' - return py3compat.decode(out) - - -def getoutputerror(cmd): - """Return (standard output, standard error) of executing cmd in a shell. - - Accepts the same arguments as os.system(). - - Parameters - ---------- - cmd : str or list - A command to be executed in the system shell. - - Returns - ------- - stdout : str - stderr : str - """ - return get_output_error_code(cmd)[:2] - -def get_output_error_code(cmd): - """Return (standard output, standard error, return code) of executing cmd - in a shell. - - Accepts the same arguments as os.system(). - - Parameters - ---------- - cmd : str or list - A command to be executed in the system shell. - - Returns - ------- - stdout : str - stderr : str - returncode: int - """ - - out_err, p = process_handler(cmd, lambda p: (p.communicate(), p)) - if out_err is None: - return '', '', p.returncode - out, err = out_err - return py3compat.decode(out), py3compat.decode(err), p.returncode - -def arg_split(s, posix=False, strict=True): - """Split a command line's arguments in a shell-like manner. - - This is a modified version of the standard library's shlex.split() - function, but with a default of posix=False for splitting, so that quotes - in inputs are respected. - - if strict=False, then any errors shlex.split would raise will result in the - unparsed remainder being the last element of the list, rather than raising. - This is because we sometimes use arg_split to parse things other than - command-line args. - """ - - lex = shlex.shlex(s, posix=posix) - lex.whitespace_split = True - # Extract tokens, ensuring that things like leaving open quotes - # does not cause this to raise. This is important, because we - # sometimes pass Python source through this (e.g. %timeit f(" ")), - # and it shouldn't raise an exception. - # It may be a bad idea to parse things that are not command-line args - # through this function, but we do, so let's be safe about it. - lex.commenters='' #fix for GH-1269 - tokens = [] - while True: - try: - tokens.append(next(lex)) - except StopIteration: - break - except ValueError: - if strict: - raise - # couldn't parse, get remaining blob as last token - tokens.append(lex.token) - break - - return tokens diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/_pydev_runfiles/__init__.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/_pydev_runfiles/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_frame_utils.py b/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_frame_utils.py deleted file mode 100644 index f079757a6c206651b771e153ceda864f726e90ea..0000000000000000000000000000000000000000 --- a/spaces/SungBeom/chatwine-korean/.venv/Lib/site-packages/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_frame_utils.py +++ /dev/null @@ -1,434 +0,0 @@ -from _pydevd_bundle.pydevd_constants import EXCEPTION_TYPE_USER_UNHANDLED, EXCEPTION_TYPE_UNHANDLED, \ - IS_PY311_OR_GREATER -from _pydev_bundle import pydev_log -import itertools -from typing import Any, Dict - - -class Frame(object): - - def __init__( - self, - f_back, - f_fileno, - f_code, - f_locals, - f_globals=None, - f_trace=None): - self.f_back = f_back - self.f_lineno = f_fileno - self.f_code = f_code - self.f_locals = f_locals - self.f_globals = f_globals - self.f_trace = f_trace - - if self.f_globals is None: - self.f_globals = {} - - -class FCode(object): - - def __init__(self, name, filename): - self.co_name = name - self.co_filename = filename - self.co_firstlineno = 1 - self.co_flags = 0 - - -def add_exception_to_frame(frame, exception_info): - frame.f_locals['__exception__'] = exception_info - - -def remove_exception_from_frame(frame): - frame.f_locals.pop('__exception__', None) - - -FILES_WITH_IMPORT_HOOKS = ['pydev_monkey_qt.py', 'pydev_import_hook.py'] - - -def just_raised(trace): - if trace is None: - return False - return trace.tb_next is None - - -def ignore_exception_trace(trace): - while trace is not None: - filename = trace.tb_frame.f_code.co_filename - if filename in ( - '', ''): - # Do not stop on inner exceptions in py3 while importing - return True - - # ImportError should appear in a user's code, not inside debugger - for file in FILES_WITH_IMPORT_HOOKS: - if filename.endswith(file): - return True - - trace = trace.tb_next - - return False - - -def cached_call(obj, func, *args): - cached_name = '_cached_' + func.__name__ - if not hasattr(obj, cached_name): - setattr(obj, cached_name, func(*args)) - - return getattr(obj, cached_name) - - -class _LineColInfo: - - def __init__(self, lineno, end_lineno, colno, end_colno): - self.lineno = lineno - self.end_lineno = end_lineno - self.colno = colno - self.end_colno = end_colno - - def map_columns_to_line(self, original_line: str): - ''' - The columns internally are actually based on bytes. - - Also, the position isn't always the ideal one as the start may not be - what we want (if the user has many subscripts in the line the start - will always be the same and only the end would change). - For more details see: - https://github.com/microsoft/debugpy/issues/1099#issuecomment-1303403995 - - So, this function maps the start/end columns to the position to be shown in the editor. - ''' - colno = _utf8_byte_offset_to_character_offset(original_line, self.colno) - end_colno = _utf8_byte_offset_to_character_offset(original_line, self.end_colno) - - if self.lineno == self.end_lineno: - try: - ret = _extract_caret_anchors_in_bytes_from_line_segment( - original_line[colno:end_colno] - ) - if ret is not None: - return ( - _utf8_byte_offset_to_character_offset(original_line, ret[0] + self.colno), - _utf8_byte_offset_to_character_offset(original_line, ret[1] + self.colno) - ) - except Exception: - pass # Suppress exception - - return colno, end_colno - - -_utf8_with_2_bytes = 0x80 -_utf8_with_3_bytes = 0x800 -_utf8_with_4_bytes = 0x10000 - - -def _utf8_byte_offset_to_character_offset(s: str, offset: int): - byte_offset = 0 - char_offset = 0 - - for char_offset, character in enumerate(s): - byte_offset += 1 - - codepoint = ord(character) - - if codepoint >= _utf8_with_4_bytes: - byte_offset += 3 - - elif codepoint >= _utf8_with_3_bytes: - byte_offset += 2 - - elif codepoint >= _utf8_with_2_bytes: - byte_offset += 1 - - if byte_offset > offset: - break - else: - char_offset += 1 - - return char_offset - - -# Based on traceback._extract_caret_anchors_in_bytes_from_line_segment (Python 3.11.0) -def _extract_caret_anchors_in_bytes_from_line_segment(segment: str): - import ast - - try: - segment = segment.encode('utf-8') - except UnicodeEncodeError: - return None - try: - tree = ast.parse(segment) - except SyntaxError: - return None - - if len(tree.body) != 1: - return None - - statement = tree.body[0] - if isinstance(statement, ast.Expr): - expr = statement.value - if isinstance(expr, ast.BinOp): - operator_str = segment[expr.left.end_col_offset:expr.right.col_offset] - operator_offset = len(operator_str) - len(operator_str.lstrip()) - - left_anchor = expr.left.end_col_offset + operator_offset - right_anchor = left_anchor + 1 - if ( - operator_offset + 1 < len(operator_str) - and not operator_str[operator_offset + 1] == ord(b' ') - ): - right_anchor += 1 - return left_anchor, right_anchor - if isinstance(expr, ast.Subscript): - return expr.value.end_col_offset, expr.slice.end_col_offset + 1 - - return None - - -class FramesList(object): - - def __init__(self): - self._frames = [] - - # If available, the line number for the frame will be gotten from this dict, - # otherwise frame.f_lineno will be used (needed for unhandled exceptions as - # the place where we report may be different from the place where it's raised). - self.frame_id_to_lineno = {} - self.frame_id_to_line_col_info: Dict[Any, _LineColInfo] = {} - - self.exc_type = None - self.exc_desc = None - self.trace_obj = None - - # This may be set to set the current frame (for the case where we have - # an unhandled exception where we want to show the root bu we have a different - # executing frame). - self.current_frame = None - - # This is to know whether an exception was extracted from a __cause__ or __context__. - self.exc_context_msg = '' - - self.chained_frames_list = None - - def append(self, frame): - self._frames.append(frame) - - def last_frame(self): - return self._frames[-1] - - def __len__(self): - return len(self._frames) - - def __iter__(self): - return iter(self._frames) - - def __repr__(self): - lst = ['FramesList('] - - lst.append('\n exc_type: ') - lst.append(str(self.exc_type)) - - lst.append('\n exc_desc: ') - lst.append(str(self.exc_desc)) - - lst.append('\n trace_obj: ') - lst.append(str(self.trace_obj)) - - lst.append('\n current_frame: ') - lst.append(str(self.current_frame)) - - for frame in self._frames: - lst.append('\n ') - lst.append(repr(frame)) - lst.append(',') - - if self.chained_frames_list is not None: - lst.append('\n--- Chained ---\n') - lst.append(str(self.chained_frames_list)) - - lst.append('\n)') - - return ''.join(lst) - - __str__ = __repr__ - - -class _DummyFrameWrapper(object): - - def __init__(self, frame, f_lineno, f_back): - self._base_frame = frame - self.f_lineno = f_lineno - self.f_back = f_back - self.f_trace = None - original_code = frame.f_code - name = original_code.co_name - self.f_code = FCode(name, original_code.co_filename) - - @property - def f_locals(self): - return self._base_frame.f_locals - - @property - def f_globals(self): - return self._base_frame.f_globals - - def __str__(self): - return "<_DummyFrameWrapper, file '%s', line %s, %s" % (self.f_code.co_filename, self.f_lineno, self.f_code.co_name) - - __repr__ = __str__ - - -_cause_message = ( - "\nThe above exception was the direct cause " - "of the following exception:\n\n") - -_context_message = ( - "\nDuring handling of the above exception, " - "another exception occurred:\n\n") - - -def create_frames_list_from_exception_cause(trace_obj, frame, exc_type, exc_desc, memo): - lst = [] - msg = '' - try: - exc_cause = getattr(exc_desc, '__cause__', None) - msg = _cause_message - except Exception: - exc_cause = None - - if exc_cause is None: - try: - exc_cause = getattr(exc_desc, '__context__', None) - msg = _context_message - except Exception: - exc_cause = None - - if exc_cause is None or id(exc_cause) in memo: - return None - - # The traceback module does this, so, let's play safe here too... - memo.add(id(exc_cause)) - - tb = exc_cause.__traceback__ - frames_list = FramesList() - frames_list.exc_type = type(exc_cause) - frames_list.exc_desc = exc_cause - frames_list.trace_obj = tb - frames_list.exc_context_msg = msg - - while tb is not None: - # Note: we don't use the actual tb.tb_frame because if the cause of the exception - # uses the same frame object, the id(frame) would be the same and the frame_id_to_lineno - # would be wrong as the same frame needs to appear with 2 different lines. - lst.append((_DummyFrameWrapper(tb.tb_frame, tb.tb_lineno, None), tb.tb_lineno, _get_line_col_info_from_tb(tb))) - tb = tb.tb_next - - for tb_frame, tb_lineno, line_col_info in lst: - frames_list.append(tb_frame) - frames_list.frame_id_to_lineno[id(tb_frame)] = tb_lineno - frames_list.frame_id_to_line_col_info[id(tb_frame)] = line_col_info - - return frames_list - - -if IS_PY311_OR_GREATER: - - def _get_code_position(code, instruction_index): - if instruction_index < 0: - return (None, None, None, None) - positions_gen = code.co_positions() - # Note: some or all of the tuple elements can be None... - return next(itertools.islice(positions_gen, instruction_index // 2, None)) - - def _get_line_col_info_from_tb(tb): - positions = _get_code_position(tb.tb_frame.f_code, tb.tb_lasti) - if positions[0] is None: - return _LineColInfo(tb.tb_lineno, *positions[1:]) - else: - return _LineColInfo(*positions) - -else: - - def _get_line_col_info_from_tb(tb): - # Not available on older versions of Python. - return None - - -def create_frames_list_from_traceback(trace_obj, frame, exc_type, exc_desc, exception_type=None): - ''' - :param trace_obj: - This is the traceback from which the list should be created. - - :param frame: - This is the first frame to be considered (i.e.: topmost frame). If None is passed, all - the frames from the traceback are shown (so, None should be passed for unhandled exceptions). - - :param exception_type: - If this is an unhandled exception or user unhandled exception, we'll not trim the stack to create from the passed - frame, rather, we'll just mark the frame in the frames list. - ''' - lst = [] - - tb = trace_obj - if tb is not None and tb.tb_frame is not None: - f = tb.tb_frame.f_back - while f is not None: - lst.insert(0, (f, f.f_lineno, None)) - f = f.f_back - - while tb is not None: - lst.append((tb.tb_frame, tb.tb_lineno, _get_line_col_info_from_tb(tb))) - tb = tb.tb_next - - frames_list = None - - for tb_frame, tb_lineno, line_col_info in reversed(lst): - if frames_list is None and ( - (frame is tb_frame) or - (frame is None) or - (exception_type == EXCEPTION_TYPE_USER_UNHANDLED) - ): - frames_list = FramesList() - - if frames_list is not None: - frames_list.append(tb_frame) - frames_list.frame_id_to_lineno[id(tb_frame)] = tb_lineno - frames_list.frame_id_to_line_col_info[id(tb_frame)] = line_col_info - - if frames_list is None and frame is not None: - # Fallback (shouldn't happen in practice). - pydev_log.info('create_frames_list_from_traceback did not find topmost frame in list.') - frames_list = create_frames_list_from_frame(frame) - - frames_list.exc_type = exc_type - frames_list.exc_desc = exc_desc - frames_list.trace_obj = trace_obj - - if exception_type == EXCEPTION_TYPE_USER_UNHANDLED: - frames_list.current_frame = frame - elif exception_type == EXCEPTION_TYPE_UNHANDLED: - if len(frames_list) > 0: - frames_list.current_frame = frames_list.last_frame() - - curr = frames_list - memo = set() - memo.add(id(exc_desc)) - - while True: - chained = create_frames_list_from_exception_cause(None, None, None, curr.exc_desc, memo) - if chained is None: - break - else: - curr.chained_frames_list = chained - curr = chained - - return frames_list - - -def create_frames_list_from_frame(frame): - lst = FramesList() - while frame is not None: - lst.append(frame) - frame = frame.f_back - - return lst diff --git a/spaces/Superlang/ImageProcessor/annotator/oneformer/oneformer/evaluation/instance_evaluation.py b/spaces/Superlang/ImageProcessor/annotator/oneformer/oneformer/evaluation/instance_evaluation.py deleted file mode 100644 index 12ce1d722987d1b6daa030423bb6aed4624e8310..0000000000000000000000000000000000000000 --- a/spaces/Superlang/ImageProcessor/annotator/oneformer/oneformer/evaluation/instance_evaluation.py +++ /dev/null @@ -1,110 +0,0 @@ -# ------------------------------------------------------------------------------ -# Reference: https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/evaluation/instance_evaluation.py -# ------------------------------------------------------------------------------ - -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 annotator.oneformer.pycocotools.mask as mask_util -import torch -from annotator.oneformer.pycocotools.coco import COCO -from annotator.oneformer.pycocotools.cocoeval import COCOeval -from tabulate import tabulate - -import annotator.oneformer.detectron2.utils.comm as comm -from annotator.oneformer.detectron2.config import CfgNode -from annotator.oneformer.detectron2.data import MetadataCatalog -from annotator.oneformer.detectron2.data.datasets.coco import convert_to_coco_json -from annotator.oneformer.detectron2.evaluation.coco_evaluation import COCOEvaluator, _evaluate_predictions_on_coco -from annotator.oneformer.detectron2.evaluation.fast_eval_api import COCOeval_opt -from annotator.oneformer.detectron2.structures import Boxes, BoxMode, pairwise_iou -from annotator.oneformer.detectron2.utils.file_io import PathManager -from annotator.oneformer.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/TRI-ML/risk_biased_prediction/tests/risk_biased/mpc_planner/test_dynamics.py b/spaces/TRI-ML/risk_biased_prediction/tests/risk_biased/mpc_planner/test_dynamics.py deleted file mode 100644 index e5611bd7e1c7214338dcb630a938a5fe12c372d2..0000000000000000000000000000000000000000 --- a/spaces/TRI-ML/risk_biased_prediction/tests/risk_biased/mpc_planner/test_dynamics.py +++ /dev/null @@ -1,34 +0,0 @@ -import pytest - -import torch - -from risk_biased.mpc_planner.dynamics import PositionVelocityDoubleIntegrator -from risk_biased.utils.planner_utils import to_state - - -@pytest.mark.parametrize("dt", [(0.01), (0.1)]) -def test_double_integrator(dt: float): - - torch.manual_seed(0) - - dynamics = PositionVelocityDoubleIntegrator(dt) - assert dynamics.dt == dt - assert dynamics.control_dim == 2 - - state_init = to_state(torch.randn(1, 4), dt) - control_input = torch.randn(10, 5, 2) - state_future = dynamics.simulate(state_init, control_input) - assert state_future.shape == (10, 5) - - assert torch.allclose( - state_future.position, - state_init.position - + torch.cumsum( - state_init.velocity + torch.cumsum(control_input, dim=1) * dt, dim=1 - ) - * dt, - ) - assert torch.allclose( - state_future.position, - state_init.position + torch.cumsum(state_future.velocity * dt, dim=1), - ) diff --git a/spaces/TYH71/gradio-ml-skeleton/src/model/__init__.py b/spaces/TYH71/gradio-ml-skeleton/src/model/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.py deleted file mode 100644 index 19a169fc30183db91f931ad6ad04fbc0e16559b3..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_vendor/more_itertools/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .more import * # noqa -from .recipes import * # noqa - -__version__ = '8.8.0' diff --git a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_vendor/packaging/metadata.py b/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_vendor/packaging/metadata.py deleted file mode 100644 index e76a60c395eb62d5f05d7248cf67210cdd10740d..0000000000000000000000000000000000000000 --- a/spaces/TandCAcceptMe/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/_vendor/packaging/metadata.py +++ /dev/null @@ -1,408 +0,0 @@ -import email.feedparser -import email.header -import email.message -import email.parser -import email.policy -import sys -import typing -from typing import Dict, List, Optional, Tuple, Union, cast - -if sys.version_info >= (3, 8): # pragma: no cover - from typing import TypedDict -else: # pragma: no cover - if typing.TYPE_CHECKING: - from typing_extensions import TypedDict - else: - try: - from typing_extensions import TypedDict - except ImportError: - - class TypedDict: - def __init_subclass__(*_args, **_kwargs): - pass - - -# The RawMetadata class attempts to make as few assumptions about the underlying -# serialization formats as possible. The idea is that as long as a serialization -# formats offer some very basic primitives in *some* way then we can support -# serializing to and from that format. -class RawMetadata(TypedDict, total=False): - """A dictionary of raw core metadata. - - Each field in core metadata maps to a key of this dictionary (when data is - provided). The key is lower-case and underscores are used instead of dashes - compared to the equivalent core metadata field. Any core metadata field that - can be specified multiple times or can hold multiple values in a single - field have a key with a plural name. - - Core metadata fields that can be specified multiple times are stored as a - list or dict depending on which is appropriate for the field. Any fields - which hold multiple values in a single field are stored as a list. - - """ - - # Metadata 1.0 - PEP 241 - metadata_version: str - name: str - version: str - platforms: List[str] - summary: str - description: str - keywords: List[str] - home_page: str - author: str - author_email: str - license: str - - # Metadata 1.1 - PEP 314 - supported_platforms: List[str] - download_url: str - classifiers: List[str] - requires: List[str] - provides: List[str] - obsoletes: List[str] - - # Metadata 1.2 - PEP 345 - maintainer: str - maintainer_email: str - requires_dist: List[str] - provides_dist: List[str] - obsoletes_dist: List[str] - requires_python: str - requires_external: List[str] - project_urls: Dict[str, str] - - # Metadata 2.0 - # PEP 426 attempted to completely revamp the metadata format - # but got stuck without ever being able to build consensus on - # it and ultimately ended up withdrawn. - # - # However, a number of tools had started emiting METADATA with - # `2.0` Metadata-Version, so for historical reasons, this version - # was skipped. - - # Metadata 2.1 - PEP 566 - description_content_type: str - provides_extra: List[str] - - # Metadata 2.2 - PEP 643 - dynamic: List[str] - - # Metadata 2.3 - PEP 685 - # No new fields were added in PEP 685, just some edge case were - # tightened up to provide better interoptability. - - -_STRING_FIELDS = { - "author", - "author_email", - "description", - "description_content_type", - "download_url", - "home_page", - "license", - "maintainer", - "maintainer_email", - "metadata_version", - "name", - "requires_python", - "summary", - "version", -} - -_LIST_STRING_FIELDS = { - "classifiers", - "dynamic", - "obsoletes", - "obsoletes_dist", - "platforms", - "provides", - "provides_dist", - "provides_extra", - "requires", - "requires_dist", - "requires_external", - "supported_platforms", -} - - -def _parse_keywords(data: str) -> List[str]: - """Split a string of comma-separate keyboards into a list of keywords.""" - return [k.strip() for k in data.split(",")] - - -def _parse_project_urls(data: List[str]) -> Dict[str, str]: - """Parse a list of label/URL string pairings separated by a comma.""" - urls = {} - for pair in data: - # Our logic is slightly tricky here as we want to try and do - # *something* reasonable with malformed data. - # - # The main thing that we have to worry about, is data that does - # not have a ',' at all to split the label from the Value. There - # isn't a singular right answer here, and we will fail validation - # later on (if the caller is validating) so it doesn't *really* - # matter, but since the missing value has to be an empty str - # and our return value is dict[str, str], if we let the key - # be the missing value, then they'd have multiple '' values that - # overwrite each other in a accumulating dict. - # - # The other potentional issue is that it's possible to have the - # same label multiple times in the metadata, with no solid "right" - # answer with what to do in that case. As such, we'll do the only - # thing we can, which is treat the field as unparseable and add it - # to our list of unparsed fields. - parts = [p.strip() for p in pair.split(",", 1)] - parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items - - # TODO: The spec doesn't say anything about if the keys should be - # considered case sensitive or not... logically they should - # be case-preserving and case-insensitive, but doing that - # would open up more cases where we might have duplicate - # entries. - label, url = parts - if label in urls: - # The label already exists in our set of urls, so this field - # is unparseable, and we can just add the whole thing to our - # unparseable data and stop processing it. - raise KeyError("duplicate labels in project urls") - urls[label] = url - - return urls - - -def _get_payload(msg: email.message.Message, source: Union[bytes, str]) -> str: - """Get the body of the message.""" - # If our source is a str, then our caller has managed encodings for us, - # and we don't need to deal with it. - if isinstance(source, str): - payload: str = msg.get_payload() - return payload - # If our source is a bytes, then we're managing the encoding and we need - # to deal with it. - else: - bpayload: bytes = msg.get_payload(decode=True) - try: - return bpayload.decode("utf8", "strict") - except UnicodeDecodeError: - raise ValueError("payload in an invalid encoding") - - -# The various parse_FORMAT functions here are intended to be as lenient as -# possible in their parsing, while still returning a correctly typed -# RawMetadata. -# -# To aid in this, we also generally want to do as little touching of the -# data as possible, except where there are possibly some historic holdovers -# that make valid data awkward to work with. -# -# While this is a lower level, intermediate format than our ``Metadata`` -# class, some light touch ups can make a massive difference in usability. - -# Map METADATA fields to RawMetadata. -_EMAIL_TO_RAW_MAPPING = { - "author": "author", - "author-email": "author_email", - "classifier": "classifiers", - "description": "description", - "description-content-type": "description_content_type", - "download-url": "download_url", - "dynamic": "dynamic", - "home-page": "home_page", - "keywords": "keywords", - "license": "license", - "maintainer": "maintainer", - "maintainer-email": "maintainer_email", - "metadata-version": "metadata_version", - "name": "name", - "obsoletes": "obsoletes", - "obsoletes-dist": "obsoletes_dist", - "platform": "platforms", - "project-url": "project_urls", - "provides": "provides", - "provides-dist": "provides_dist", - "provides-extra": "provides_extra", - "requires": "requires", - "requires-dist": "requires_dist", - "requires-external": "requires_external", - "requires-python": "requires_python", - "summary": "summary", - "supported-platform": "supported_platforms", - "version": "version", -} - - -def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[str]]]: - """Parse a distribution's metadata. - - This function returns a two-item tuple of dicts. The first dict is of - recognized fields from the core metadata specification. Fields that can be - parsed and translated into Python's built-in types are converted - appropriately. All other fields are left as-is. Fields that are allowed to - appear multiple times are stored as lists. - - The second dict contains all other fields from the metadata. This includes - any unrecognized fields. It also includes any fields which are expected to - be parsed into a built-in type but were not formatted appropriately. Finally, - any fields that are expected to appear only once but are repeated are - included in this dict. - - """ - raw: Dict[str, Union[str, List[str], Dict[str, str]]] = {} - unparsed: Dict[str, List[str]] = {} - - if isinstance(data, str): - parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) - else: - parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) - - # We have to wrap parsed.keys() in a set, because in the case of multiple - # values for a key (a list), the key will appear multiple times in the - # list of keys, but we're avoiding that by using get_all(). - for name in frozenset(parsed.keys()): - # Header names in RFC are case insensitive, so we'll normalize to all - # lower case to make comparisons easier. - name = name.lower() - - # We use get_all() here, even for fields that aren't multiple use, - # because otherwise someone could have e.g. two Name fields, and we - # would just silently ignore it rather than doing something about it. - headers = parsed.get_all(name) - - # The way the email module works when parsing bytes is that it - # unconditionally decodes the bytes as ascii using the surrogateescape - # handler. When you pull that data back out (such as with get_all() ), - # it looks to see if the str has any surrogate escapes, and if it does - # it wraps it in a Header object instead of returning the string. - # - # As such, we'll look for those Header objects, and fix up the encoding. - value = [] - # Flag if we have run into any issues processing the headers, thus - # signalling that the data belongs in 'unparsed'. - valid_encoding = True - for h in headers: - # It's unclear if this can return more types than just a Header or - # a str, so we'll just assert here to make sure. - assert isinstance(h, (email.header.Header, str)) - - # If it's a header object, we need to do our little dance to get - # the real data out of it. In cases where there is invalid data - # we're going to end up with mojibake, but there's no obvious, good - # way around that without reimplementing parts of the Header object - # ourselves. - # - # That should be fine since, if mojibacked happens, this key is - # going into the unparsed dict anyways. - if isinstance(h, email.header.Header): - # The Header object stores it's data as chunks, and each chunk - # can be independently encoded, so we'll need to check each - # of them. - chunks: List[Tuple[bytes, Optional[str]]] = [] - for bin, encoding in email.header.decode_header(h): - try: - bin.decode("utf8", "strict") - except UnicodeDecodeError: - # Enable mojibake. - encoding = "latin1" - valid_encoding = False - else: - encoding = "utf8" - chunks.append((bin, encoding)) - - # Turn our chunks back into a Header object, then let that - # Header object do the right thing to turn them into a - # string for us. - value.append(str(email.header.make_header(chunks))) - # This is already a string, so just add it. - else: - value.append(h) - - # We've processed all of our values to get them into a list of str, - # but we may have mojibake data, in which case this is an unparsed - # field. - if not valid_encoding: - unparsed[name] = value - continue - - raw_name = _EMAIL_TO_RAW_MAPPING.get(name) - if raw_name is None: - # This is a bit of a weird situation, we've encountered a key that - # we don't know what it means, so we don't know whether it's meant - # to be a list or not. - # - # Since we can't really tell one way or another, we'll just leave it - # as a list, even though it may be a single item list, because that's - # what makes the most sense for email headers. - unparsed[name] = value - continue - - # If this is one of our string fields, then we'll check to see if our - # value is a list of a single item. If it is then we'll assume that - # it was emitted as a single string, and unwrap the str from inside - # the list. - # - # If it's any other kind of data, then we haven't the faintest clue - # what we should parse it as, and we have to just add it to our list - # of unparsed stuff. - if raw_name in _STRING_FIELDS and len(value) == 1: - raw[raw_name] = value[0] - # If this is one of our list of string fields, then we can just assign - # the value, since email *only* has strings, and our get_all() call - # above ensures that this is a list. - elif raw_name in _LIST_STRING_FIELDS: - raw[raw_name] = value - # Special Case: Keywords - # The keywords field is implemented in the metadata spec as a str, - # but it conceptually is a list of strings, and is serialized using - # ", ".join(keywords), so we'll do some light data massaging to turn - # this into what it logically is. - elif raw_name == "keywords" and len(value) == 1: - raw[raw_name] = _parse_keywords(value[0]) - # Special Case: Project-URL - # The project urls is implemented in the metadata spec as a list of - # specially-formatted strings that represent a key and a value, which - # is fundamentally a mapping, however the email format doesn't support - # mappings in a sane way, so it was crammed into a list of strings - # instead. - # - # We will do a little light data massaging to turn this into a map as - # it logically should be. - elif raw_name == "project_urls": - try: - raw[raw_name] = _parse_project_urls(value) - except KeyError: - unparsed[name] = value - # Nothing that we've done has managed to parse this, so it'll just - # throw it in our unparseable data and move on. - else: - unparsed[name] = value - - # We need to support getting the Description from the message payload in - # addition to getting it from the the headers. This does mean, though, there - # is the possibility of it being set both ways, in which case we put both - # in 'unparsed' since we don't know which is right. - try: - payload = _get_payload(parsed, data) - except ValueError: - unparsed.setdefault("description", []).append( - parsed.get_payload(decode=isinstance(data, bytes)) - ) - else: - if payload: - # Check to see if we've already got a description, if so then both - # it, and this body move to unparseable. - if "description" in raw: - description_header = cast(str, raw.pop("description")) - unparsed.setdefault("description", []).extend( - [description_header, payload] - ) - elif "description" in unparsed: - unparsed["description"].append(payload) - else: - raw["description"] = payload - - # We need to cast our `raw` to a metadata, because a TypedDict only support - # literal key names, but we're computing our key names on purpose, but the - # way this function is implemented, our `TypedDict` can only have valid key - # names. - return cast(RawMetadata, raw), unparsed diff --git a/spaces/TechShark20/handwespeak/main.py b/spaces/TechShark20/handwespeak/main.py deleted file mode 100644 index f56becc972000202a0e794e2b427072f21d15052..0000000000000000000000000000000000000000 --- a/spaces/TechShark20/handwespeak/main.py +++ /dev/null @@ -1,43 +0,0 @@ - -import ast -import pandas as pd - -from normalization.hand_normalization import normalize_hands_full -from normalization.body_normalization import normalize_body_full - - -# Load the dataset -df = pd.read_csv("/Users/matyasbohacek/Documents/WLASL_test_15fps.csv", encoding="utf-8") - -# Retrieve metadata -video_size_heights = df["video_size_height"].to_list() -video_size_widths = df["video_size_width"].to_list() - -# Delete redundant (non-related) properties -del df["video_size_height"] -del df["video_size_width"] - -# Temporarily remove other relevant metadata -labels = df["labels"].to_list() -video_fps = df["video_fps"].to_list() -del df["labels"] -del df["video_fps"] - -# Convert the strings into lists -convert = lambda x: ast.literal_eval(str(x)) -for column in df.columns: - df[column] = df[column].apply(convert) - -# Perform the normalizations -df = normalize_hands_full(df) -df, invalid_row_indexes = normalize_body_full(df) - -# Clear lists of items from deleted rows -# labels = [t for i, t in enumerate(labels) if i not in invalid_row_indexes] -# video_fps = [t for i, t in enumerate(video_fps) if i not in invalid_row_indexes] - -# Return the metadata back to the dataset -df["labels"] = labels -df["video_fps"] = video_fps - -df.to_csv("/Users/matyasbohacek/Desktop/WLASL_test_15fps_normalized.csv", encoding="utf-8", index=False) diff --git a/spaces/ThirdEyeData/Customer-Conversion-Prediction/matumizi/sampler.py b/spaces/ThirdEyeData/Customer-Conversion-Prediction/matumizi/sampler.py deleted file mode 100644 index 2821f3df627ae45f75bf1a8f4446f000e55c1615..0000000000000000000000000000000000000000 --- a/spaces/ThirdEyeData/Customer-Conversion-Prediction/matumizi/sampler.py +++ /dev/null @@ -1,1455 +0,0 @@ -#!/usr/local/bin/python3 - -# avenir-python: Machine Learning -# Author: Pranab Ghosh -# -# 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 sys -import random -import time -import math -import random -import numpy as np -from scipy import stats -from random import randint -from .util import * -from .stats import Histogram - -def randomFloat(low, high): - """ - sample float within range - - Parameters - low : low valuee - high : high valuee - """ - return random.random() * (high-low) + low - -def randomInt(minv, maxv): - """ - sample int within range - - Parameters - minv : low valuee - maxv : high valuee - """ - return randint(minv, maxv) - -def randIndex(lData): - """ - random index of a list - - Parameters - lData : list data - """ - return randint(0, len(lData)-1) - -def randomUniformSampled(low, high): - """ - sample float within range - - Parameters - low : low value - high : high value - """ - return np.random.uniform(low, high) - -def randomUniformSampledList(low, high, size): - """ - sample floats within range to create list - - Parameters - low : low value - high : high value - size ; size of list to be returned - """ - return np.random.uniform(low, high, size) - -def randomNormSampled(mean, sd): - """ - sample float from normal - - Parameters - mean : mean - sd : std deviation - """ - return np.random.normal(mean, sd) - -def randomNormSampledList(mean, sd, size): - """ - sample float list from normal - - Parameters - mean : mean - sd : std deviation - size : size of list to be returned - """ - return np.random.normal(mean, sd, size) - -def randomSampledList(sampler, size): - """ - sample list from given sampler - - Parameters - sampler : sampler object - size : size of list to be returned - """ - return list(map(lambda i : sampler.sample(), range(size))) - - -def minLimit(val, minv): - """ - min limit - - Parameters - val : value - minv : min limit - """ - if (val < minv): - val = minv - return val - - -def rangeLimit(val, minv, maxv): - """ - range limit - - Parameters - val : value - minv : min limit - maxv : max limit - """ - if (val < minv): - val = minv - elif (val > maxv): - val = maxv - return val - - -def sampleUniform(minv, maxv): - """ - sample int within range - - Parameters - minv ; int min limit - maxv : int max limit - """ - return randint(minv, maxv) - - -def sampleFromBase(value, dev): - """ - sample int wrt base - - Parameters - value : base value - dev : deviation - """ - return randint(value - dev, value + dev) - - -def sampleFloatFromBase(value, dev): - """ - sample float wrt base - - Parameters - value : base value - dev : deviation - """ - return randomFloat(value - dev, value + dev) - - -def distrUniformWithRanndom(total, numItems, noiseLevel): - """ - uniformly distribute with some randomness and preserves total - - Parameters - total : total count - numItems : no of bins - noiseLevel : noise level fraction - """ - perItem = total / numItems - var = perItem * noiseLevel - items = [] - for i in range(numItems): - item = perItem + randomFloat(-var, var) - items.append(item) - - #adjust last item - sm = sum(items[:-1]) - items[-1] = total - sm - return items - - -def isEventSampled(threshold, maxv=100): - """ - sample event which occurs if sampled below threshold - - Parameters - threshold : threshold for sampling - maxv : maximum values - """ - return randint(0, maxv) < threshold - - -def sampleBinaryEvents(events, probPercent): - """ - sample binary events - - Parameters - events : two events - probPercent : probability as percentage - """ - if (randint(0, 100) < probPercent): - event = events[0] - else: - event = events[1] - return event - - -def addNoiseNum(value, sampler): - """ - add noise to numeric value - - Parameters - value : base value - sampler : sampler for noise - """ - return value * (1 + sampler.sample()) - - -def addNoiseCat(value, values, noise): - """ - add noise to categorical value i.e with some probability change value - - Parameters - value : cat value - values : cat values - noise : noise level fraction - """ - newValue = value - threshold = int(noise * 100) - if (isEventSampled(threshold)): - newValue = selectRandomFromList(values) - while newValue == value: - newValue = selectRandomFromList(values) - return newValue - - -def sampleWithReplace(data, sampSize): - """ - sample with replacement - - Parameters - data : array - sampSize : sample size - """ - sampled = list() - le = len(data) - if sampSize is None: - sampSize = le - for i in range(sampSize): - j = random.randint(0, le - 1) - sampled.append(data[j]) - return sampled - -class CumDistr: - """ - cumulative distr - """ - - def __init__(self, data, numBins = None): - """ - initializer - - Parameters - data : array - numBins : no of bins - """ - if not numBins: - numBins = int(len(data) / 5) - res = stats.cumfreq(data, numbins=numBins) - self.cdistr = res.cumcount / len(data) - self.loLim = res.lowerlimit - self.upLim = res.lowerlimit + res.binsize * res.cumcount.size - self.binWidth = res.binsize - - def getDistr(self, value): - """ - get cumulative distribution - - Parameters - value : value - """ - if value <= self.loLim: - d = 0.0 - elif value >= self.upLim: - d = 1.0 - else: - bin = int((value - self.loLim) / self.binWidth) - d = self.cdistr[bin] - return d - -class BernoulliTrialSampler: - """ - bernoulli trial sampler return True or False - """ - - def __init__(self, pr, events=None): - """ - initializer - - Parameters - pr : probability - events : event values - """ - self.pr = pr - self.retEvent = False if events is None else True - self.events = events - - - def sample(self): - """ - samples value - """ - res = random.random() < self.pr - if self.retEvent: - res = self.events[0] if res else self.events[1] - return res - -class PoissonSampler: - """ - poisson sampler returns number of events - """ - def __init__(self, rateOccur, maxSamp): - """ - initializer - - Parameters - rateOccur : rate of occurence - maxSamp : max limit on no of samples - """ - self.rateOccur = rateOccur - self.maxSamp = int(maxSamp) - self.pmax = self.calculatePr(rateOccur) - - def calculatePr(self, numOccur): - """ - calulates probability - - Parameters - numOccur : no of occurence - """ - p = (self.rateOccur ** numOccur) * math.exp(-self.rateOccur) / math.factorial(numOccur) - return p - - def sample(self): - """ - samples value - """ - done = False - samp = 0 - while not done: - no = randint(0, self.maxSamp) - sp = randomFloat(0.0, self.pmax) - ap = self.calculatePr(no) - if sp < ap: - done = True - samp = no - return samp - -class ExponentialSampler: - """ - returns interval between events - """ - def __init__(self, rateOccur, maxSamp = None): - """ - initializer - - Parameters - rateOccur : rate of occurence - maxSamp : max limit on interval - """ - self.interval = 1.0 / rateOccur - self.maxSamp = int(maxSamp) if maxSamp is not None else None - - def sample(self): - """ - samples value - """ - sampled = np.random.exponential(scale=self.interval) - if self.maxSamp is not None: - while sampled > self.maxSamp: - sampled = np.random.exponential(scale=self.interval) - return sampled - -class UniformNumericSampler: - """ - uniform sampler for numerical values - """ - def __init__(self, minv, maxv): - """ - initializer - - Parameters - minv : min value - maxv : max value - """ - self.minv = minv - self.maxv = maxv - - def isNumeric(self): - """ - returns true - """ - return True - - def sample(self): - """ - samples value - """ - samp = sampleUniform(self.minv, self.maxv) if isinstance(self.minv, int) else randomFloat(self.minv, self.maxv) - return samp - -class UniformCategoricalSampler: - """ - uniform sampler for categorical values - """ - def __init__(self, cvalues): - """ - initializer - - Parameters - cvalues : categorical value list - """ - self.cvalues = cvalues - - def isNumeric(self): - return False - - def sample(self): - """ - samples value - """ - return selectRandomFromList(self.cvalues) - -class NormalSampler: - """ - normal sampler - """ - def __init__(self, mean, stdDev): - """ - initializer - - Parameters - mean : mean - stdDev : std deviation - """ - self.mean = mean - self.stdDev = stdDev - self.sampleAsInt = False - - def isNumeric(self): - return True - - def sampleAsIntValue(self): - """ - set True to sample as int - """ - self.sampleAsInt = True - - def sample(self): - """ - samples value - """ - samp = np.random.normal(self.mean, self.stdDev) - if self.sampleAsInt: - samp = int(samp) - return samp - -class LogNormalSampler: - """ - log normal sampler - """ - def __init__(self, mean, stdDev): - """ - initializer - - Parameters - mean : mean - stdDev : std deviation - """ - self.mean = mean - self.stdDev = stdDev - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - return np.random.lognormal(self.mean, self.stdDev) - -class NormalSamplerWithTrendCycle: - """ - normal sampler with cycle and trend - """ - def __init__(self, mean, stdDev, dmean, cycle, step=1): - """ - initializer - - Parameters - mean : mean - stdDev : std deviation - dmean : trend delta - cycle : cycle values wrt base mean - step : adjustment step for cycle and trend - """ - self.mean = mean - self.cmean = mean - self.stdDev = stdDev - self.dmean = dmean - self.cycle = cycle - self.clen = len(cycle) if cycle is not None else 0 - self.step = step - self.count = 0 - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - s = np.random.normal(self.cmean, self.stdDev) - self.count += 1 - if self.count % self.step == 0: - cy = 0 - if self.clen > 1: - coff = self.count % self.clen - cy = self.cycle[coff] - tr = self.count * self.dmean - self.cmean = self.mean + tr + cy - return s - - -class ParetoSampler: - """ - pareto sampler - """ - def __init__(self, mode, shape): - """ - initializer - - Parameters - mode : mode - shape : shape - """ - self.mode = mode - self.shape = shape - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - return (np.random.pareto(self.shape) + 1) * self.mode - -class GammaSampler: - """ - pareto sampler - """ - def __init__(self, shape, scale): - """ - initializer - - Parameters - shape : shape - scale : scale - """ - self.shape = shape - self.scale = scale - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - return np.random.gamma(self.shape, self.scale) - -class GaussianRejectSampler: - """ - gaussian sampling based on rejection sampling - """ - def __init__(self, mean, stdDev): - """ - initializer - - Parameters - mean : mean - stdDev : std deviation - """ - self.mean = mean - self.stdDev = stdDev - self.xmin = mean - 3 * stdDev - self.xmax = mean + 3 * stdDev - self.ymin = 0.0 - self.fmax = 1.0 / (math.sqrt(2.0 * 3.14) * stdDev) - self.ymax = 1.05 * self.fmax - self.sampleAsInt = False - - def isNumeric(self): - return True - - def sampleAsIntValue(self): - """ - sample as int value - """ - self.sampleAsInt = True - - def sample(self): - """ - samples value - """ - done = False - samp = 0 - while not done: - x = randomFloat(self.xmin, self.xmax) - y = randomFloat(self.ymin, self.ymax) - f = self.fmax * math.exp(-(x - self.mean) * (x - self.mean) / (2.0 * self.stdDev * self.stdDev)) - if (y < f): - done = True - samp = x - if self.sampleAsInt: - samp = int(samp) - return samp - -class DiscreteRejectSampler: - """ - non parametric sampling for discrete values using given distribution based - on rejection sampling - """ - def __init__(self, xmin, xmax, step, *values): - """ - initializer - - Parameters - xmin : min value - xmax : max value - step : discrete step - values : distr values - """ - self.xmin = xmin - self.xmax = xmax - self.step = step - self.distr = values - if (len(self.distr) == 1): - self.distr = self.distr[0] - numSteps = int((self.xmax - self.xmin) / self.step) - #print("{:.3f} {:.3f} {:.3f} {}".format(self.xmin, self.xmax, self.step, numSteps)) - assert len(self.distr) == numSteps + 1, "invalid number of distr values expected {}".format(numSteps + 1) - self.ximin = 0 - self.ximax = numSteps - self.pmax = float(max(self.distr)) - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - done = False - samp = None - while not done: - xi = randint(self.ximin, self.ximax) - #print(formatAny(xi, "xi")) - ps = randomFloat(0.0, self.pmax) - pa = self.distr[xi] - if ps < pa: - samp = self.xmin + xi * self.step - done = True - return samp - - -class TriangularRejectSampler: - """ - non parametric sampling using triangular distribution based on rejection sampling - """ - def __init__(self, xmin, xmax, vertexValue, vertexPos=None): - """ - initializer - - Parameters - xmin : min value - xmax : max value - vertexValue : distr value at vertex - vertexPos : vertex pposition - """ - self.xmin = xmin - self.xmax = xmax - self.vertexValue = vertexValue - if vertexPos: - assert vertexPos > xmin and vertexPos < xmax, "vertex position outside bound" - self.vertexPos = vertexPos - else: - self.vertexPos = 0.5 * (xmin + xmax) - self.s1 = vertexValue / (self.vertexPos - xmin) - self.s2 = vertexValue / (xmax - self.vertexPos) - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - done = False - samp = None - while not done: - x = randomFloat(self.xmin, self.xmax) - y = randomFloat(0.0, self.vertexValue) - f = (x - self.xmin) * self.s1 if x < self.vertexPos else (self.xmax - x) * self.s2 - if (y < f): - done = True - samp = x - - return samp; - -class NonParamRejectSampler: - """ - non parametric sampling using given distribution based on rejection sampling - """ - def __init__(self, xmin, binWidth, *values): - """ - initializer - - Parameters - xmin : min value - binWidth : bin width - values : distr values - """ - self.values = values - if (len(self.values) == 1): - self.values = self.values[0] - self.xmin = xmin - self.xmax = xmin + binWidth * (len(self.values) - 1) - #print(self.xmin, self.xmax, binWidth) - self.binWidth = binWidth - self.fmax = 0 - for v in self.values: - if (v > self.fmax): - self.fmax = v - self.ymin = 0 - self.ymax = self.fmax - self.sampleAsInt = True - - def isNumeric(self): - return True - - def sampleAsFloat(self): - self.sampleAsInt = False - - def sample(self): - """ - samples value - """ - done = False - samp = 0 - while not done: - if self.sampleAsInt: - x = random.randint(self.xmin, self.xmax) - y = random.randint(self.ymin, self.ymax) - else: - x = randomFloat(self.xmin, self.xmax) - y = randomFloat(self.ymin, self.ymax) - bin = int((x - self.xmin) / self.binWidth) - f = self.values[bin] - if (y < f): - done = True - samp = x - return samp - -class JointNonParamRejectSampler: - """ - non parametric sampling using given distribution based on rejection sampling - """ - def __init__(self, xmin, xbinWidth, xnbin, ymin, ybinWidth, ynbin, *values): - """ - initializer - - Parameters - xmin : min value for x - xbinWidth : bin width for x - xnbin : no of bins for x - ymin : min value for y - ybinWidth : bin width for y - ynbin : no of bins for y - values : distr values - """ - self.values = values - if (len(self.values) == 1): - self.values = self.values[0] - assert len(self.values) == xnbin * ynbin, "wrong number of values for joint distr" - self.xmin = xmin - self.xmax = xmin + xbinWidth * xnbin - self.xbinWidth = xbinWidth - self.ymin = ymin - self.ymax = ymin + ybinWidth * ynbin - self.ybinWidth = ybinWidth - self.pmax = max(self.values) - self.values = np.array(self.values).reshape(xnbin, ynbin) - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - done = False - samp = 0 - while not done: - x = randomFloat(self.xmin, self.xmax) - y = randomFloat(self.ymin, self.ymax) - xbin = int((x - self.xmin) / self.xbinWidth) - ybin = int((y - self.ymin) / self.ybinWidth) - ap = self.values[xbin][ybin] - sp = randomFloat(0.0, self.pmax) - if (sp < ap): - done = True - samp = [x,y] - return samp - - -class JointNormalSampler: - """ - joint normal sampler - """ - def __init__(self, *values): - """ - initializer - - Parameters - values : 2 mean values followed by 4 values for covar matrix - """ - lvalues = list(values) - assert len(lvalues) == 6, "incorrect number of arguments for joint normal sampler" - mean = lvalues[:2] - self.mean = np.array(mean) - sd = lvalues[2:] - self.sd = np.array(sd).reshape(2,2) - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - return list(np.random.multivariate_normal(self.mean, self.sd)) - - -class MultiVarNormalSampler: - """ - muti variate normal sampler - """ - def __init__(self, numVar, *values): - """ - initializer - - Parameters - numVar : no of variables - values : numVar mean values followed by numVar x numVar values for covar matrix - """ - lvalues = list(values) - assert len(lvalues) == numVar + numVar * numVar, "incorrect number of arguments for multi var normal sampler" - mean = lvalues[:numVar] - self.mean = np.array(mean) - sd = lvalues[numVar:] - self.sd = np.array(sd).reshape(numVar,numVar) - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - return list(np.random.multivariate_normal(self.mean, self.sd)) - -class CategoricalRejectSampler: - """ - non parametric sampling for categorical attributes using given distribution based - on rejection sampling - """ - def __init__(self, *values): - """ - initializer - - Parameters - values : list of tuples which contains a categorical value and the corresponsding distr value - """ - self.distr = values - if (len(self.distr) == 1): - self.distr = self.distr[0] - maxv = 0 - for t in self.distr: - if t[1] > maxv: - maxv = t[1] - self.maxv = maxv - - def sample(self): - """ - samples value - """ - done = False - samp = "" - while not done: - t = self.distr[randint(0, len(self.distr)-1)] - d = randomFloat(0, self.maxv) - if (d <= t[1]): - done = True - samp = t[0] - return samp - - -class CategoricalSetSampler: - """ - non parametric sampling for categorical attributes using uniform distribution based for - sampling a set of values from all values - """ - def __init__(self, *values): - """ - initializer - - Parameters - values : list which contains a categorical values - """ - self.values = values - if (len(self.values) == 1): - self.values = self.values[0] - self.sampled = list() - - def sample(self): - """ - samples value only from previously unsamopled - """ - samp = selectRandomFromList(self.values) - while True: - if samp in self.sampled: - samp = selectRandomFromList(self.values) - else: - self.sampled.append(samp) - break - return samp - - def setSampled(self, sampled): - """ - set already sampled - - Parameters - sampled : already sampled list - """ - self.sampled = sampled - - def unsample(self, sample=None): - """ - rempve from sample history - - Parameters - sample : sample to be removed - """ - if sample is None: - self.sampled.clear() - else: - self.sampled.remove(sample) - -class DistrMixtureSampler: - """ - distr mixture sampler - """ - def __init__(self, mixtureWtDistr, *compDistr): - """ - initializer - - Parameters - mixtureWtDistr : sampler that returns index into sampler list - compDistr : sampler list - """ - self.mixtureWtDistr = mixtureWtDistr - self.compDistr = compDistr - if (len(self.compDistr) == 1): - self.compDistr = self.compDistr[0] - - def isNumeric(self): - return True - - def sample(self): - """ - samples value - """ - comp = self.mixtureWtDistr.sample() - - #sample sampled comp distr - return self.compDistr[comp].sample() - -class AncestralSampler: - """ - ancestral sampler using conditional distribution - """ - def __init__(self, parentDistr, childDistr, numChildren): - """ - initializer - - Parameters - parentDistr : parent distr - childDistr : childdren distribution dictionary - numChildren : no of children - """ - self.parentDistr = parentDistr - self.childDistr = childDistr - self.numChildren = numChildren - - def sample(self): - """ - samples value - """ - parent = self.parentDistr.sample() - - #sample all children conditioned on parent - children = [] - for i in range(self.numChildren): - key = (parent, i) - child = self.childDistr[key].sample() - children.append(child) - return (parent, children) - -class ClusterSampler: - """ - sample cluster and then sample member of sampled cluster - """ - def __init__(self, clusters, *clustDistr): - """ - initializer - - Parameters - clusters : dictionary clusters - clustDistr : distr for clusters - """ - self.sampler = CategoricalRejectSampler(*clustDistr) - self.clusters = clusters - - def sample(self): - """ - samples value - """ - cluster = self.sampler.sample() - member = random.choice(self.clusters[cluster]) - return (cluster, member) - - -class MetropolitanSampler: - """ - metropolitan sampler - """ - def __init__(self, propStdDev, min, binWidth, values): - """ - initializer - - Parameters - propStdDev : proposal distr std dev - min : min domain value for target distr - binWidth : bin width - values : target distr values - """ - self.targetDistr = Histogram.createInitialized(min, binWidth, values) - self.propsalDistr = GaussianRejectSampler(0, propStdDev) - self.proposalMixture = False - - # bootstrap sample - (minv, maxv) = self.targetDistr.getMinMax() - self.curSample = random.randint(minv, maxv) - self.curDistr = self.targetDistr.value(self.curSample) - self.transCount = 0 - - def initialize(self): - """ - initialize - """ - (minv, maxv) = self.targetDistr.getMinMax() - self.curSample = random.randint(minv, maxv) - self.curDistr = self.targetDistr.value(self.curSample) - self.transCount = 0 - - def setProposalDistr(self, propsalDistr): - """ - set custom proposal distribution - - Parameters - propsalDistr : proposal distribution - """ - self.propsalDistr = propsalDistr - - - def setGlobalProposalDistr(self, globPropStdDev, proposalChoiceThreshold): - """ - set custom proposal distribution - - Parameters - globPropStdDev : global proposal distr std deviation - proposalChoiceThreshold : threshold for using global proposal distribution - """ - self.globalProposalDistr = GaussianRejectSampler(0, globPropStdDev) - self.proposalChoiceThreshold = proposalChoiceThreshold - self.proposalMixture = True - - def sample(self): - """ - samples value - """ - nextSample = self.proposalSample(1) - self.targetSample(nextSample) - return self.curSample; - - def proposalSample(self, skip): - """ - sample from proposal distribution - - Parameters - skip : no of samples to skip - """ - for i in range(skip): - if not self.proposalMixture: - #one proposal distr - nextSample = self.curSample + self.propsalDistr.sample() - nextSample = self.targetDistr.boundedValue(nextSample) - else: - #mixture of proposal distr - if random.random() < self.proposalChoiceThreshold: - nextSample = self.curSample + self.propsalDistr.sample() - else: - nextSample = self.curSample + self.globalProposalDistr.sample() - nextSample = self.targetDistr.boundedValue(nextSample) - - return nextSample - - def targetSample(self, nextSample): - """ - target sample - - Parameters - nextSample : proposal distr sample - """ - nextDistr = self.targetDistr.value(nextSample) - - transition = False - if nextDistr > self.curDistr: - transition = True - else: - distrRatio = float(nextDistr) / self.curDistr - if random.random() < distrRatio: - transition = True - - if transition: - self.curSample = nextSample - self.curDistr = nextDistr - self.transCount += 1 - - - def subSample(self, skip): - """ - sub sample - - Parameters - skip : no of samples to skip - """ - nextSample = self.proposalSample(skip) - self.targetSample(nextSample) - return self.curSample; - - def setMixtureProposal(self, globPropStdDev, mixtureThreshold): - """ - mixture proposal - - Parameters - globPropStdDev : global proposal distr std deviation - mixtureThreshold : threshold for using global proposal distribution - """ - self.globalProposalDistr = GaussianRejectSampler(0, globPropStdDev) - self.mixtureThreshold = mixtureThreshold - - def samplePropsal(self): - """ - sample from proposal distr - - """ - if self.globalPropsalDistr is None: - proposal = self.propsalDistr.sample() - else: - if random.random() < self.mixtureThreshold: - proposal = self.propsalDistr.sample() - else: - proposal = self.globalProposalDistr.sample() - - return proposal - -class PermutationSampler: - """ - permutation sampler by shuffling a list - """ - def __init__(self): - """ - initialize - """ - self.values = None - self.numShuffles = None - - @staticmethod - def createSamplerWithValues(values, *numShuffles): - """ - creator with values - - Parameters - values : list data - numShuffles : no of shuffles or range of no of shuffles - """ - sampler = PermutationSampler() - sampler.values = values - sampler.numShuffles = numShuffles - return sampler - - @staticmethod - def createSamplerWithRange(minv, maxv, *numShuffles): - """ - creator with ramge min and max - - Parameters - minv : min of range - maxv : max of range - numShuffles : no of shuffles or range of no of shuffles - """ - sampler = PermutationSampler() - sampler.values = list(range(minv, maxv + 1)) - sampler.numShuffles = numShuffles - return sampler - - def sample(self): - """ - sample new permutation - """ - cloned = self.values.copy() - shuffle(cloned, *self.numShuffles) - return cloned - -class SpikeyDataSampler: - """ - samples spikey data - """ - def __init__(self, intvMean, intvScale, distr, spikeValueMean, spikeValueStd, spikeMaxDuration, baseValue = 0): - """ - initializer - - Parameters - intvMean : interval mean - intvScale : interval std dev - distr : type of distr for interval - spikeValueMean : spike value mean - spikeValueStd : spike value std dev - spikeMaxDuration : max duration for spike - baseValue : base or offset value - """ - if distr == "norm": - self.intvSampler = NormalSampler(intvMean, intvScale) - elif distr == "expo": - rate = 1.0 / intvScale - self.intvSampler = ExponentialSampler(rate) - else: - raise ValueError("invalid distribution") - - self.spikeSampler = NormalSampler(spikeValueMean, spikeValueStd) - self.spikeMaxDuration = spikeMaxDuration - self.baseValue = baseValue - self.inSpike = False - self.spikeCount = 0 - self.baseCount = 0 - self.baseLength = int(self.intvSampler.sample()) - self.spikeValues = list() - self.spikeLength = None - - def sample(self): - """ - sample new value - """ - if self.baseCount <= self.baseLength: - sampled = self.baseValue - self.baseCount += 1 - else: - if not self.inSpike: - #starting spike - spikeVal = self.spikeSampler.sample() - self.spikeLength = sampleUniform(1, self.spikeMaxDuration) - spikeMaxPos = 0 if self.spikeLength == 1 else sampleUniform(0, self.spikeLength-1) - self.spikeValues.clear() - for i in range(self.spikeLength): - if i < spikeMaxPos: - frac = (i + 1) / (spikeMaxPos + 1) - frac = sampleFloatFromBase(frac, 0.1 * frac) - elif i > spikeMaxPos: - frac = (self.spikeLength - i) / (self.spikeLength - spikeMaxPos) - frac = sampleFloatFromBase(frac, 0.1 * frac) - else: - frac = 1.0 - self.spikeValues.append(frac * spikeVal) - self.inSpike = True - self.spikeCount = 0 - - - sampled = self.spikeValues[self.spikeCount] - self.spikeCount += 1 - - if self.spikeCount == self.spikeLength: - #ending spike - self.baseCount = 0 - self.baseLength = int(self.intvSampler.sample()) - self.inSpike = False - - return sampled - - -class EventSampler: - """ - sample event - """ - def __init__(self, intvSampler, valSampler=None): - """ - initializer - - Parameters - intvSampler : interval sampler - valSampler : value sampler - """ - self.intvSampler = intvSampler - self.valSampler = valSampler - self.trigger = int(self.intvSampler.sample()) - self.count = 0 - - def reset(self): - """ - reset trigger - """ - self.trigger = int(self.intvSampler.sample()) - self.count = 0 - - def sample(self): - """ - sample event - """ - if self.count == self.trigger: - sampled = self.valSampler.sample() if self.valSampler is not None else 1.0 - self.trigger = int(self.intvSampler.sample()) - self.count = 0 - else: - sample = 0.0 - self.count += 1 - return sampled - - - - -def createSampler(data): - """ - create sampler - - Parameters - data : sampler description - """ - #print(data) - items = data.split(":") - size = len(items) - dtype = items[-1] - stype = items[-2] - #print("sampler data {}".format(data)) - #print("sampler {}".format(stype)) - sampler = None - if stype == "uniform": - if dtype == "int": - min = int(items[0]) - max = int(items[1]) - sampler = UniformNumericSampler(min, max) - elif dtype == "float": - min = float(items[0]) - max = float(items[1]) - sampler = UniformNumericSampler(min, max) - elif dtype == "categorical": - values = items[:-2] - sampler = UniformCategoricalSampler(values) - elif stype == "normal": - mean = float(items[0]) - sd = float(items[1]) - sampler = NormalSampler(mean, sd) - if dtype == "int": - sampler.sampleAsIntValue() - elif stype == "nonparam": - if dtype == "int" or dtype == "float": - min = int(items[0]) - binWidth = int(items[1]) - values = items[2:-2] - values = list(map(lambda v: int(v), values)) - sampler = NonParamRejectSampler(min, binWidth, values) - if dtype == "float": - sampler.sampleAsFloat() - elif dtype == "categorical": - values = list() - for i in range(0, size-2, 2): - cval = items[i] - dist = int(items[i+1]) - pair = (cval, dist) - values.append(pair) - sampler = CategoricalRejectSampler(values) - elif dtype == "scategorical": - vfpath = items[0] - values = getFileLines(vfpath, None) - sampler = CategoricalSetSampler(values) - elif stype == "discrete": - vmin = int(items[0]) - vmax = int(items[1]) - step = int(items[2]) - values = list(map(lambda i : int(items[i]), range(3, len(items)-2))) - sampler = DiscreteRejectSampler(vmin, vmax, step, values) - elif stype == "bernauli": - pr = float(items[0]) - events = None - if len(items) == 5: - events = list() - if dtype == "int": - events.append(int(items[1])) - events.append(int(items[2])) - elif dtype == "categorical": - events.append(items[1]) - events.append(items[2]) - sampler = BernoulliTrialSampler(pr, events) - else: - raise ValueError("invalid sampler type " + stype) - return sampler - - - - - diff --git a/spaces/ThirdEyeData/TagDiciphering/app.py b/spaces/ThirdEyeData/TagDiciphering/app.py deleted file mode 100644 index 9da21519b22de4a2efbdc70f8e5c080b32c95698..0000000000000000000000000000000000000000 --- a/spaces/ThirdEyeData/TagDiciphering/app.py +++ /dev/null @@ -1,155 +0,0 @@ -import simplejson -import tensorflow -import visualization_utils as vis_util -from PIL import Image -import numpy as np -from PIL import Image -import numpy as np -import label_map_util -import tensorflow as tf -from matplotlib import pyplot as plt -import time -import cv2 -from numpy import asarray -#import streamlit as st -import gradio as gr -#st.title("Tag_Diciphering") -def prediction(image_path): - total_time_start = time.time() - #image_path = path_image - - - def loadImageIntoNumpyArray(image): - (im_width, im_height) = image.size - if image.getdata().mode == "RGBA": - image = image.convert('RGB') - - return asarray(image).reshape((im_height, im_width, 3)).astype(np.uint8) - - - def main(image_path,model_path,model_PATH_TO_CKPT,path_to_labels): - image = Image.open(image_path) - image_np = loadImageIntoNumpyArray(image) - image_np_expanded = np.expand_dims(image_np, axis=0) - label_map = label_map_util.load_labelmap(path_to_labels) - # print("label_map------->",type(label_map)) - categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=100, use_display_name=True) - category_index = label_map_util.create_category_index(categories) - # print("category index-->",category_index) - - detection_graph = tf.Graph() - with detection_graph.as_default(): - od_graph_def = tf.compat.v1.GraphDef() - with tf.compat.v2.io.gfile.GFile(model_PATH_TO_CKPT, 'rb') as fid: - serialized_graph = fid.read() - od_graph_def.ParseFromString(serialized_graph) - tf.import_graph_def(od_graph_def, name='') - sess = tf.compat.v1.Session(graph=detection_graph) - # Input tensor is the image - image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') - # Output tensors are the detection boxes, scores, and classes - # Each box represents a part of the image where a particular object was detected - detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') - # Each score represents level of confidence for each of the objects. - # The score is shown on the result image, together with the class label. - detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') - detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') - # Number of objects detected - num_detections = detection_graph.get_tensor_by_name('num_detections:0') - (boxes, scores, classes, num) = sess.run( - [detection_boxes, detection_scores, detection_classes, num_detections], - feed_dict={image_tensor: image_np_expanded}) - vis_util.visualize_boxes_and_labels_on_image_array( - image_np, - np.squeeze(boxes), - np.squeeze(classes).astype(np.int32), - np.squeeze(scores), - category_index, - use_normalized_coordinates=True, - line_thickness=8, - min_score_thresh=0.1) - #%matplotlib inline - from matplotlib import pyplot as plt - # print("boxes:",boxes) - # print("class:",classes) - objects = [] - threshold = 0.5 - # print("category:",category_index) - boxes = boxes[0] - for index, value in enumerate(classes[0]): - object_dict = {} - if scores[0, index] > threshold: - object_dict["class"] = (category_index.get(value)).get('name') - object_dict["score"] = round(scores[0, index] * 100,2) - box = tuple(boxes[index].tolist()) - ymin, xmin, ymax, xmax= box - im_width,im_height = 360,360 - left, right, top, bottom = (xmin * im_width, xmax * im_width, - ymin * im_height, ymax * im_height) - object_dict["box"] = (int(left), int(right), int(top), int(bottom)) - objects.append(object_dict) - - image_orignal = Image.open(image_path) - image_np_orignal = loadImageIntoNumpyArray(image_orignal) - - - fig, ax = plt.subplots(1,2) - - fig.suptitle('Tag Deciphering') - - ax[0].imshow(image_np_orignal,aspect='auto'); - ax[1].imshow(image_np,aspect='auto'); - - - return objects,image_np - - - - image_path = image_path - model_path = "//inference" - model_PATH_TO_CKPT = "frozen_inference_graph.pb" - path_to_labels = "tf_label_map.pbtxt" - - result,fig = main(image_path,model_path,model_PATH_TO_CKPT,path_to_labels) - - # print("result-",result) - # list_to_be_sorted= [{'class': 'Y', 'score': 99.97, 'box': (157, 191, 269, 288)}, {'class': '6', 'score': 99.93, 'box': (158, 191, 247, 267)}, {'class': '9', 'score': 99.88, 'box': (156, 190, 179, 196)}, {'class': '4', 'score': 99.8, 'box': (156, 189, 198, 219)}, {'class': '1', 'score': 99.65, 'box': (157, 189, 222, 244)}, {'class': 'F', 'score': 63.4, 'box': (155, 185, 157, 175)}] - newlist = sorted(result, key=lambda k: k['box'][3],reverse=False) - - text ='' - for each in newlist: - if(each['score']>65): - text += each['class'] - # print("text:",text) - if(text!=""): - text = text.replace("yellowTag", "") - result = text - else: - result = "No Vertical Tag Detected" - response = {"predictions": [result]} - total_time_end = time.time() - print("total time : ",round((total_time_end-total_time_start),2)) - return simplejson.dumps(response),fig - -inputs = gr.inputs.Image(type = 'filepath') -EXAMPLES = ["img1.jpg","img2.jpg","img6.jpg","img7.jpg","img8.jpg","img4.jpg","img10.jpg"] -DESCRIPTION = """Tag Dicipher is to convert into understandable form. especially to decode the tags to make out -the meaning of despite lack of clearness.""" -outputs = [gr.outputs.Textbox(label = "Prediction"), - gr.outputs.Image(type = 'numpy',label = 'Tag Diciphering')] - -article = "

    Detailed Description

    " -demo_app = gr.Interface( - fn= prediction, - inputs=inputs, - outputs= outputs, - title = "Tag Diciphering", - description = DESCRIPTION, - examples = EXAMPLES, - article = article, - #cache_example = True, - #live = True, - theme = 'huggingface' -) -demo_app.launch() - diff --git a/spaces/Um124/Global_Warming_Analysis/pages/Coal Consumption data Analysis.py b/spaces/Um124/Global_Warming_Analysis/pages/Coal Consumption data Analysis.py deleted file mode 100644 index b9bb82d772d534747c3a47af5806e9d00c84ff9e..0000000000000000000000000000000000000000 --- a/spaces/Um124/Global_Warming_Analysis/pages/Coal Consumption data Analysis.py +++ /dev/null @@ -1,87 +0,0 @@ -import pandas as pd -import numpy as np -import plotly.express as px -import streamlit as st - - -st.set_page_config( - page_title='Coal Consumption data Analysis', - page_icon='📈', - layout='wide' -) - -Years=['1965','1966','1967','1968','1969','1970','1971','1972','1973','1974','1975','1976','1977','1978','1979', -'1980','1981','1982','1983','1984','1985','1986','1987','1988','1989','1990','1991','1992','1993','1994','1995', -'1996','1997','1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011', -'2012','2013','2014','2015','2016'] - -@st.cache_data -def load_data(): - df=pd.read_csv('data/coal_consumption_per_cap.csv') - df.rename({'geo':'Country'},axis=1,inplace=True) - df.set_index('Country',inplace=True) - df.sort_values('Country',inplace=True) - df['Total']=df[Years].sum(axis=1) - df['Average']=df.mean(axis=1) - df['Minimum']=df.min(axis=1) - df['Maximum']=df.max(axis=1) - return df - -st.title('Coal Consumption Per Capital') -df=load_data() -st.dataframe(df,use_container_width=True) - -countries=df.index.unique().tolist() -Graphs = ['bar','pie','line','area','funnel'] -c1,c2=st.columns(2) -country = c1.selectbox("Select a Country",countries) -Graph = c2.selectbox("Select a Graph type",Graphs) - - -st.header("Country wise visualization") -cdf = df.loc[country,Years].reset_index() -cdf.rename({'index':'Years'},axis=1, inplace=True) -if Graph == Graphs[0]: - fig = px.bar(cdf, 'Years',country, title=f'{country} coal consumption per cap') -if Graph == Graphs[1]: - fig = px.pie(cdf, 'Years',country, title=f'{country} coal consumption per cap') -if Graph == Graphs[2]: - fig = px.line(cdf, 'Years',country, title=f'{country} coal consumption per cap') -if Graph == Graphs[3]: - fig = px.area(cdf, 'Years',country, title=f'{country} coal consumption per cap') -if Graph == Graphs[4]: - fig = px.funnel(cdf, 'Years',country, title=f'{country} co2 emissions tonnes by per person') - -st.plotly_chart(fig, use_container_width=True) - - -st.header("Comparison of Countries") -clist = st.multiselect("Select countries to compare", countries, default='India') -cdf = df.loc[clist, Years].T # T to rotate the data in 90deg -st.write(cdf) -figc = px.line(cdf,cdf.index, clist, title=f'Comparing {", ".join(clist)}') -st.plotly_chart(figc, use_container_width=True) - -df.sort_values(by='Total', ascending=False, inplace=True) -fig1=px.bar(df, x=df.index, y='Total',title='Total coal consumption per cap by Country') -st.plotly_chart(fig1, use_container_width=True) - -dfavg = df.sort_values(by='Average').reset_index() -dfavg.rename({'index':'Country'},axis=1,inplace=True) -fig2=px.bar(dfavg, 'Country', 'Average', title="Average coal consumption per cap by Country") -st.plotly_chart(fig2, use_container_width=True) - -dfmin=df.sort_values(by='Minimum').reset_index() -dfmin.rename({'index':'Country'},axis=1,inplace=True) -fig3=px.bar(dfmin,'Country','Minimum',title='Minimum coal consumption by Country' ) -st.plotly_chart(fig3, use_container_width=True) - -dfmax=df.sort_values(by='Maximum').reset_index() -dfmax.rename({'index':'Country'},axis=1,inplace=True) -fig4=px.bar(dfmax,'Country','Maximum',title='Maximum coal consumption by Country' ) -st.plotly_chart(fig4, use_container_width=True) - -dfcomp=df.sort_values(by='Country',ascending=False,inplace=True) -fig5 = px.line(df, x=df.index, y='Maximum',title='Maximum and Minimum coal consumption comparisons') -fig5.add_scatter(x=df.index, y=df['Minimum'], mode='lines',) -st.plotly_chart(fig5, use_container_width=True) \ No newline at end of file diff --git a/spaces/Usaki108/VoiceChange/infer_pack/modules/F0Predictor/HarvestF0Predictor.py b/spaces/Usaki108/VoiceChange/infer_pack/modules/F0Predictor/HarvestF0Predictor.py deleted file mode 100644 index 98d4e98b353008f81bde2c37e7da818763a992c9..0000000000000000000000000000000000000000 --- a/spaces/Usaki108/VoiceChange/infer_pack/modules/F0Predictor/HarvestF0Predictor.py +++ /dev/null @@ -1,86 +0,0 @@ -from infer_pack.modules.F0Predictor.F0Predictor import F0Predictor -import pyworld -import numpy as np - - -class HarvestF0Predictor(F0Predictor): - def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100): - self.hop_length = hop_length - self.f0_min = f0_min - self.f0_max = f0_max - self.sampling_rate = sampling_rate - - def interpolate_f0(self, f0): - """ - 对F0进行插值处理 - """ - - data = np.reshape(f0, (f0.size, 1)) - - vuv_vector = np.zeros((data.size, 1), dtype=np.float32) - vuv_vector[data > 0.0] = 1.0 - vuv_vector[data <= 0.0] = 0.0 - - ip_data = data - - frame_number = data.size - last_value = 0.0 - for i in range(frame_number): - if data[i] <= 0.0: - j = i + 1 - for j in range(i + 1, frame_number): - if data[j] > 0.0: - break - if j < frame_number - 1: - if last_value > 0.0: - step = (data[j] - data[i - 1]) / float(j - i) - for k in range(i, j): - ip_data[k] = data[i - 1] + step * (k - i + 1) - else: - for k in range(i, j): - ip_data[k] = data[j] - else: - for k in range(i, frame_number): - ip_data[k] = last_value - else: - ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝 - last_value = data[i] - - return ip_data[:, 0], vuv_vector[:, 0] - - def resize_f0(self, x, target_len): - source = np.array(x) - source[source < 0.001] = np.nan - target = np.interp( - np.arange(0, len(source) * target_len, len(source)) / target_len, - np.arange(0, len(source)), - source, - ) - res = np.nan_to_num(target) - return res - - def compute_f0(self, wav, p_len=None): - if p_len is None: - p_len = wav.shape[0] // self.hop_length - f0, t = pyworld.harvest( - wav.astype(np.double), - fs=self.hop_length, - f0_ceil=self.f0_max, - f0_floor=self.f0_min, - frame_period=1000 * self.hop_length / self.sampling_rate, - ) - f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.fs) - return self.interpolate_f0(self.resize_f0(f0, p_len))[0] - - def compute_f0_uv(self, wav, p_len=None): - if p_len is None: - p_len = wav.shape[0] // self.hop_length - f0, t = pyworld.harvest( - wav.astype(np.double), - fs=self.sampling_rate, - f0_floor=self.f0_min, - f0_ceil=self.f0_max, - frame_period=1000 * self.hop_length / self.sampling_rate, - ) - f0 = pyworld.stonemask(wav.astype(np.double), f0, t, self.sampling_rate) - return self.interpolate_f0(self.resize_f0(f0, p_len)) diff --git a/spaces/Vegecken/sovits4dzl/vdecoder/__init__.py b/spaces/Vegecken/sovits4dzl/vdecoder/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Vision-CAIR/MiniGPT-v2/minigpt4/datasets/datasets/dataloader_utils.py b/spaces/Vision-CAIR/MiniGPT-v2/minigpt4/datasets/datasets/dataloader_utils.py deleted file mode 100644 index 8eaa3a58b0ad42ca7937fb51b46e53511cc3cd0c..0000000000000000000000000000000000000000 --- a/spaces/Vision-CAIR/MiniGPT-v2/minigpt4/datasets/datasets/dataloader_utils.py +++ /dev/null @@ -1,162 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import time -import random -import torch -from minigpt4.datasets.data_utils import move_to_cuda -from torch.utils.data import DataLoader - - -class MultiIterLoader: - """ - A simple wrapper for iterating over multiple iterators. - - Args: - loaders (List[Loader]): List of Iterator loaders. - ratios (List[float]): List of ratios to sample from each loader. If None, all loaders are sampled uniformly. - """ - - def __init__(self, loaders, ratios=None): - # assert all loaders has __next__ method - for loader in loaders: - assert hasattr( - loader, "__next__" - ), "Loader {} has no __next__ method.".format(loader) - - if ratios is None: - ratios = [1.0] * len(loaders) - else: - assert len(ratios) == len(loaders) - ratios = [float(ratio) / sum(ratios) for ratio in ratios] - - self.loaders = loaders - self.ratios = ratios - - def __next__(self): - # random sample from each loader by ratio - loader_idx = random.choices(range(len(self.loaders)), self.ratios, k=1)[0] - return next(self.loaders[loader_idx]) - - -class PrefetchLoader(object): - """ - Modified from https://github.com/ChenRocks/UNITER. - - overlap compute and cuda data transfer - (copied and then modified from nvidia apex) - """ - - def __init__(self, loader): - self.loader = loader - self.stream = torch.cuda.Stream() - - def __iter__(self): - loader_it = iter(self.loader) - self.preload(loader_it) - batch = self.next(loader_it) - while batch is not None: - is_tuple = isinstance(batch, tuple) - if is_tuple: - task, batch = batch - - if is_tuple: - yield task, batch - else: - yield batch - batch = self.next(loader_it) - - def __len__(self): - return len(self.loader) - - def preload(self, it): - try: - self.batch = next(it) - except StopIteration: - self.batch = None - return - # if record_stream() doesn't work, another option is to make sure - # device inputs are created on the main stream. - # self.next_input_gpu = torch.empty_like(self.next_input, - # device='cuda') - # self.next_target_gpu = torch.empty_like(self.next_target, - # device='cuda') - # Need to make sure the memory allocated for next_* is not still in use - # by the main stream at the time we start copying to next_*: - # self.stream.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(self.stream): - self.batch = move_to_cuda(self.batch) - # more code for the alternative if record_stream() doesn't work: - # copy_ will record the use of the pinned source tensor in this - # side stream. - # self.next_input_gpu.copy_(self.next_input, non_blocking=True) - # self.next_target_gpu.copy_(self.next_target, non_blocking=True) - # self.next_input = self.next_input_gpu - # self.next_target = self.next_target_gpu - - def next(self, it): - torch.cuda.current_stream().wait_stream(self.stream) - batch = self.batch - if batch is not None: - record_cuda_stream(batch) - self.preload(it) - return batch - - def __getattr__(self, name): - method = self.loader.__getattribute__(name) - return method - - -def record_cuda_stream(batch): - if isinstance(batch, torch.Tensor): - batch.record_stream(torch.cuda.current_stream()) - elif isinstance(batch, list) or isinstance(batch, tuple): - for t in batch: - record_cuda_stream(t) - elif isinstance(batch, dict): - for t in batch.values(): - record_cuda_stream(t) - else: - pass - - -class IterLoader: - """ - A wrapper to convert DataLoader as an infinite iterator. - - Modified from: - https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/iter_based_runner.py - """ - - def __init__(self, dataloader: DataLoader, use_distributed: bool = False): - self._dataloader = dataloader - self.iter_loader = iter(self._dataloader) - self._use_distributed = use_distributed - self._epoch = 0 - - @property - def epoch(self) -> int: - return self._epoch - - def __next__(self): - try: - data = next(self.iter_loader) - except StopIteration: - self._epoch += 1 - if hasattr(self._dataloader.sampler, "set_epoch") and self._use_distributed: - self._dataloader.sampler.set_epoch(self._epoch) - time.sleep(2) # Prevent possible deadlock during epoch transition - self.iter_loader = iter(self._dataloader) - data = next(self.iter_loader) - - return data - - def __iter__(self): - return self - - def __len__(self): - return len(self._dataloader) diff --git a/spaces/Vision-CAIR/MiniGPT-v2/minigpt4/models/base_model.py b/spaces/Vision-CAIR/MiniGPT-v2/minigpt4/models/base_model.py deleted file mode 100644 index 95902848162c28992fa36b2648b4c280e3a98d39..0000000000000000000000000000000000000000 --- a/spaces/Vision-CAIR/MiniGPT-v2/minigpt4/models/base_model.py +++ /dev/null @@ -1,250 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import os -import logging -import contextlib - -from omegaconf import OmegaConf -import numpy as np -import torch -import torch.nn as nn -from transformers import BertTokenizer, LlamaTokenizer -from transformers.models.llama.modeling_llama import LlamaForCausalLM -from peft import ( - LoraConfig, - get_peft_model, - prepare_model_for_int8_training, -) - -from minigpt4.common.dist_utils import download_cached_file, is_dist_avail_and_initialized -from minigpt4.common.utils import get_abs_path, is_url -from minigpt4.models.eva_vit import create_eva_vit_g - - - -class BaseModel(nn.Module): - """Base class for models.""" - - def __init__(self): - super().__init__() - - @property - def device(self): - return list(self.parameters())[-1].device - - def load_checkpoint(self, url_or_filename): - """ - Load from a finetuned checkpoint. - - This should expect no mismatch in the model keys and the checkpoint keys. - """ - - if is_url(url_or_filename): - cached_file = download_cached_file( - url_or_filename, check_hash=False, progress=True - ) - checkpoint = torch.load(cached_file, map_location="cpu") - elif os.path.isfile(url_or_filename): - checkpoint = torch.load(url_or_filename, map_location="cpu") - else: - raise RuntimeError("checkpoint url or path is invalid") - - if "model" in checkpoint.keys(): - state_dict = checkpoint["model"] - else: - state_dict = checkpoint - - msg = self.load_state_dict(state_dict, strict=False) - - logging.info("Missing keys {}".format(msg.missing_keys)) - logging.info("load checkpoint from %s" % url_or_filename) - - return msg - - @classmethod - def from_pretrained(cls, model_type): - """ - Build a pretrained model from default configuration file, specified by model_type. - - Args: - - model_type (str): model type, specifying architecture and checkpoints. - - Returns: - - model (nn.Module): pretrained or finetuned model, depending on the configuration. - """ - model_cfg = OmegaConf.load(cls.default_config_path(model_type)).model - model = cls.from_config(model_cfg) - - return model - - @classmethod - def default_config_path(cls, model_type): - assert ( - model_type in cls.PRETRAINED_MODEL_CONFIG_DICT - ), "Unknown model type {}".format(model_type) - return get_abs_path(cls.PRETRAINED_MODEL_CONFIG_DICT[model_type]) - - def load_checkpoint_from_config(self, cfg, **kwargs): - """ - Load checkpoint as specified in the config file. - - If load_finetuned is True, load the finetuned model; otherwise, load the pretrained model. - When loading the pretrained model, each task-specific architecture may define their - own load_from_pretrained() method. - """ - load_finetuned = cfg.get("load_finetuned", True) - if load_finetuned: - finetune_path = cfg.get("finetuned", None) - assert ( - finetune_path is not None - ), "Found load_finetuned is True, but finetune_path is None." - self.load_checkpoint(url_or_filename=finetune_path) - else: - # load pre-trained weights - pretrain_path = cfg.get("pretrained", None) - assert "Found load_finetuned is False, but pretrain_path is None." - self.load_from_pretrained(url_or_filename=pretrain_path, **kwargs) - - def before_evaluation(self, **kwargs): - pass - - def show_n_params(self, return_str=True): - tot = 0 - for p in self.parameters(): - w = 1 - for x in p.shape: - w *= x - tot += w - if return_str: - if tot >= 1e6: - return "{:.1f}M".format(tot / 1e6) - else: - return "{:.1f}K".format(tot / 1e3) - else: - return tot - - def maybe_autocast(self, dtype=torch.float16): - # if on cpu, don't use autocast - # if on gpu, use autocast with dtype if provided, otherwise use torch.float16 - enable_autocast = self.device != torch.device("cpu") - - if enable_autocast: - return torch.cuda.amp.autocast(dtype=dtype) - else: - return contextlib.nullcontext() - - @classmethod - def init_vision_encoder( - cls, model_name, img_size, drop_path_rate, use_grad_checkpoint, precision, freeze - ): - logging.info('Loading VIT') - - assert model_name == "eva_clip_g", "vit model must be eva_clip_g for current version of MiniGPT-4" - if not freeze: - precision = "fp32" # fp16 is not for training - - visual_encoder = create_eva_vit_g( - img_size, drop_path_rate, use_grad_checkpoint, precision - ) - - ln_vision = LayerNorm(visual_encoder.num_features) - - if freeze: - for name, param in visual_encoder.named_parameters(): - param.requires_grad = False - visual_encoder = visual_encoder.eval() - visual_encoder.train = disabled_train - for name, param in ln_vision.named_parameters(): - param.requires_grad = False - ln_vision = ln_vision.eval() - ln_vision.train = disabled_train - logging.info("freeze vision encoder") - - logging.info('Loading VIT Done') - return visual_encoder, ln_vision - - def init_llm(cls, llama_model_path, low_resource=False, low_res_device=0, lora_r=0, - lora_target_modules=["q_proj","v_proj"], **lora_kargs): - logging.info('Loading LLAMA') - llama_tokenizer = LlamaTokenizer.from_pretrained("Vision-CAIR/llama-2-7b-chat-pytorch", use_fast=False, use_auth_token=True) - llama_tokenizer.pad_token = "$$" - - if low_resource: - llama_model = LlamaForCausalLM.from_pretrained( - "Vision-CAIR/llama-2-7b-chat-pytorch", - torch_dtype=torch.float16, - load_in_8bit=True, - device_map={'': low_res_device}, - use_auth_token=True - ) - else: - llama_model = LlamaForCausalLM.from_pretrained( - "Vision-CAIR/llama-2-7b-chat-pytorch", - torch_dtype=torch.float16, - use_auth_token=True - ) - - if lora_r > 0: - llama_model = prepare_model_for_int8_training(llama_model) - loraconfig = LoraConfig( - r=lora_r, - bias="none", - task_type="CAUSAL_LM", - target_modules=lora_target_modules, - **lora_kargs - ) - llama_model = get_peft_model(llama_model, loraconfig) - - llama_model.print_trainable_parameters() - - else: - for name, param in llama_model.named_parameters(): - param.requires_grad = False - logging.info('Loading LLAMA Done') - return llama_model, llama_tokenizer - - - def load_from_pretrained(self, url_or_filename): - if is_url(url_or_filename): - cached_file = download_cached_file( - url_or_filename, check_hash=False, progress=True - ) - checkpoint = torch.load(cached_file, map_location="cpu") - elif os.path.isfile(url_or_filename): - checkpoint = torch.load(url_or_filename, map_location="cpu") - else: - raise RuntimeError("checkpoint url or path is invalid") - - state_dict = checkpoint["model"] - - msg = self.load_state_dict(state_dict, strict=False) - - # logging.info("Missing keys {}".format(msg.missing_keys)) - logging.info("load checkpoint from %s" % url_or_filename) - - return msg - - -def disabled_train(self, mode=True): - """Overwrite model.train with this function to make sure train/eval mode - does not change anymore.""" - return self - - -class LayerNorm(nn.LayerNorm): - """Subclass torch's LayerNorm to handle fp16.""" - - def forward(self, x: torch.Tensor): - orig_type = x.dtype - ret = super().forward(x.type(torch.float32)) - return ret.type(orig_type) - - - - - diff --git a/spaces/Xinyoumeng233hu/SteganographywithGPT-2/huffman_baseline.py b/spaces/Xinyoumeng233hu/SteganographywithGPT-2/huffman_baseline.py deleted file mode 100644 index 443bbce661fc66ed615c9e840c692d4677238539..0000000000000000000000000000000000000000 --- a/spaces/Xinyoumeng233hu/SteganographywithGPT-2/huffman_baseline.py +++ /dev/null @@ -1,166 +0,0 @@ -import torch -import torch.nn.functional as F - -from huffman import HuffmanCoding -from utils import kl, entropy, is_sent_finish, limit_past - -def encode_huffman(model, enc, message, context, bits_per_word, finish_sent=False, device='cpu'): - length = len(message) - - context = torch.tensor(context[-1022:], device=device, dtype=torch.long) - - prev = context - output = context - past = None - - total_num = 0 - total_num_for_stats = 0 - total_log_probs = 0 - total_kl = 0 # in bits - total_num_sents = 0 - - with torch.no_grad(): - i = 0 - sent_finish = False - while i < length or (finish_sent and not sent_finish): - logits, past = model(prev.unsqueeze(0), past=past) - past = limit_past(past) - logits[0, -1, -1] = -1e10 # endoftext can't happen - logits[0, -1, 628] = -1e10 # 2 newlines can't happen - logits, indices = logits[0, -1, :].sort(descending=True) - - # Get the top 2**bits options - indices = indices[:2**bits_per_word] - log_probs = F.log_softmax(logits, dim=-1)[:2**bits_per_word] - probs = torch.exp(log_probs) - - if i >= length: - selection = 0 - sent_finish = is_sent_finish(indices[0].item(), enc) - else: - probs_array = probs.cpu().numpy() - coding = HuffmanCoding() - coding.make_heap_from_array(probs_array) - coding.merge_nodes() - root = coding.make_codes() - - #print(message[i:i+10]) - while root.token is None: - if i >= length or message[i] == 0: - root = root.left - else: - root = root.right - i += 1 - selection = root.token - - logq = torch.tensor([-len(coding.codes[idx]) for idx in range(len(probs_array))], dtype=torch.float, device=device) # in bits - logq = logq*0.69315 # in nats - q = torch.exp(logq) - total_kl += kl(q, logq, log_probs) - total_log_probs += log_probs[selection].item() - total_num_for_stats += 1 - - total_num += 1 - - prev = indices[selection].view(1) - output = torch.cat((output, prev)) - - avg_NLL = -total_log_probs/total_num_for_stats - avg_KL = total_kl/total_num_for_stats - words_per_bit = total_num_for_stats/i - - return output[len(context):].tolist(), avg_NLL, avg_KL, words_per_bit - -def decode_huffman(model, enc, text, context, bits_per_word, device='cpu'): - # inp is a list of token indices - # context is a list of token indices - inp = enc.encode(text) - i = 0 - while i < len(inp): - if inp[i] == 628: - inp[i] = 198 - inp[i+1:i+1] = [198] - i += 2 - else: - i += 1 - - context = torch.tensor(context[-1022:], device=device, dtype=torch.long) - prev = context - past = None - - message = [] - with torch.no_grad(): - i = 0 - while i < len(inp): - if past and past[0].shape[3] >= 1023: - raise RuntimeError - - logits, past = model(prev.unsqueeze(0), past=past) - past = limit_past(past) - logits[0, -1, -1] = -1e10 # endoftext can't happen - logits[0, -1, 628] = -1e10 # 2 newlines can't happen - logits, indices = logits[0, -1, :].sort(descending=True) - - # Get the top 2**bits options - indices = indices[:2**bits_per_word] - log_probs = F.log_softmax(logits, dim=-1)[:2**bits_per_word] - probs = torch.exp(log_probs) - - if inp[i] not in indices: - true_token_text = enc.decoder[inp[i]] - for rank_idx in range(2**bits_per_word): - prop_token_text = enc.decoder[indices[rank_idx].item()] - # common case that is not caught - if inp[i] == 128 and indices[rank_idx] == 198: - rank = rank_idx - inp[i] = indices[rank_idx].item() - break - - # Is there a more likely prefix token that could be the actual token generated? - if len(prop_token_text) <= len(true_token_text) and \ - prop_token_text == true_token_text[:len(prop_token_text)]: - rank = rank_idx - suffix = true_token_text[len(prop_token_text):] - suffix_tokens = enc.encode(suffix) # a list - inp[i] = indices[rank_idx].item() - inp[i+1:i+1] = suffix_tokens # insert suffix tokens into list - break - - # Is there a more likely longer token that could be the actual token generated? - elif len(prop_token_text) > len(true_token_text) and \ - true_token_text == prop_token_text[:len(true_token_text)]: - whole_text = true_token_text - num_extra = 1 - while len(whole_text) < len(prop_token_text): - whole_text += enc.decoder[inp[i+num_extra]] - num_extra += 1 - if prop_token_text == whole_text[:len(prop_token_text)]: - rank = rank_idx - inp[i] = indices[rank_idx].item() - for j in range(1, num_extra): - del inp[i+j] - - if len(whole_text) > len(prop_token_text): - suffix = whole_text[len(prop_token_text):] - suffix_tokens = enc.encode(suffix) # a list - inp[i+1:i+1] = suffix_tokens # insert suffix tokens into list - break - else: - print('Unable to fix BPE error: token received: %s=%d, text: %s' % (true_token_text, inp[i], text)) - rank = 0 - else: - rank = (indices == inp[i]).nonzero().item() - - probs_array = probs.cpu().numpy() - coding = HuffmanCoding() - coding.make_heap_from_array(probs_array) - coding.merge_nodes() - coding.make_codes() - - tokens_t = map(int, coding.codes[rank]) - - message.extend(tokens_t) - prev = torch.tensor([inp[i]], device=device, dtype=torch.long) - i += 1 - - return message diff --git a/spaces/XlalalaX/VITS-Umamusume-voice-synthesizer/text/sanskrit.py b/spaces/XlalalaX/VITS-Umamusume-voice-synthesizer/text/sanskrit.py deleted file mode 100644 index 0223aaac384a2f850f5bc20651fc18eb964607d0..0000000000000000000000000000000000000000 --- a/spaces/XlalalaX/VITS-Umamusume-voice-synthesizer/text/sanskrit.py +++ /dev/null @@ -1,62 +0,0 @@ -import re -from indic_transliteration import sanscript - - -# List of (iast, ipa) pairs: -_iast_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('a', 'ə'), - ('ā', 'aː'), - ('ī', 'iː'), - ('ū', 'uː'), - ('ṛ', 'ɹ`'), - ('ṝ', 'ɹ`ː'), - ('ḷ', 'l`'), - ('ḹ', 'l`ː'), - ('e', 'eː'), - ('o', 'oː'), - ('k', 'k⁼'), - ('k⁼h', 'kʰ'), - ('g', 'g⁼'), - ('g⁼h', 'gʰ'), - ('ṅ', 'ŋ'), - ('c', 'ʧ⁼'), - ('ʧ⁼h', 'ʧʰ'), - ('j', 'ʥ⁼'), - ('ʥ⁼h', 'ʥʰ'), - ('ñ', 'n^'), - ('ṭ', 't`⁼'), - ('t`⁼h', 't`ʰ'), - ('ḍ', 'd`⁼'), - ('d`⁼h', 'd`ʰ'), - ('ṇ', 'n`'), - ('t', 't⁼'), - ('t⁼h', 'tʰ'), - ('d', 'd⁼'), - ('d⁼h', 'dʰ'), - ('p', 'p⁼'), - ('p⁼h', 'pʰ'), - ('b', 'b⁼'), - ('b⁼h', 'bʰ'), - ('y', 'j'), - ('ś', 'ʃ'), - ('ṣ', 's`'), - ('r', 'ɾ'), - ('l̤', 'l`'), - ('h', 'ɦ'), - ("'", ''), - ('~', '^'), - ('ṃ', '^') -]] - - -def devanagari_to_ipa(text): - text = text.replace('ॐ', 'ओम्') - text = re.sub(r'\s*।\s*$', '.', text) - text = re.sub(r'\s*।\s*', ', ', text) - text = re.sub(r'\s*॥', '.', text) - text = sanscript.transliterate(text, sanscript.DEVANAGARI, sanscript.IAST) - for regex, replacement in _iast_to_ipa: - text = re.sub(regex, replacement, text) - text = re.sub('(.)[`ː]*ḥ', lambda x: x.group(0) - [:-1]+'h'+x.group(1)+'*', text) - return text diff --git a/spaces/XzJosh/TianDou-Bert-VITS2/modules.py b/spaces/XzJosh/TianDou-Bert-VITS2/modules.py deleted file mode 100644 index 92e0f32a51c472bfd1659a50a95a95d195281d2b..0000000000000000000000000000000000000000 --- a/spaces/XzJosh/TianDou-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/YiYiXu/it-happened-one-frame-2/README.md b/spaces/YiYiXu/it-happened-one-frame-2/README.md deleted file mode 100644 index 7522b13f182ec0c6f8674722c36c6d6b7e69839d..0000000000000000000000000000000000000000 --- a/spaces/YiYiXu/it-happened-one-frame-2/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: It Happened One Frame 2 -emoji: 🐠 -colorFrom: red -colorTo: red -sdk: gradio -sdk_version: 3.0.11 -app_file: app.py -pinned: false -license: afl-3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/Yudha515/Rvc-Models/audiocraft/data/audio_utils.py b/spaces/Yudha515/Rvc-Models/audiocraft/data/audio_utils.py deleted file mode 100644 index 76d4bc2a33ce722d879db2af33cd1336bd6b1fb3..0000000000000000000000000000000000000000 --- a/spaces/Yudha515/Rvc-Models/audiocraft/data/audio_utils.py +++ /dev/null @@ -1,174 +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 sys -import typing as tp - -import julius -import torch -import torchaudio - - -def convert_audio_channels(wav: torch.Tensor, channels: int = 2) -> torch.Tensor: - """Convert audio to the given number of channels. - - Args: - wav (torch.Tensor): Audio wave of shape [B, C, T]. - channels (int): Expected number of channels as output. - Returns: - torch.Tensor: Downmixed or unchanged audio wave [B, C, T]. - """ - *shape, src_channels, length = wav.shape - if src_channels == channels: - pass - elif channels == 1: - # Case 1: - # The caller asked 1-channel audio, and the stream has multiple - # channels, downmix all channels. - wav = wav.mean(dim=-2, keepdim=True) - elif src_channels == 1: - # Case 2: - # The caller asked for multiple channels, but the input file has - # a single channel, replicate the audio over all channels. - wav = wav.expand(*shape, channels, length) - elif src_channels >= channels: - # Case 3: - # The caller asked for multiple channels, and the input file has - # more channels than requested. In that case return the first channels. - wav = wav[..., :channels, :] - else: - # Case 4: What is a reasonable choice here? - raise ValueError('The audio file has less channels than requested but is not mono.') - return wav - - -def convert_audio(wav: torch.Tensor, from_rate: float, - to_rate: float, to_channels: int) -> torch.Tensor: - """Convert audio to new sample rate and number of audio channels. - """ - wav = julius.resample_frac(wav, int(from_rate), int(to_rate)) - wav = convert_audio_channels(wav, to_channels) - return wav - - -def normalize_loudness(wav: torch.Tensor, sample_rate: int, loudness_headroom_db: float = 14, - loudness_compressor: bool = False, energy_floor: float = 2e-3): - """Normalize an input signal to a user loudness in dB LKFS. - Audio loudness is defined according to the ITU-R BS.1770-4 recommendation. - - Args: - wav (torch.Tensor): Input multichannel audio data. - sample_rate (int): Sample rate. - loudness_headroom_db (float): Target loudness of the output in dB LUFS. - loudness_compressor (bool): Uses tanh for soft clipping. - energy_floor (float): anything below that RMS level will not be rescaled. - Returns: - output (torch.Tensor): Loudness normalized output data. - """ - energy = wav.pow(2).mean().sqrt().item() - if energy < energy_floor: - return wav - transform = torchaudio.transforms.Loudness(sample_rate) - input_loudness_db = transform(wav).item() - # calculate the gain needed to scale to the desired loudness level - delta_loudness = -loudness_headroom_db - input_loudness_db - gain = 10.0 ** (delta_loudness / 20.0) - output = gain * wav - if loudness_compressor: - output = torch.tanh(output) - assert output.isfinite().all(), (input_loudness_db, wav.pow(2).mean().sqrt()) - return output - - -def _clip_wav(wav: torch.Tensor, log_clipping: bool = False, stem_name: tp.Optional[str] = None) -> None: - """Utility function to clip the audio with logging if specified.""" - max_scale = wav.abs().max() - if log_clipping and max_scale > 1: - clamp_prob = (wav.abs() > 1).float().mean().item() - print(f"CLIPPING {stem_name or ''} happening with proba (a bit of clipping is okay):", - clamp_prob, "maximum scale: ", max_scale.item(), file=sys.stderr) - wav.clamp_(-1, 1) - - -def normalize_audio(wav: torch.Tensor, normalize: bool = True, - strategy: str = 'peak', peak_clip_headroom_db: float = 1, - rms_headroom_db: float = 18, loudness_headroom_db: float = 14, - loudness_compressor: bool = False, log_clipping: bool = False, - sample_rate: tp.Optional[int] = None, - stem_name: tp.Optional[str] = None) -> torch.Tensor: - """Normalize the audio according to the prescribed strategy (see after). - - Args: - wav (torch.Tensor): Audio data. - normalize (bool): if `True` (default), normalizes according to the prescribed - strategy (see after). If `False`, the strategy is only used in case clipping - would happen. - strategy (str): Can be either 'clip', 'peak', or 'rms'. Default is 'peak', - i.e. audio is normalized by its largest value. RMS normalizes by root-mean-square - with extra headroom to avoid clipping. 'clip' just clips. - peak_clip_headroom_db (float): Headroom in dB when doing 'peak' or 'clip' strategy. - rms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much larger - than the `peak_clip` one to avoid further clipping. - loudness_headroom_db (float): Target loudness for loudness normalization. - loudness_compressor (bool): If True, uses tanh based soft clipping. - log_clipping (bool): If True, basic logging on stderr when clipping still - occurs despite strategy (only for 'rms'). - sample_rate (int): Sample rate for the audio data (required for loudness). - stem_name (Optional[str]): Stem name for clipping logging. - Returns: - torch.Tensor: Normalized audio. - """ - scale_peak = 10 ** (-peak_clip_headroom_db / 20) - scale_rms = 10 ** (-rms_headroom_db / 20) - if strategy == 'peak': - rescaling = (scale_peak / wav.abs().max()) - if normalize or rescaling < 1: - wav = wav * rescaling - elif strategy == 'clip': - wav = wav.clamp(-scale_peak, scale_peak) - elif strategy == 'rms': - mono = wav.mean(dim=0) - rescaling = scale_rms / mono.pow(2).mean().sqrt() - if normalize or rescaling < 1: - wav = wav * rescaling - _clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name) - elif strategy == 'loudness': - assert sample_rate is not None, "Loudness normalization requires sample rate." - wav = normalize_loudness(wav, sample_rate, loudness_headroom_db, loudness_compressor) - _clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name) - else: - assert wav.abs().max() < 1 - assert strategy == '' or strategy == 'none', f"Unexpected strategy: '{strategy}'" - return wav - - -def f32_pcm(wav: torch.Tensor) -> torch.Tensor: - """Convert audio to float 32 bits PCM format. - """ - if wav.dtype.is_floating_point: - return wav - else: - assert wav.dtype == torch.int16 - return wav.float() / 2**15 - - -def i16_pcm(wav: torch.Tensor) -> torch.Tensor: - """Convert audio to int 16 bits PCM format. - - ..Warning:: There exist many formula for doing this convertion. None are perfect - due to the asymetry of the int16 range. One either have possible clipping, DC offset, - or inconsistancies with f32_pcm. If the given wav doesn't have enough headroom, - it is possible that `i16_pcm(f32_pcm)) != Identity`. - """ - if wav.dtype.is_floating_point: - assert wav.abs().max() <= 1 - candidate = (wav * 2 ** 15).round() - if candidate.max() >= 2 ** 15: # clipping would occur - candidate = (wav * (2 ** 15 - 1)).round() - return candidate.short() - else: - assert wav.dtype == torch.int16 - return wav diff --git a/spaces/Zengyf-CVer/Streamlit_YOLOv5_Model2x/utils/autobatch.py b/spaces/Zengyf-CVer/Streamlit_YOLOv5_Model2x/utils/autobatch.py deleted file mode 100644 index 641b055b9fe35f2dfa80b13746f616fb6ce3cad9..0000000000000000000000000000000000000000 --- a/spaces/Zengyf-CVer/Streamlit_YOLOv5_Model2x/utils/autobatch.py +++ /dev/null @@ -1,69 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -Auto-batch utils -""" - -from copy import deepcopy - -import numpy as np -import torch - -from utils.general import LOGGER, colorstr -from utils.torch_utils import profile - - -def check_train_batch_size(model, imgsz=640, amp=True): - # Check YOLOv5 training batch size - with torch.cuda.amp.autocast(amp): - return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size - - -def autobatch(model, imgsz=640, fraction=0.8, batch_size=16): - # Automatically estimate best batch size to use `fraction` of available CUDA memory - # Usage: - # import torch - # from utils.autobatch import autobatch - # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False) - # print(autobatch(model)) - - # Check device - prefix = colorstr('AutoBatch: ') - LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}') - device = next(model.parameters()).device # get model device - if device.type == 'cpu': - LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}') - return batch_size - - # Inspect CUDA memory - gb = 1 << 30 # bytes to GiB (1024 ** 3) - d = str(device).upper() # 'CUDA:0' - properties = torch.cuda.get_device_properties(device) # device properties - t = properties.total_memory / gb # GiB total - r = torch.cuda.memory_reserved(device) / gb # GiB reserved - a = torch.cuda.memory_allocated(device) / gb # GiB allocated - f = t - (r + a) # GiB free - LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free') - - # Profile batch sizes - batch_sizes = [1, 2, 4, 8, 16] - try: - img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes] - results = profile(img, model, n=3, device=device) - except Exception as e: - LOGGER.warning(f'{prefix}{e}') - - # Fit a solution - y = [x[2] for x in results if x] # memory [2] - p = np.polyfit(batch_sizes[:len(y)], y, deg=1) # first degree polynomial fit - b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size) - if None in results: # some sizes failed - i = results.index(None) # first fail index - if b >= batch_sizes[i]: # y intercept above failure point - b = batch_sizes[max(i - 1, 0)] # select prior safe point - if b < 1 or b > 1024: # b outside of safe range - b = batch_size - LOGGER.warning(f'{prefix}WARNING: ⚠️ CUDA anomaly detected, recommend restart environment and retry command.') - - fraction = np.polyval(p, b) / t # actual fraction predicted - LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅') - return b diff --git a/spaces/abdulmeLINK/programmer-bloom/app.py b/spaces/abdulmeLINK/programmer-bloom/app.py deleted file mode 100644 index 050bd070c51b1297517cf6bfadf6a721b09c9bc1..0000000000000000000000000000000000000000 --- a/spaces/abdulmeLINK/programmer-bloom/app.py +++ /dev/null @@ -1,86 +0,0 @@ -from cProfile import label -from code import interact -from multiprocessing.util import ForkAwareThreadLock -import os -import requests -import gradio as gr - - -# ENV vars -API_URL = os.environ["API_URL"] -HF_TOKEN = os.environ["HF_TOKEN"] -headers = {"Authorization": f"Bearer {HF_TOKEN}"} - -comment_syntaxes = { - "C": "/* {} */", - "C++": "/* {} */", - "Java": "/* {} */", - "Golang": "/* {} */", - "Rust": "/* {} */", - "Javascript": "/* {} */", - "PHP": "/* {} */", - "Kotlin": "/* {} */", - "HTML": "", - "Python": "#{}", - "Bash": "#{}", - "Ruby": "=begin {} =end", -} - -jsn_trail = {"parameters": - { - "top_p": 0.9, - "max_new_tokens": 64, - "return_full_text": True, - "do_sample": True, - }, - "options": - {"use_cache": True, - "wait_for_model": True, - }, } - - -def post(jsn): - response = requests.post(API_URL, headers=headers, json=jsn) - return response.json()[0]["generated_text"] - - -def get_script(lang, instruction): - jsn = {"inputs": comment_syntaxes[lang].format("Programming Language: " + lang) + "\n" + comment_syntaxes[lang].format("Instruction: " + instruction.replace( - '\n', '')) + '\n', **jsn_trail} - return post(jsn) - - -def feedback(opt): - return post({"inputs": opt, **jsn_trail}) - - -demo = gr.Blocks() - -with demo: - gr.Markdown( - "

    Give Instructions to Generate a Program

    ") - gr.Markdown( - "

    This project aims to prepare a prompt for BLOOM to generate scripts

    ") - with gr.Row(): - - dropdown = gr.Dropdown(value="Python", - choices=list(comment_syntaxes.keys()), label="Choose the language") - - # with gr.Column: - instruction = gr.Textbox(label="Write an instruction", - value="Create a python function that generates random password with given length using ascii characters ", lines=6) - - with gr.Row(): - generated_txt = gr.Textbox(lines=5, interactive=False, label="Output") - - btn = gr.Button("Generate") - btn.click(get_script, inputs=[dropdown, - instruction], outputs=generated_txt) - feeedback_btn = gr.Button("Feedback") - feeedback_btn.click( - feedback, inputs=[generated_txt], outputs=generated_txt) - with gr.Row(): - gr.Markdown( - "![visitor badge](https://visitor-badge.glitch.me/badge?page_id=abdulmeLINK.programmer-bloom)") - -demo.launch(enable_queue=True, debug=True) diff --git a/spaces/abdvl/datahub_qa_bot/docs/features.md b/spaces/abdvl/datahub_qa_bot/docs/features.md deleted file mode 100644 index a06789f28f82bde99e6a970c287d12718ab73103..0000000000000000000000000000000000000000 --- a/spaces/abdvl/datahub_qa_bot/docs/features.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: "Features" ---- - -# DataHub Features Overview - -DataHub is a modern data catalog built to enable end-to-end data discovery, data observability, and data governance. This extensible metadata platform is built for developers to tame the complexity of their rapidly evolving data ecosystems and for data practitioners to leverage the total value of data within their organization. - -Here’s an overview of DataHub’s current functionality. Check out our [roadmap](https://feature-requests.datahubproject.io/roadmap) to see what's to come. - ---- - -## Search and Discovery - -### **Search All Corners of Your Data Stack** - -DataHub's unified search experience surfaces results across databases, data lakes, BI platforms, ML feature stores, orchestration tools, and more. - -

    - -

    - -### **Trace End-to-End Lineage** - -Quickly understand the end-to-end journey of data by tracing lineage across platforms, datasets, ETL/ELT pipelines, charts, dashboards, and beyond. - -

    - -

    - -### **Understand the Impact of Breaking Changes on Downstream Dependencies** - -Proactively identify which entities may be impacted by a breaking change using Impact Analysis. - -

    - -

    - -### **View Metadata 360 at a Glance** - -Combine *technical* and *logical* metadata to provide a 360º view of your data entities. - -Generate **Dataset Stats** to understand the shape & distribution of the data - -

    - -

    - -Capture historical **Data Validation Outcomes** from tools like Great Expectations - -

    - -

    - -Leverage DataHub's **Schema Version History** to track changes to the physical structure of data over time - -

    - -

    - ---- - -## Modern Data Governance - -### **Govern in Real Time** - -[The Actions Framework](./actions/README.md) powers the following real-time use cases: - -* **Notifications:** Generate organization-specific notifications when a change is made on DataHub. For example, send an email to the governance team when a "PII" tag is added to any data asset. -* **Workflow Integration:** Integrate DataHub into your organization's internal workflows. For example, create a Jira ticket when specific Tags or Terms are proposed on a Dataset. -* **Synchronization:** Sync changes made in DataHub into a 3rd party system. For example, reflect Tag additions in DataHub into Snowflake. -* **Auditing:** Audit who is making what changes on DataHub through time. - -

    - -

    - -### **Manage Entity Ownership** -Quickly and easily assign entity ownership to users and user groups. - -

    - -

    - -### **Govern with Tags, Glossary Terms, and Domains** -Empower data owners to govern their data entities with: - -1. **Tags:** Informal, loosely controlled labels that serve as a tool for search & discovery. No formal, central management. -2. **Glossary Terms:** A controlled vocabulary with optional hierarchy, commonly used to describe core business concepts and measurements. -3. **Domains:** Curated, top-level folders or categories, widely used in Data Mesh to organize entities by department (i.e., Finance, Marketing) or Data Products. - -

    - -

    - ---- -## DataHub Administration - -### **Create Users, Groups, & Access Policies** - -DataHub admins can create Policies to define who can perform what action against which resource(s). When you create a new Policy, you will be able to define the following: - -* **Policy Type** - Platform (top-level DataHub Platform privileges, i.e., managing users, groups, and policies) or Metadata (ability to manipulate ownership, tags, documentation, and more) -* **Resource Type** - Specify the type of resources, such as Datasets, Dashboards, Pipelines, and beyond -* **Privileges** - Choose the set of permissions, such as Edit Owners, Edit Documentation, Edit Links -* **Users and/or Groups** - Assign relevant Users and Groups; you can also assign the Policy to Resource Owners, regardless of which Group they belong - -

    - -

    - -### **Ingest Metadata from the UI** - -Create, configure, schedule, & execute batch metadata ingestion using the DataHub user interface. This makes getting metadata into DataHub easier by minimizing the overhead required to operate custom integration pipelines. - -

    - -

    \ No newline at end of file diff --git a/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/release-notes/v_0_2_4.md b/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/release-notes/v_0_2_4.md deleted file mode 100644 index 936d8929211682a02c0a396b70c26d2538dabcb9..0000000000000000000000000000000000000000 --- a/spaces/abdvl/datahub_qa_bot/docs/managed-datahub/release-notes/v_0_2_4.md +++ /dev/null @@ -1,21 +0,0 @@ -# v0.2.4 ---- - -Release Availability Date ---- -24-Mar-2023 - -## Release Changelog ---- -- Since `v0.2.3` no changes from OSS DataHub have been pulled in. -- fix(ui) Safeguard ingestion execution request check - Fixes an error on frontend managed ingestion page -- fix(impactAnalysis): fix filtering for lightning mode search -- fix(search): fix tags with colons -- refactor(incidents): Remove dataset health caching to make incident health instantly update -- fix(ui): Address regression in column usage stats + add unit test -- fix(timeBasedLineage): fix ingestProposal flow for no ops -- feat(assertions + incidents): Support Querying Entities by Assertion / Incident Status + Chrome Embed Optimizations -- fix(lineage): change default lineage time window to All Time -- Truncate cache key for search lineage -- feat(config): Add endpoint to exact search query information -- fix(default policies): Add Manage Proposals Default Policies for Root User \ No newline at end of file diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/visualization/optflow.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/visualization/optflow.py deleted file mode 100644 index c3870c700f7c946177ee5d536ce3f6c814a77ce7..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmcv/visualization/optflow.py +++ /dev/null @@ -1,112 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from __future__ import division - -import numpy as np - -from annotator.uniformer.mmcv.image import rgb2bgr -from annotator.uniformer.mmcv.video import flowread -from .image import imshow - - -def flowshow(flow, win_name='', wait_time=0): - """Show optical flow. - - Args: - flow (ndarray or str): The optical flow to be displayed. - win_name (str): The window name. - wait_time (int): Value of waitKey param. - """ - flow = flowread(flow) - flow_img = flow2rgb(flow) - imshow(rgb2bgr(flow_img), win_name, wait_time) - - -def flow2rgb(flow, color_wheel=None, unknown_thr=1e6): - """Convert flow map to RGB image. - - Args: - flow (ndarray): Array of optical flow. - color_wheel (ndarray or None): Color wheel used to map flow field to - RGB colorspace. Default color wheel will be used if not specified. - unknown_thr (str): Values above this threshold will be marked as - unknown and thus ignored. - - Returns: - ndarray: RGB image that can be visualized. - """ - assert flow.ndim == 3 and flow.shape[-1] == 2 - if color_wheel is None: - color_wheel = make_color_wheel() - assert color_wheel.ndim == 2 and color_wheel.shape[1] == 3 - num_bins = color_wheel.shape[0] - - dx = flow[:, :, 0].copy() - dy = flow[:, :, 1].copy() - - ignore_inds = ( - np.isnan(dx) | np.isnan(dy) | (np.abs(dx) > unknown_thr) | - (np.abs(dy) > unknown_thr)) - dx[ignore_inds] = 0 - dy[ignore_inds] = 0 - - rad = np.sqrt(dx**2 + dy**2) - if np.any(rad > np.finfo(float).eps): - max_rad = np.max(rad) - dx /= max_rad - dy /= max_rad - - rad = np.sqrt(dx**2 + dy**2) - angle = np.arctan2(-dy, -dx) / np.pi - - bin_real = (angle + 1) / 2 * (num_bins - 1) - bin_left = np.floor(bin_real).astype(int) - bin_right = (bin_left + 1) % num_bins - w = (bin_real - bin_left.astype(np.float32))[..., None] - flow_img = (1 - - w) * color_wheel[bin_left, :] + w * color_wheel[bin_right, :] - small_ind = rad <= 1 - flow_img[small_ind] = 1 - rad[small_ind, None] * (1 - flow_img[small_ind]) - flow_img[np.logical_not(small_ind)] *= 0.75 - - flow_img[ignore_inds, :] = 0 - - return flow_img - - -def make_color_wheel(bins=None): - """Build a color wheel. - - Args: - bins(list or tuple, optional): Specify the number of bins for each - color range, corresponding to six ranges: red -> yellow, - yellow -> green, green -> cyan, cyan -> blue, blue -> magenta, - magenta -> red. [15, 6, 4, 11, 13, 6] is used for default - (see Middlebury). - - Returns: - ndarray: Color wheel of shape (total_bins, 3). - """ - if bins is None: - bins = [15, 6, 4, 11, 13, 6] - assert len(bins) == 6 - - RY, YG, GC, CB, BM, MR = tuple(bins) - - ry = [1, np.arange(RY) / RY, 0] - yg = [1 - np.arange(YG) / YG, 1, 0] - gc = [0, 1, np.arange(GC) / GC] - cb = [0, 1 - np.arange(CB) / CB, 1] - bm = [np.arange(BM) / BM, 0, 1] - mr = [1, 0, 1 - np.arange(MR) / MR] - - num_bins = RY + YG + GC + CB + BM + MR - - color_wheel = np.zeros((3, num_bins), dtype=np.float32) - - col = 0 - for i, color in enumerate([ry, yg, gc, cb, bm, mr]): - for j in range(3): - color_wheel[j, col:col + bins[i]] = color[j] - col += bins[i] - - return color_wheel.T diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/pisa_retinanet_head.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/pisa_retinanet_head.py deleted file mode 100644 index bd87b9aeb07e05ff94b444ac8999eca3f616711a..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmdet/models/dense_heads/pisa_retinanet_head.py +++ /dev/null @@ -1,154 +0,0 @@ -import torch -from mmcv.runner import force_fp32 - -from mmdet.core import images_to_levels -from ..builder import HEADS -from ..losses import carl_loss, isr_p -from .retina_head import RetinaHead - - -@HEADS.register_module() -class PISARetinaHead(RetinaHead): - """PISA Retinanet Head. - - The head owns the same structure with Retinanet Head, but differs in two - aspects: - 1. Importance-based Sample Reweighting Positive (ISR-P) is applied to - change the positive loss weights. - 2. Classification-aware regression loss is adopted as a third loss. - """ - - @force_fp32(apply_to=('cls_scores', 'bbox_preds')) - def loss(self, - cls_scores, - bbox_preds, - gt_bboxes, - gt_labels, - img_metas, - gt_bboxes_ignore=None): - """Compute losses of the 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) - gt_bboxes (list[Tensor]): Ground truth bboxes of each image - with shape (num_obj, 4). - gt_labels (list[Tensor]): Ground truth labels of each image - with shape (num_obj, 4). - img_metas (list[dict]): Meta information of each image, e.g., - image size, scaling factor, etc. - gt_bboxes_ignore (list[Tensor]): Ignored gt bboxes of each image. - Default: None. - - Returns: - dict: Loss dict, comprise classification loss, regression loss and - carl loss. - """ - featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] - assert len(featmap_sizes) == self.anchor_generator.num_levels - - device = cls_scores[0].device - - anchor_list, valid_flag_list = self.get_anchors( - featmap_sizes, img_metas, device=device) - label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1 - cls_reg_targets = self.get_targets( - anchor_list, - valid_flag_list, - gt_bboxes, - img_metas, - gt_bboxes_ignore_list=gt_bboxes_ignore, - gt_labels_list=gt_labels, - label_channels=label_channels, - return_sampling_results=True) - if cls_reg_targets is None: - return None - (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, - num_total_pos, num_total_neg, sampling_results_list) = cls_reg_targets - num_total_samples = ( - num_total_pos + num_total_neg if self.sampling else num_total_pos) - - # anchor number of multi levels - num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]] - # concat all level anchors and flags to a single tensor - concat_anchor_list = [] - for i in range(len(anchor_list)): - concat_anchor_list.append(torch.cat(anchor_list[i])) - all_anchor_list = images_to_levels(concat_anchor_list, - num_level_anchors) - - num_imgs = len(img_metas) - flatten_cls_scores = [ - cls_score.permute(0, 2, 3, 1).reshape(num_imgs, -1, label_channels) - for cls_score in cls_scores - ] - flatten_cls_scores = torch.cat( - flatten_cls_scores, dim=1).reshape(-1, - flatten_cls_scores[0].size(-1)) - flatten_bbox_preds = [ - bbox_pred.permute(0, 2, 3, 1).reshape(num_imgs, -1, 4) - for bbox_pred in bbox_preds - ] - flatten_bbox_preds = torch.cat( - flatten_bbox_preds, dim=1).view(-1, flatten_bbox_preds[0].size(-1)) - flatten_labels = torch.cat(labels_list, dim=1).reshape(-1) - flatten_label_weights = torch.cat( - label_weights_list, dim=1).reshape(-1) - flatten_anchors = torch.cat(all_anchor_list, dim=1).reshape(-1, 4) - flatten_bbox_targets = torch.cat( - bbox_targets_list, dim=1).reshape(-1, 4) - flatten_bbox_weights = torch.cat( - bbox_weights_list, dim=1).reshape(-1, 4) - - # Apply ISR-P - isr_cfg = self.train_cfg.get('isr', None) - if isr_cfg is not None: - all_targets = (flatten_labels, flatten_label_weights, - flatten_bbox_targets, flatten_bbox_weights) - with torch.no_grad(): - all_targets = isr_p( - flatten_cls_scores, - flatten_bbox_preds, - all_targets, - flatten_anchors, - sampling_results_list, - bbox_coder=self.bbox_coder, - loss_cls=self.loss_cls, - num_class=self.num_classes, - **self.train_cfg.isr) - (flatten_labels, flatten_label_weights, flatten_bbox_targets, - flatten_bbox_weights) = all_targets - - # For convenience we compute loss once instead separating by fpn level, - # so that we don't need to separate the weights by level again. - # The result should be the same - losses_cls = self.loss_cls( - flatten_cls_scores, - flatten_labels, - flatten_label_weights, - avg_factor=num_total_samples) - losses_bbox = self.loss_bbox( - flatten_bbox_preds, - flatten_bbox_targets, - flatten_bbox_weights, - avg_factor=num_total_samples) - loss_dict = dict(loss_cls=losses_cls, loss_bbox=losses_bbox) - - # CARL Loss - carl_cfg = self.train_cfg.get('carl', None) - if carl_cfg is not None: - loss_carl = carl_loss( - flatten_cls_scores, - flatten_labels, - flatten_bbox_preds, - flatten_bbox_targets, - self.loss_bbox, - **self.train_cfg.carl, - avg_factor=num_total_pos, - sigmoid=True, - num_class=self.num_classes) - loss_dict.update(loss_carl) - - return loss_dict diff --git a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmseg/ops/wrappers.py b/spaces/abhishek/sketch-to-image/annotator/uniformer/mmseg/ops/wrappers.py deleted file mode 100644 index 0ed9a0cb8d7c0e0ec2748dd89c652756653cac78..0000000000000000000000000000000000000000 --- a/spaces/abhishek/sketch-to-image/annotator/uniformer/mmseg/ops/wrappers.py +++ /dev/null @@ -1,50 +0,0 @@ -import warnings - -import torch.nn as nn -import torch.nn.functional as F - - -def resize(input, - size=None, - scale_factor=None, - mode='nearest', - align_corners=None, - warning=True): - if warning: - if size is not None and align_corners: - input_h, input_w = tuple(int(x) for x in input.shape[2:]) - output_h, output_w = tuple(int(x) for x in size) - if output_h > input_h or output_w > output_h: - if ((output_h > 1 and output_w > 1 and input_h > 1 - and input_w > 1) and (output_h - 1) % (input_h - 1) - and (output_w - 1) % (input_w - 1)): - warnings.warn( - f'When align_corners={align_corners}, ' - 'the output would more aligned if ' - f'input size {(input_h, input_w)} is `x+1` and ' - f'out size {(output_h, output_w)} is `nx+1`') - return F.interpolate(input, size, scale_factor, mode, align_corners) - - -class Upsample(nn.Module): - - def __init__(self, - size=None, - scale_factor=None, - mode='nearest', - align_corners=None): - super(Upsample, self).__init__() - self.size = size - if isinstance(scale_factor, tuple): - self.scale_factor = tuple(float(factor) for factor in scale_factor) - else: - self.scale_factor = float(scale_factor) if scale_factor else None - self.mode = mode - self.align_corners = align_corners - - def forward(self, x): - if not self.size: - size = [int(t * self.scale_factor) for t in x.shape[-2:]] - else: - size = self.size - return resize(x, size, None, self.mode, self.align_corners) diff --git a/spaces/ahdsoft/Persian-Automatic-Speech-Recognition/Dockerfile b/spaces/ahdsoft/Persian-Automatic-Speech-Recognition/Dockerfile deleted file mode 100644 index 07c167fbcfd18c67bf711c9a4c3f0bf747022ea8..0000000000000000000000000000000000000000 --- a/spaces/ahdsoft/Persian-Automatic-Speech-Recognition/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM python:3.8 -RUN mkdir /app -WORKDIR /app -COPY requirements.txt . - -RUN pip install -r requirements.txt - -COPY . . - -ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=4000", "--server.address=0.0.0.0", "--client.showErrorDetails=false"] diff --git a/spaces/aipicasso/playground/app.py b/spaces/aipicasso/playground/app.py deleted file mode 100644 index 9e03b90feebebcf90ae6ff4a9b7eba5eeaf1ec94..0000000000000000000000000000000000000000 --- a/spaces/aipicasso/playground/app.py +++ /dev/null @@ -1,99 +0,0 @@ -import gradio as gr -import requests -import os -from PIL import Image -from io import BytesIO -import base64 - -def error_str(error, title="Error"): - return f"""#### {title} - {error}""" if error else "" - -def inference(prompt, guidance, steps, image_size="Landscape", seed=0, img=None, strength=0.5, neg_prompt="", disable_auto_prompt_correction=False): - try: - response = requests.post(os.environ["BACKEND"], json={ - "data": [ - prompt, - guidance, - steps, - image_size, - seed, - img, - strength, - neg_prompt, - disable_auto_prompt_correction, - ] - }).json() - - data = response["data"] - - image=Image.open(BytesIO(base64.b64decode(data[0].split(',')[1]))) - - return image,data[1],data[2] - except Exception as e: - print(error_str(e)) - return None, "Error", "Error" - -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""" -
    -
    -

    ChatEmi Beta デモ

    -
    -

    - 個人情報などは入れないでください。 -

    -

    - サンプルプロンプト1:黒い髪の美少女の顔アップ -

    -

    - サンプルプロンプト2:白い髪の男性の上半身 -

    -
    - """ - ) - 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="[your prompt]") - generate = gr.Button(value="Generate") - - image_out = gr.Image(height=1024,width=1024) - 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") - disable_auto_prompt_correction = gr.Checkbox(label="Disable auto prompt corretion.") - with gr.Row(): - image_size=gr.Radio(["Portrait","Landscape","Square"]) - image_size.show_label=False - image_size.value="Square" - - with gr.Row(): - guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=25) - steps = gr.Slider(label="Steps", value=20, minimum=2, maximum=30, step=1) - - seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1) - prompt_display= gr.Textbox(label="Upsampled prompt", interactive=False) - - 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) - - inputs = [prompt, guidance, steps, image_size, seed, image, strength, neg_prompt, disable_auto_prompt_correction] - - outputs = [image_out, error_output, prompt_display] - prompt.submit(inference, inputs=inputs, outputs=outputs) - generate.click(inference, inputs=inputs, outputs=outputs) - -demo.queue(concurrency_count=1) -demo.launch() \ No newline at end of file diff --git a/spaces/akhaliq/CLIP_prefix_captioning/README.md b/spaces/akhaliq/CLIP_prefix_captioning/README.md deleted file mode 100644 index 1faa5db8a51dcd4b63109627c7c8463f2dd9bf07..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/CLIP_prefix_captioning/README.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: CLIP_prefix_captioning -emoji: 💩 -colorFrom: red -colorTo: indigo -sdk: gradio -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` - -`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). -Path is relative to the root of the repository. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/akhaliq/Mask2Former/mask2former_video/__init__.py b/spaces/akhaliq/Mask2Former/mask2former_video/__init__.py deleted file mode 100644 index b6b2f54903ccabe6d4301471711d98c57a961c51..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/Mask2Former/mask2former_video/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from . import modeling - -# config -from .config import add_maskformer2_video_config - -# models -from .video_maskformer_model import VideoMaskFormer - -# video -from .data_video import ( - YTVISDatasetMapper, - YTVISEvaluator, - build_detection_train_loader, - build_detection_test_loader, - get_detection_dataset_dicts, -) diff --git a/spaces/akhaliq/Real-ESRGAN/scripts/generate_multiscale_DF2K.py b/spaces/akhaliq/Real-ESRGAN/scripts/generate_multiscale_DF2K.py deleted file mode 100644 index d4f5d8324b1624e4cb6163754703b8dac2d188fd..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/Real-ESRGAN/scripts/generate_multiscale_DF2K.py +++ /dev/null @@ -1,48 +0,0 @@ -import argparse -import glob -import os -from PIL import Image - - -def main(args): - # For DF2K, we consider the following three scales, - # and the smallest image whose shortest edge is 400 - scale_list = [0.75, 0.5, 1 / 3] - shortest_edge = 400 - - path_list = sorted(glob.glob(os.path.join(args.input, '*'))) - for path in path_list: - print(path) - basename = os.path.splitext(os.path.basename(path))[0] - - img = Image.open(path) - width, height = img.size - for idx, scale in enumerate(scale_list): - print(f'\t{scale:.2f}') - rlt = img.resize((int(width * scale), int(height * scale)), resample=Image.LANCZOS) - rlt.save(os.path.join(args.output, f'{basename}T{idx}.png')) - - # save the smallest image which the shortest edge is 400 - if width < height: - ratio = height / width - width = shortest_edge - height = int(width * ratio) - else: - ratio = width / height - height = shortest_edge - width = int(height * ratio) - rlt = img.resize((int(width), int(height)), resample=Image.LANCZOS) - rlt.save(os.path.join(args.output, f'{basename}T{idx+1}.png')) - - -if __name__ == '__main__': - """Generate multi-scale versions for GT images with LANCZOS resampling. - It is now used for DF2K dataset (DIV2K + Flickr 2K) - """ - parser = argparse.ArgumentParser() - parser.add_argument('--input', type=str, default='datasets/DF2K/DF2K_HR', help='Input folder') - parser.add_argument('--output', type=str, default='datasets/DF2K/DF2K_multiscale', help='Output folder') - args = parser.parse_args() - - os.makedirs(args.output, exist_ok=True) - main(args) diff --git a/spaces/akhaliq/SpecVQGAN_Neural_Audio_Codec/app.py b/spaces/akhaliq/SpecVQGAN_Neural_Audio_Codec/app.py deleted file mode 100644 index 0dc4892e5d666b03e611f0f5ef718cda24b193f6..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/SpecVQGAN_Neural_Audio_Codec/app.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -os.system("git clone https://github.com/v-iashin/SpecVQGAN") -os.system("pip install pytorch-lightning==1.2.10 omegaconf==2.0.6 streamlit==0.80 matplotlib==3.4.1 albumentations==0.5.2 SoundFile torch torchvision librosa gdown") - -from pathlib import Path -import soundfile -import torch -import gradio as gr - -import sys -sys.path.append('./SpecVQGAN') -from feature_extraction.demo_utils import (calculate_codebook_bitrate, - extract_melspectrogram, - get_audio_file_bitrate, - get_duration, - load_neural_audio_codec) -from sample_visualization import tensor_to_plt -from torch.utils.data.dataloader import default_collate - -os.chdir("SpecVQGAN") -device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') - -os.system("gdown https://drive.google.com/uc?id=1KGof44Sx4yIn4Hohpp9-VVTh2zGucKeY") - -model_name = '2021-05-19T22-16-54_vggsound_codebook' -log_dir = './logs' -# loading the models might take a few minutes -config, model, vocoder = load_neural_audio_codec(model_name, log_dir, device) - -def inference(audio): - # Select an Audio - input_wav = audio.name - - # Spectrogram Extraction - model_sr = config.data.params.sample_rate - duration = get_duration(input_wav) - spec = extract_melspectrogram(input_wav, sr=model_sr, duration=duration) - print(f'Audio Duration: {duration} seconds') - print('Original Spectrogram Shape:', spec.shape) - - # Prepare Input - spectrogram = {'input': spec} - batch = default_collate([spectrogram]) - batch['image'] = batch['input'].to(device) - x = model.get_input(batch, 'image') - - with torch.no_grad(): - quant_z, diff, info = model.encode(x) - xrec = model.decode(quant_z) - - print('Compressed representation (it is all you need to recover the audio):') - F, T = quant_z.shape[-2:] - print(info[2].reshape(F, T)) - - - # Calculate Bitrate - bitrate = calculate_codebook_bitrate(duration, quant_z, model.quantize.n_e) - orig_bitrate = get_audio_file_bitrate(input_wav) - - # Save and Display - x = x.squeeze(0) - xrec = xrec.squeeze(0) - # specs are in [-1, 1], making them in [0, 1] - wav_x = vocoder((x + 1) / 2).squeeze().detach().cpu().numpy() - wav_xrec = vocoder((xrec + 1) / 2).squeeze().detach().cpu().numpy() - # Save paths - x_save_path = 'vocoded_orig_spec.wav' - xrec_save_path = f'specvqgan_{bitrate:.2f}kbps.wav' - # Save - soundfile.write(x_save_path, wav_x, model_sr, 'PCM_16') - soundfile.write(xrec_save_path, wav_xrec, model_sr, 'PCM_16') - return 'vocoded_orig_spec.wav', f'specvqgan_{bitrate:.2f}kbps.wav', tensor_to_plt(x, flip_dims=(2,)), tensor_to_plt(xrec, flip_dims=(2,)) - -title = "SpecVQGAN Neural Audio Codec" -description = "Gradio demo for Spectrogram VQGAN as a Neural Audio Codec. To use it, simply add your audio, or click one of the examples to load them. Read more at the links below." -article = "

    Taming Visually Guided Sound Generation | Github Repo

    " - -examples=[['example.wav']] -gr.Interface( - inference, - gr.Audio(type="file", label="Input Audio"), - [gr.Audio(type="file", label="Original audio"),gr.Audio(type="file", label="Reconstructed audio"),gr.Plot(label="Original Spectrogram:"),gr.Plot(label="Reconstructed Spectrogram:")], - title=title, - description=description, - article=article, - enable_queue=True, - examples=examples, - cache_examples=True - ).launch(debug=True) \ No newline at end of file diff --git a/spaces/akhaliq/deeplab2/video/vip_deeplab.py b/spaces/akhaliq/deeplab2/video/vip_deeplab.py deleted file mode 100644 index e931ec6bfebfc6e13d1a7a8b37ee7dbb2a74252f..0000000000000000000000000000000000000000 --- a/spaces/akhaliq/deeplab2/video/vip_deeplab.py +++ /dev/null @@ -1,321 +0,0 @@ -# coding=utf-8 -# Copyright 2021 The Deeplab2 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 file contains the ViP-DeepLab meta architecture.""" -import collections -import functools -from typing import Any, Dict, Text, Tuple - -from absl import logging -import tensorflow as tf - -from deeplab2 import common -from deeplab2 import config_pb2 -from deeplab2.data import dataset -from deeplab2.model import builder -from deeplab2.model import utils -from deeplab2.model.post_processor import post_processor_builder -from deeplab2.model.post_processor import vip_deeplab - -_OFFSET_OUTPUT = 'offset' - - -class ViPDeepLab(tf.keras.Model): - """This class represents the ViP-DeepLab meta architecture. - - This class supports the architecture of ViP-DeepLab. - """ - - def __init__(self, config: config_pb2.ExperimentOptions, - dataset_descriptor: dataset.DatasetDescriptor): - """Initializes a ViP-DeepLab architecture. - - Args: - config: A config_pb2.ExperimentOptions configuration. - dataset_descriptor: A dataset.DatasetDescriptor. - """ - super(ViPDeepLab, self).__init__(name='ViPDeepLab') - - if config.trainer_options.solver_options.use_sync_batchnorm: - logging.info('Synchronized Batchnorm is used.') - bn_layer = functools.partial( - tf.keras.layers.experimental.SyncBatchNormalization, - momentum=config.trainer_options.solver_options.batchnorm_momentum, - epsilon=config.trainer_options.solver_options.batchnorm_epsilon) - else: - logging.info('Standard (unsynchronized) Batchnorm is used.') - bn_layer = functools.partial( - tf.keras.layers.BatchNormalization, - momentum=config.trainer_options.solver_options.batchnorm_momentum, - epsilon=config.trainer_options.solver_options.batchnorm_epsilon) - - self._encoder = builder.create_encoder( - config.model_options.backbone, - bn_layer, - conv_kernel_weight_decay=( - config.trainer_options.solver_options.weight_decay / 2)) - - self._decoder = builder.create_decoder(config.model_options, bn_layer, - dataset_descriptor.ignore_label) - - self._post_processor = post_processor_builder.get_post_processor( - config, dataset_descriptor) - - pool_size = config.train_dataset_options.crop_size - output_stride = float(config.model_options.backbone.output_stride) - pool_size = tuple( - utils.scale_mutable_sequence(pool_size, 1.0 / output_stride)) - logging.info('Setting pooling size to %s', pool_size) - self.set_pool_size(pool_size) - - # Variables for multi-scale inference. - self._add_flipped_images = config.evaluator_options.add_flipped_images - if not config.evaluator_options.eval_scales: - self._eval_scales = [1.0] - else: - self._eval_scales = config.evaluator_options.eval_scales - - self._label_divisor = dataset_descriptor.panoptic_label_divisor - - def _inference(self, input_tensor: tf.Tensor, next_input_tensor: tf.Tensor, - training: bool) -> Dict[Text, Any]: - """Performs an inference pass and returns raw predictions.""" - _, input_h, input_w, _ = input_tensor.get_shape().as_list() - result_dict = collections.defaultdict(list) - # Evaluation mode where one could perform multi-scale inference. - scale_1_pool_size = self.get_pool_size() - logging.info('Eval with scales %s', self._eval_scales) - for eval_scale in self._eval_scales: - # Get the scaled images/pool_size for each scale. - scaled_images, scaled_pool_size = ( - self._scale_images_and_pool_size(input_tensor, - list(scale_1_pool_size), eval_scale)) - next_scaled_images, _ = ( - self._scale_images_and_pool_size(next_input_tensor, - list(scale_1_pool_size), eval_scale)) - # Update the ASPP pool size for different eval scales. - self.set_pool_size(tuple(scaled_pool_size)) - logging.info('Eval scale %s; setting pooling size to %s', eval_scale, - scaled_pool_size) - pred_dict = self._decoder( - self._encoder(scaled_images, training=training), - self._encoder(next_scaled_images, training=training), - training=training) - pred_dict = self._resize_predictions( - pred_dict, target_h=input_h, target_w=input_w) - # Change the semantic logits to probabilities with softmax. Note - # one should remove semantic logits for faster inference. We still - # keep them since they will be used to compute evaluation loss. - pred_dict[common.PRED_SEMANTIC_PROBS_KEY] = tf.nn.softmax( - pred_dict[common.PRED_SEMANTIC_LOGITS_KEY]) - # Store the predictions from each scale. - for output_type, output_value in pred_dict.items(): - result_dict[output_type].append(output_value) - if self._add_flipped_images: - pred_dict_reverse = self._decoder( - self._encoder(tf.reverse(scaled_images, [2]), training=training), - self._encoder( - tf.reverse(next_scaled_images, [2]), training=training), - training=training) - pred_dict_reverse = self._resize_predictions( - pred_dict_reverse, target_h=input_h, target_w=input_w, reverse=True) - # Change the semantic logits to probabilities with softmax. - pred_dict_reverse[common.PRED_SEMANTIC_PROBS_KEY] = tf.nn.softmax( - pred_dict_reverse[common.PRED_SEMANTIC_LOGITS_KEY]) - # Store the predictions from each scale. - for output_type, output_value in pred_dict_reverse.items(): - result_dict[output_type].append(output_value) - # Set back the pool_size for scale 1.0, the original setting. - self.set_pool_size(tuple(scale_1_pool_size)) - # Average results across scales. - for output_type, output_value in result_dict.items(): - result_dict[output_type] = tf.reduce_mean( - tf.stack(output_value, axis=0), axis=0) - return result_dict - - def call(self, - input_tensor: tf.Tensor, - training: bool = False) -> Dict[Text, Any]: - """Performs a forward pass. - - Args: - input_tensor: An input tensor of type tf.Tensor with shape [batch, height, - width, channels]. The input tensor should contain batches of RGB images - pairs. The channel dimension is expected to encode two RGB pixels. - training: A boolean flag indicating whether training behavior should be - used (default: False). - - Returns: - A dictionary containing the results of the specified DeepLab architecture. - The results are bilinearly upsampled to input size before returning. - """ - # Normalize the input in the same way as Inception. We normalize it outside - # the encoder so that we can extend encoders to different backbones without - # copying the normalization to each encoder. We normalize it after data - # preprocessing because it is faster on TPUs than on host CPUs. The - # normalization should not increase TPU memory consumption because it does - # not require gradient. - input_tensor = input_tensor / 127.5 - 1.0 - # Get the static spatial shape of the input tensor. - _, input_h, input_w, _ = input_tensor.get_shape().as_list() - # Splits the input_tensor into the current and the next frames. - input_tensor, next_input_tensor = tf.split(input_tensor, 2, axis=3) - if training: - encoder_features = self._encoder(input_tensor, training=training) - next_encoder_features = self._encoder( - next_input_tensor, training=training) - result_dict = self._decoder( - encoder_features, next_encoder_features, training=training) - result_dict = self._resize_predictions( - result_dict, target_h=input_h, target_w=input_w) - else: - result_dict = self._inference(input_tensor, next_input_tensor, training) - # To get panoptic prediction of the next frame, we reverse the - # input_tensor and next_input_tensor and use them as the input. - # The second input can be anything. In sequence evaluation, we can wait - # for the results of the next pair. Here, we need to compute the panoptic - # predictions of the next frame to do pair evaluation. - # pylint: disable=arguments-out-of-order - next_result_dict = self._inference( - next_input_tensor, input_tensor, training) - # Here, we horizontally concat the raw predictions of the current frame - # and the next frame to perform two-frame panoptic post-processing. - concat_result_dict = collections.defaultdict(list) - concat_result_dict[common.PRED_SEMANTIC_PROBS_KEY] = tf.concat([ - result_dict[common.PRED_SEMANTIC_PROBS_KEY], - next_result_dict[common.PRED_SEMANTIC_PROBS_KEY] - ], - axis=2) - concat_result_dict[common.PRED_CENTER_HEATMAP_KEY] = tf.concat([ - result_dict[common.PRED_CENTER_HEATMAP_KEY], - tf.zeros_like(next_result_dict[common.PRED_CENTER_HEATMAP_KEY]) - ], - axis=2) - next_regression_y, next_regression_x = tf.split( - result_dict[common.PRED_NEXT_OFFSET_MAP_KEY], - num_or_size_splits=2, - axis=3) - # The predicted horizontal offsets of the next frame need to subtract the - # image width to point to the object centers in the current frame because - # the two frames are horizontally concatenated. - next_regression_x -= tf.constant(input_w, dtype=tf.float32) - next_regression = tf.concat([next_regression_y, next_regression_x], - axis=3) - concat_result_dict[common.PRED_OFFSET_MAP_KEY] = tf.concat( - [result_dict[common.PRED_OFFSET_MAP_KEY], next_regression], axis=2) - concat_result_dict.update(self._post_processor(concat_result_dict)) - next_result_dict.update(self._post_processor(next_result_dict)) - result_dict[common.PRED_NEXT_PANOPTIC_KEY] = next_result_dict[ - common.PRED_PANOPTIC_KEY] - for result_key in [ - common.PRED_PANOPTIC_KEY, common.PRED_SEMANTIC_KEY, - common.PRED_INSTANCE_KEY, common.PRED_INSTANCE_CENTER_KEY, - common.PRED_INSTANCE_SCORES_KEY - ]: - result_dict[result_key], next_result_dict[result_key] = tf.split( - concat_result_dict[result_key], num_or_size_splits=2, axis=2) - result_dict[common.PRED_CONCAT_NEXT_PANOPTIC_KEY] = next_result_dict[ - common.PRED_PANOPTIC_KEY] - result_dict[common.PRED_NEXT_PANOPTIC_KEY] = tf.numpy_function( - func=vip_deeplab.stitch_video_panoptic_prediction, - inp=[ - result_dict[common.PRED_CONCAT_NEXT_PANOPTIC_KEY], - result_dict[common.PRED_NEXT_PANOPTIC_KEY], self._label_divisor - ], - Tout=tf.int32) - result_dict[common.PRED_NEXT_PANOPTIC_KEY].set_shape( - result_dict[common.PRED_CONCAT_NEXT_PANOPTIC_KEY].get_shape()) - if common.PRED_CENTER_HEATMAP_KEY in result_dict: - result_dict[common.PRED_CENTER_HEATMAP_KEY] = tf.squeeze( - result_dict[common.PRED_CENTER_HEATMAP_KEY], axis=3) - return result_dict - - def reset_pooling_layer(self): - """Resets the ASPP pooling layer to global average pooling.""" - self._decoder.reset_pooling_layer() - - def set_pool_size(self, pool_size: Tuple[int, int]): - """Sets the pooling size of the ASPP pooling layer. - - Args: - pool_size: A tuple specifying the pooling size of the ASPP pooling layer. - """ - self._decoder.set_pool_size(pool_size) - - def get_pool_size(self): - return self._decoder.get_pool_size() - - @property - def checkpoint_items(self) -> Dict[Text, Any]: - items = dict(encoder=self._encoder) - items.update(self._decoder.checkpoint_items) - return items - - def _resize_predictions(self, result_dict, target_h, target_w, reverse=False): - """Resizes predictions to the target height and width. - - This function resizes the items in the result_dict to the target height and - width. The items are optionally reversed w.r.t width if `reverse` is True. - - Args: - result_dict: A dictionary storing prediction results to be resized. - target_h: An integer, the target height. - target_w: An integer, the target width. - reverse: A boolean, reversing the prediction result w.r.t. width. - - Returns: - Resized (or optionally reversed) result_dict. - """ - for key, value in result_dict.items(): - if reverse: - value = tf.reverse(value, [2]) - # Special care to offsets: need to flip x-offsets. - if _OFFSET_OUTPUT in key: - offset_y, offset_x = tf.split( - value=value, num_or_size_splits=2, axis=3) - offset_x *= -1 - value = tf.concat([offset_y, offset_x], 3) - if _OFFSET_OUTPUT in key: - result_dict[key] = utils.resize_and_rescale_offsets( - value, [target_h, target_w]) - else: - result_dict[key] = utils.resize_bilinear(value, [target_h, target_w]) - return result_dict - - def _scale_images_and_pool_size(self, images, pool_size, scale): - """Scales images and pool_size w.r.t. - - scale. - - Args: - images: An input tensor with shape [batch, height, width, 3]. - pool_size: A list with two elements, specifying the pooling size of ASPP - pooling layer. - scale: A float, used to scale the input images and pool_size. - - Returns: - Scaled images, and pool_size. - """ - if scale == 1.0: - scaled_images = images - scaled_pool_size = pool_size - else: - image_size = images.get_shape().as_list()[1:3] - scaled_image_size = utils.scale_mutable_sequence(image_size, scale) - scaled_images = utils.resize_bilinear(images, scaled_image_size) - scaled_pool_size = [None, None] - if pool_size != [None, None]: - scaled_pool_size = utils.scale_mutable_sequence(pool_size, scale) - return scaled_images, scaled_pool_size diff --git a/spaces/ali-ghamdan/deoldify/fastai/text/models/bwd_forget_mult_cuda.cpp b/spaces/ali-ghamdan/deoldify/fastai/text/models/bwd_forget_mult_cuda.cpp deleted file mode 100644 index c9b5a14281e17dee53d6a15d3a4e99fa6171d1b5..0000000000000000000000000000000000000000 --- a/spaces/ali-ghamdan/deoldify/fastai/text/models/bwd_forget_mult_cuda.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include - -#include - -// CUDA forward declarations -at::Tensor bwd_forget_mult_cuda_forward(at::Tensor x, at::Tensor f, at::Tensor output, bool batch_first); - -// C++ interface - -#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") -#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") -#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) - -at::Tensor bwd_forget_mult_forward(at::Tensor x, at::Tensor f, at::Tensor output, bool batch_first) { - CHECK_INPUT(x); CHECK_INPUT(f); CHECK_INPUT(output); - return bwd_forget_mult_cuda_forward(x, f, output, batch_first); -} - -std::vector bwd_forget_mult_cuda_backward(at::Tensor x, at::Tensor f, at::Tensor output, - at::Tensor grad_output, bool batch_first); - -std::vector bwd_forget_mult_backward(at::Tensor x, at::Tensor f, at::Tensor output, - at::Tensor grad_output, bool batch_first) { - CHECK_INPUT(x); CHECK_INPUT(f); CHECK_INPUT(output); - return bwd_forget_mult_cuda_backward(x, f, output, grad_output, batch_first); -} - -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { - m.def("forward", &bwd_forget_mult_forward, "BwdForgetMult forward (CUDA)"); - m.def("backward", &bwd_forget_mult_backward, "BwdForgetMult backward (CUDA)"); -} diff --git a/spaces/alphunt/diffdock-alphunt-demo/baselines/baseline_evaluation.py b/spaces/alphunt/diffdock-alphunt-demo/baselines/baseline_evaluation.py deleted file mode 100644 index 6ce83de2d0bb471c0b78e5935679b141c3518a3a..0000000000000000000000000000000000000000 --- a/spaces/alphunt/diffdock-alphunt-demo/baselines/baseline_evaluation.py +++ /dev/null @@ -1,219 +0,0 @@ -# small script to extract the ligand and save it in a separate file because GNINA will use the ligand position as initial pose -import os - -import plotly.express as px -import time -from argparse import FileType, ArgumentParser - -import numpy as np -import pandas as pd -import wandb -from biopandas.pdb import PandasPdb -from rdkit import Chem - -from tqdm import tqdm - -from datasets.pdbbind import read_mol -from datasets.process_mols import read_molecule -from utils.utils import read_strings_from_txt, get_symmetry_rmsd - -parser = ArgumentParser() -parser.add_argument('--config', type=FileType(mode='r'), default=None) -parser.add_argument('--run_name', type=str, default='gnina_results', help='') -parser.add_argument('--data_dir', type=str, default='data/PDBBind_processed', help='') -parser.add_argument('--results_path', type=str, default='results/user_inference', help='Path to folder with trained model and hyperparameters') -parser.add_argument('--file_suffix', type=str, default='_baseline_ligand.pdb', help='Path to folder with trained model and hyperparameters') -parser.add_argument('--project', type=str, default='ligbind_inf', help='') -parser.add_argument('--wandb', action='store_true', default=False, help='') -parser.add_argument('--file_to_exclude', type=str, default=None, help='') -parser.add_argument('--all_dirs_in_results', action='store_true', default=True, help='Evaluate all directories in the results path instead of using directly looking for the names') -parser.add_argument('--num_predictions', type=int, default=10, help='') -parser.add_argument('--no_id_in_filename', action='store_true', default=False, help='') -args = parser.parse_args() - -print('Reading paths and names.') -names = read_strings_from_txt(f'data/splits/timesplit_test') -names_no_rec_overlap = read_strings_from_txt(f'data/splits/timesplit_test_no_rec_overlap') -results_path_containments = os.listdir(args.results_path) - -if args.wandb: - wandb.init( - entity='coarse-graining-mit', - settings=wandb.Settings(start_method="fork"), - project=args.project, - name=args.run_name, - config=args - ) - -all_times = [] -successful_names_list = [] -rmsds_list = [] -centroid_distances_list = [] -min_cross_distances_list = [] -min_self_distances_list = [] -without_rec_overlap_list = [] -start_time = time.time() -for i, name in enumerate(tqdm(names)): - mol = read_mol(args.data_dir, name, remove_hs=True) - mol = Chem.RemoveAllHs(mol) - orig_ligand_pos = np.array(mol.GetConformer().GetPositions()) - - if args.all_dirs_in_results: - directory_with_name = [directory for directory in results_path_containments if name in directory][0] - ligand_pos = [] - for i in range(args.num_predictions): - file_paths = os.listdir(os.path.join(args.results_path, directory_with_name)) - file_path = [path for path in file_paths if f'rank{i+1}' in path][0] - if args.file_to_exclude is not None and args.file_to_exclude in file_path: continue - mol_pred = read_molecule(os.path.join(args.results_path, directory_with_name, file_path),remove_hs=True, sanitize=True) - mol_pred = Chem.RemoveAllHs(mol_pred) - ligand_pos.append(mol_pred.GetConformer().GetPositions()) - ligand_pos = np.asarray(ligand_pos) - else: - if not os.path.exists(os.path.join(args.results_path, name, f'{"" if args.no_id_in_filename else name}{args.file_suffix}')): raise Exception('path did not exists:', os.path.join(args.results_path, name, f'{"" if args.no_id_in_filename else name}{args.file_suffix}')) - mol_pred = read_molecule(os.path.join(args.results_path, name, f'{"" if args.no_id_in_filename else name}{args.file_suffix}'), remove_hs=True, sanitize=True) - if mol_pred == None: - print("Skipping ", name, ' because RDKIT could not read it.') - continue - mol_pred = Chem.RemoveAllHs(mol_pred) - ligand_pos = np.asarray([np.array(mol_pred.GetConformer(i).GetPositions()) for i in range(args.num_predictions)]) - try: - rmsd = get_symmetry_rmsd(mol, orig_ligand_pos, [l for l in ligand_pos], mol_pred) - except Exception as e: - print("Using non corrected RMSD because of the error:", e) - rmsd = np.sqrt(((ligand_pos - orig_ligand_pos) ** 2).sum(axis=2).mean(axis=1)) - - rmsds_list.append(rmsd) - centroid_distances_list.append(np.linalg.norm(ligand_pos.mean(axis=1) - orig_ligand_pos[None,:].mean(axis=1), axis=1)) - - rec_path = os.path.join(args.data_dir, name, f'{name}_protein_processed.pdb') - if not os.path.exists(rec_path): - rec_path = os.path.join(args.data_dir, name,f'{name}_protein_obabel_reduce.pdb') - rec = PandasPdb().read_pdb(rec_path) - rec_df = rec.df['ATOM'] - receptor_pos = rec_df[['x_coord', 'y_coord', 'z_coord']].to_numpy().squeeze().astype(np.float32) - receptor_pos = np.tile(receptor_pos, (args.num_predictions, 1, 1)) - - cross_distances = np.linalg.norm(receptor_pos[:, :, None, :] - ligand_pos[:, None, :, :], axis=-1) - self_distances = np.linalg.norm(ligand_pos[:, :, None, :] - ligand_pos[:, None, :, :], axis=-1) - self_distances = np.where(np.eye(self_distances.shape[2]), np.inf, self_distances) - min_cross_distances_list.append(np.min(cross_distances, axis=(1,2))) - min_self_distances_list.append(np.min(self_distances, axis=(1, 2))) - successful_names_list.append(name) - without_rec_overlap_list.append(1 if name in names_no_rec_overlap else 0) -performance_metrics = {} -for overlap in ['', 'no_overlap_']: - if 'no_overlap_' == overlap: - without_rec_overlap = np.array(without_rec_overlap_list, dtype=bool) - rmsds = np.array(rmsds_list)[without_rec_overlap] - centroid_distances = np.array(centroid_distances_list)[without_rec_overlap] - min_cross_distances = np.array(min_cross_distances_list)[without_rec_overlap] - min_self_distances = np.array(min_self_distances_list)[without_rec_overlap] - successful_names = np.array(successful_names_list)[without_rec_overlap] - else: - rmsds = np.array(rmsds_list) - centroid_distances = np.array(centroid_distances_list) - min_cross_distances = np.array(min_cross_distances_list) - min_self_distances = np.array(min_self_distances_list) - successful_names = np.array(successful_names_list) - - np.save(os.path.join(args.results_path, f'{overlap}rmsds.npy'), rmsds) - np.save(os.path.join(args.results_path, f'{overlap}names.npy'), successful_names) - np.save(os.path.join(args.results_path, f'{overlap}min_cross_distances.npy'), np.array(min_cross_distances)) - np.save(os.path.join(args.results_path, f'{overlap}min_self_distances.npy'), np.array(min_self_distances)) - - performance_metrics.update({ - f'{overlap}steric_clash_fraction': (100 * (min_cross_distances < 0.4).sum() / len(min_cross_distances) / args.num_predictions).__round__(2), - f'{overlap}self_intersect_fraction': (100 * (min_self_distances < 0.4).sum() / len(min_self_distances) / args.num_predictions).__round__(2), - f'{overlap}mean_rmsd': rmsds[:,0].mean(), - f'{overlap}rmsds_below_2': (100 * (rmsds[:,0] < 2).sum() / len(rmsds[:,0])), - f'{overlap}rmsds_below_5': (100 * (rmsds[:,0] < 5).sum() / len(rmsds[:,0])), - f'{overlap}rmsds_percentile_25': np.percentile(rmsds[:,0], 25).round(2), - f'{overlap}rmsds_percentile_50': np.percentile(rmsds[:,0], 50).round(2), - f'{overlap}rmsds_percentile_75': np.percentile(rmsds[:,0], 75).round(2), - - f'{overlap}mean_centroid': centroid_distances[:,0].mean().__round__(2), - f'{overlap}centroid_below_2': (100 * (centroid_distances[:,0] < 2).sum() / len(centroid_distances[:,0])).__round__(2), - f'{overlap}centroid_below_5': (100 * (centroid_distances[:,0] < 5).sum() / len(centroid_distances[:,0])).__round__(2), - f'{overlap}centroid_percentile_25': np.percentile(centroid_distances[:,0], 25).round(2), - f'{overlap}centroid_percentile_50': np.percentile(centroid_distances[:,0], 50).round(2), - f'{overlap}centroid_percentile_75': np.percentile(centroid_distances[:,0], 75).round(2), - }) - - top5_rmsds = np.min(rmsds[:, :5], axis=1) - top5_centroid_distances = centroid_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :5], axis=1)][:,0] - top5_min_cross_distances = min_cross_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :5], axis=1)][:,0] - top5_min_self_distances = min_self_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :5], axis=1)][:,0] - performance_metrics.update({ - f'{overlap}top5_steric_clash_fraction': (100 * (top5_min_cross_distances < 0.4).sum() / len(top5_min_cross_distances)).__round__(2), - f'{overlap}top5_self_intersect_fraction': (100 * (top5_min_self_distances < 0.4).sum() / len(top5_min_self_distances)).__round__(2), - f'{overlap}top5_rmsds_below_2': (100 * (top5_rmsds < 2).sum() / len(top5_rmsds)).__round__(2), - f'{overlap}top5_rmsds_below_5': (100 * (top5_rmsds < 5).sum() / len(top5_rmsds)).__round__(2), - f'{overlap}top5_rmsds_percentile_25': np.percentile(top5_rmsds, 25).round(2), - f'{overlap}top5_rmsds_percentile_50': np.percentile(top5_rmsds, 50).round(2), - f'{overlap}top5_rmsds_percentile_75': np.percentile(top5_rmsds, 75).round(2), - - f'{overlap}top5_centroid_below_2': (100 * (top5_centroid_distances < 2).sum() / len(top5_centroid_distances)).__round__(2), - f'{overlap}top5_centroid_below_5': (100 * (top5_centroid_distances < 5).sum() / len(top5_centroid_distances)).__round__(2), - f'{overlap}top5_centroid_percentile_25': np.percentile(top5_centroid_distances, 25).round(2), - f'{overlap}top5_centroid_percentile_50': np.percentile(top5_centroid_distances, 50).round(2), - f'{overlap}top5_centroid_percentile_75': np.percentile(top5_centroid_distances, 75).round(2), - }) - - - top10_rmsds = np.min(rmsds[:, :10], axis=1) - top10_centroid_distances = centroid_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :10], axis=1)][:,0] - top10_min_cross_distances = min_cross_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :10], axis=1)][:,0] - top10_min_self_distances = min_self_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :10], axis=1)][:,0] - performance_metrics.update({ - f'{overlap}top10_self_intersect_fraction': (100 * (top10_min_self_distances < 0.4).sum() / len(top10_min_self_distances)).__round__(2), - f'{overlap}top10_steric_clash_fraction': ( 100 * (top10_min_cross_distances < 0.4).sum() / len(top10_min_cross_distances)).__round__(2), - f'{overlap}top10_rmsds_below_2': (100 * (top10_rmsds < 2).sum() / len(top10_rmsds)).__round__(2), - f'{overlap}top10_rmsds_below_5': (100 * (top10_rmsds < 5).sum() / len(top10_rmsds)).__round__(2), - f'{overlap}top10_rmsds_percentile_25': np.percentile(top10_rmsds, 25).round(2), - f'{overlap}top10_rmsds_percentile_50': np.percentile(top10_rmsds, 50).round(2), - f'{overlap}top10_rmsds_percentile_75': np.percentile(top10_rmsds, 75).round(2), - - f'{overlap}top10_centroid_below_2': (100 * (top10_centroid_distances < 2).sum() / len(top10_centroid_distances)).__round__(2), - f'{overlap}top10_centroid_below_5': (100 * (top10_centroid_distances < 5).sum() / len(top10_centroid_distances)).__round__(2), - f'{overlap}top10_centroid_percentile_25': np.percentile(top10_centroid_distances, 25).round(2), - f'{overlap}top10_centroid_percentile_50': np.percentile(top10_centroid_distances, 50).round(2), - f'{overlap}top10_centroid_percentile_75': np.percentile(top10_centroid_distances, 75).round(2), - }) -for k in performance_metrics: - print(k, performance_metrics[k]) - -if args.wandb: - wandb.log(performance_metrics) - histogram_metrics_list = [('rmsd', rmsds[:,0]), - ('centroid_distance', centroid_distances[:,0]), - ('mean_rmsd', rmsds[:,0]), - ('mean_centroid_distance', centroid_distances[:,0])] - histogram_metrics_list.append(('top5_rmsds', top5_rmsds)) - histogram_metrics_list.append(('top5_centroid_distances', top5_centroid_distances)) - histogram_metrics_list.append(('top10_rmsds', top10_rmsds)) - histogram_metrics_list.append(('top10_centroid_distances', top10_centroid_distances)) - - os.makedirs(f'.plotly_cache/baseline_cache', exist_ok=True) - images = [] - for metric_name, metric in histogram_metrics_list: - d = {args.results_path: metric} - df = pd.DataFrame(data=d) - fig = px.ecdf(df, width=900, height=600, range_x=[0, 40]) - fig.add_vline(x=2, annotation_text='2 A;', annotation_font_size=20, annotation_position="top right", - line_dash='dash', line_color='firebrick', annotation_font_color='firebrick') - fig.add_vline(x=5, annotation_text='5 A;', annotation_font_size=20, annotation_position="top right", - line_dash='dash', line_color='green', annotation_font_color='green') - fig.update_xaxes(title=f'{metric_name} in Angstrom', title_font={"size": 20}, tickfont={"size": 20}) - fig.update_yaxes(title=f'Fraction of predictions with lower error', title_font={"size": 20}, - tickfont={"size": 20}) - fig.update_layout(autosize=False, margin={'l': 0, 'r': 0, 't': 0, 'b': 0}, plot_bgcolor='white', - paper_bgcolor='white', legend_title_text='Method', legend_title_font_size=17, - legend=dict(yanchor="bottom", y=0.1, xanchor="right", x=0.99, font=dict(size=17), ), ) - fig.update_xaxes(showgrid=True, gridcolor='lightgrey') - fig.update_yaxes(showgrid=True, gridcolor='lightgrey') - - fig.write_image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png')) - wandb.log({metric_name: wandb.Image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png'), caption=f"{metric_name}")}) - images.append(wandb.Image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png'), caption=f"{metric_name}")) - wandb.log({'images': images}) \ No newline at end of file diff --git a/spaces/amish1729/LFUNet/README.md b/spaces/amish1729/LFUNet/README.md deleted file mode 100644 index 9cb416a993dd4c39cd754e56464dd1f4da73769f..0000000000000000000000000000000000000000 --- a/spaces/amish1729/LFUNet/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: LFUNet -emoji: 👀 -colorFrom: blue -colorTo: purple -sdk: gradio -sdk_version: 3.35.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/anthonygaltier/text_2_price__real_estate/README.md b/spaces/anthonygaltier/text_2_price__real_estate/README.md deleted file mode 100644 index 5f296d6e95894ce0794483ed15b2bd4a8e4a1e26..0000000000000000000000000000000000000000 --- a/spaces/anthonygaltier/text_2_price__real_estate/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Text 2 Price Real Estate -emoji: 📚 -colorFrom: purple -colorTo: red -sdk: streamlit -sdk_version: 1.10.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/aodianyun/panoptic-segment-anything/README.md b/spaces/aodianyun/panoptic-segment-anything/README.md deleted file mode 100644 index a332324e6ffd5313db46a6d14cc0223dfac47b8b..0000000000000000000000000000000000000000 --- a/spaces/aodianyun/panoptic-segment-anything/README.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Panoptic Segment Anything -emoji: 🖼️🪄 -colorFrom: yellow -colorTo: red -sdk: gradio -sdk_version: 3.24.1 -app_file: app.py -pinned: false -license: apache-2.0 -models: -- ShilongLiu/GroundingDINO -- CIDAS/clipseg-rd64-refined -tags: -- segmentation -- zero-shot -- sam -duplicated_from: segments/panoptic-segment-anything ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/aodianyun/stable-diffusion-webui/modules/ui.py b/spaces/aodianyun/stable-diffusion-webui/modules/ui.py deleted file mode 100644 index badf4975128985ad55bb69d6ee028adc0a61f97c..0000000000000000000000000000000000000000 --- a/spaces/aodianyun/stable-diffusion-webui/modules/ui.py +++ /dev/null @@ -1,1798 +0,0 @@ -import html -import json -import math -import mimetypes -import os -import platform -import random -import sys -import tempfile -import time -import traceback -from functools import partial, reduce -import warnings - -import gradio as gr -import gradio.routes -import gradio.utils -import numpy as np -from PIL import Image, PngImagePlugin -from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call, wrap_gradio_call - -from modules import sd_hijack, sd_models, localization, script_callbacks, ui_extensions, deepbooru, sd_vae, extra_networks, postprocessing, ui_components, ui_common, ui_postprocessing -from modules.ui_components import FormRow, FormGroup, ToolButton, FormHTML -from modules.paths import script_path, data_path - -from modules.shared import opts, cmd_opts, restricted_opts - -import modules.codeformer_model -import modules.generation_parameters_copypaste as parameters_copypaste -import modules.gfpgan_model -import modules.hypernetworks.ui -import modules.scripts -import modules.shared as shared -import modules.styles -import modules.textual_inversion.ui -from modules import prompt_parser -from modules.images import save_image -from modules.sd_hijack import model_hijack -from modules.sd_samplers import samplers, samplers_for_img2img -from modules.textual_inversion import textual_inversion -import modules.hypernetworks.ui -from modules.generation_parameters_copypaste import image_from_url_text -import modules.extras - -warnings.filterwarnings("default" if opts.show_warnings else "ignore", category=UserWarning) - -# this is a fix for Windows users. Without it, javascript files will be served with text/html content-type and the browser will not show any UI -mimetypes.init() -mimetypes.add_type('application/javascript', '.js') - -if not cmd_opts.share and not cmd_opts.listen: - # fix gradio phoning home - gradio.utils.version_check = lambda: None - gradio.utils.get_local_ip_address = lambda: '127.0.0.1' - -if cmd_opts.ngrok is not None: - import modules.ngrok as ngrok - print('ngrok authtoken detected, trying to connect...') - ngrok.connect( - cmd_opts.ngrok, - cmd_opts.port if cmd_opts.port is not None else 7860, - cmd_opts.ngrok_region - ) - - -def gr_show(visible=True): - return {"visible": visible, "__type__": "update"} - - -sample_img2img = "assets/stable-samples/img2img/sketch-mountains-input.jpg" -sample_img2img = sample_img2img if os.path.exists(sample_img2img) else None - -css_hide_progressbar = """ -.wrap .m-12 svg { display:none!important; } -.wrap .m-12::before { content:"Loading..." } -.wrap .z-20 svg { display:none!important; } -.wrap .z-20::before { content:"Loading..." } -.wrap.cover-bg .z-20::before { content:"" } -.progress-bar { display:none!important; } -.meta-text { display:none!important; } -.meta-text-center { display:none!important; } -""" - -# Using constants for these since the variation selector isn't visible. -# Important that they exactly match script.js for tooltip to work. -random_symbol = '\U0001f3b2\ufe0f' # 🎲️ -reuse_symbol = '\u267b\ufe0f' # ♻️ -paste_symbol = '\u2199\ufe0f' # ↙ -refresh_symbol = '\U0001f504' # 🔄 -save_style_symbol = '\U0001f4be' # 💾 -apply_style_symbol = '\U0001f4cb' # 📋 -clear_prompt_symbol = '\U0001F5D1' # 🗑️ -extra_networks_symbol = '\U0001F3B4' # 🎴 -switch_values_symbol = '\U000021C5' # ⇅ - - -def plaintext_to_html(text): - return ui_common.plaintext_to_html(text) - - -def send_gradio_gallery_to_image(x): - if len(x) == 0: - return None - return image_from_url_text(x[0]) - -def visit(x, func, path=""): - if hasattr(x, 'children'): - for c in x.children: - visit(c, func, path) - elif x.label is not None: - func(path + "/" + str(x.label), x) - - -def add_style(name: str, prompt: str, negative_prompt: str): - if name is None: - return [gr_show() for x in range(4)] - - style = modules.styles.PromptStyle(name, prompt, negative_prompt) - shared.prompt_styles.styles[style.name] = style - # Save all loaded prompt styles: this allows us to update the storage format in the future more easily, because we - # reserialize all styles every time we save them - shared.prompt_styles.save_styles(shared.styles_filename) - - return [gr.Dropdown.update(visible=True, choices=list(shared.prompt_styles.styles)) for _ in range(2)] - - -def calc_resolution_hires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y): - from modules import processing, devices - - if not enable: - return "" - - p = processing.StableDiffusionProcessingTxt2Img(width=width, height=height, enable_hr=True, hr_scale=hr_scale, hr_resize_x=hr_resize_x, hr_resize_y=hr_resize_y) - - with devices.autocast(): - p.init([""], [0], [0]) - - return f"resize: from {p.width}x{p.height} to {p.hr_resize_x or p.hr_upscale_to_x}x{p.hr_resize_y or p.hr_upscale_to_y}" - - -def apply_styles(prompt, prompt_neg, styles): - prompt = shared.prompt_styles.apply_styles_to_prompt(prompt, styles) - prompt_neg = shared.prompt_styles.apply_negative_styles_to_prompt(prompt_neg, styles) - - return [gr.Textbox.update(value=prompt), gr.Textbox.update(value=prompt_neg), gr.Dropdown.update(value=[])] - - -def process_interrogate(interrogation_function, mode, ii_input_dir, ii_output_dir, *ii_singles): - if mode in {0, 1, 3, 4}: - return [interrogation_function(ii_singles[mode]), None] - elif mode == 2: - return [interrogation_function(ii_singles[mode]["image"]), None] - elif mode == 5: - assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled" - images = shared.listfiles(ii_input_dir) - print(f"Will process {len(images)} images.") - if ii_output_dir != "": - os.makedirs(ii_output_dir, exist_ok=True) - else: - ii_output_dir = ii_input_dir - - for image in images: - img = Image.open(image) - filename = os.path.basename(image) - left, _ = os.path.splitext(filename) - print(interrogation_function(img), file=open(os.path.join(ii_output_dir, left + ".txt"), 'a')) - - return [gr.update(), None] - - -def interrogate(image): - prompt = shared.interrogator.interrogate(image.convert("RGB")) - return gr.update() if prompt is None else prompt - - -def interrogate_deepbooru(image): - prompt = deepbooru.model.tag(image) - return gr.update() if prompt is None else prompt - - -def create_seed_inputs(target_interface): - with FormRow(elem_id=target_interface + '_seed_row'): - seed = (gr.Textbox if cmd_opts.use_textbox_seed else gr.Number)(label='Seed', value=-1, elem_id=target_interface + '_seed') - seed.style(container=False) - random_seed = gr.Button(random_symbol, elem_id=target_interface + '_random_seed') - reuse_seed = gr.Button(reuse_symbol, elem_id=target_interface + '_reuse_seed') - - with gr.Group(elem_id=target_interface + '_subseed_show_box'): - seed_checkbox = gr.Checkbox(label='Extra', elem_id=target_interface + '_subseed_show', value=False) - - # Components to show/hide based on the 'Extra' checkbox - seed_extras = [] - - with FormRow(visible=False, elem_id=target_interface + '_subseed_row') as seed_extra_row_1: - seed_extras.append(seed_extra_row_1) - subseed = gr.Number(label='Variation seed', value=-1, elem_id=target_interface + '_subseed') - subseed.style(container=False) - random_subseed = gr.Button(random_symbol, elem_id=target_interface + '_random_subseed') - reuse_subseed = gr.Button(reuse_symbol, elem_id=target_interface + '_reuse_subseed') - subseed_strength = gr.Slider(label='Variation strength', value=0.0, minimum=0, maximum=1, step=0.01, elem_id=target_interface + '_subseed_strength') - - with FormRow(visible=False) as seed_extra_row_2: - seed_extras.append(seed_extra_row_2) - seed_resize_from_w = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize seed from width", value=0, elem_id=target_interface + '_seed_resize_from_w') - seed_resize_from_h = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize seed from height", value=0, elem_id=target_interface + '_seed_resize_from_h') - - random_seed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[seed]) - random_subseed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[subseed]) - - def change_visibility(show): - return {comp: gr_show(show) for comp in seed_extras} - - seed_checkbox.change(change_visibility, show_progress=False, inputs=[seed_checkbox], outputs=seed_extras) - - return seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox - - - -def connect_clear_prompt(button): - """Given clear button, prompt, and token_counter objects, setup clear prompt button click event""" - button.click( - _js="clear_prompt", - fn=None, - inputs=[], - outputs=[], - ) - - -def connect_reuse_seed(seed: gr.Number, reuse_seed: gr.Button, generation_info: gr.Textbox, dummy_component, is_subseed): - """ Connects a 'reuse (sub)seed' button's click event so that it copies last used - (sub)seed value from generation info the to the seed field. If copying subseed and subseed strength - was 0, i.e. no variation seed was used, it copies the normal seed value instead.""" - def copy_seed(gen_info_string: str, index): - res = -1 - - try: - gen_info = json.loads(gen_info_string) - index -= gen_info.get('index_of_first_image', 0) - - if is_subseed and gen_info.get('subseed_strength', 0) > 0: - all_subseeds = gen_info.get('all_subseeds', [-1]) - res = all_subseeds[index if 0 <= index < len(all_subseeds) else 0] - else: - all_seeds = gen_info.get('all_seeds', [-1]) - res = all_seeds[index if 0 <= index < len(all_seeds) else 0] - - except json.decoder.JSONDecodeError as e: - if gen_info_string != '': - print("Error parsing JSON generation info:", file=sys.stderr) - print(gen_info_string, file=sys.stderr) - - return [res, gr_show(False)] - - reuse_seed.click( - fn=copy_seed, - _js="(x, y) => [x, selected_gallery_index()]", - show_progress=False, - inputs=[generation_info, dummy_component], - outputs=[seed, dummy_component] - ) - - -def update_token_counter(text, steps): - try: - text, _ = extra_networks.parse_prompt(text) - - _, prompt_flat_list, _ = prompt_parser.get_multicond_prompt_list([text]) - prompt_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(prompt_flat_list, steps) - - except Exception: - # a parsing error can happen here during typing, and we don't want to bother the user with - # messages related to it in console - prompt_schedules = [[[steps, text]]] - - flat_prompts = reduce(lambda list1, list2: list1+list2, prompt_schedules) - prompts = [prompt_text for step, prompt_text in flat_prompts] - token_count, max_length = max([model_hijack.get_prompt_lengths(prompt) for prompt in prompts], key=lambda args: args[0]) - return f"{token_count}/{max_length}" - - -def create_toprow(is_img2img): - id_part = "img2img" if is_img2img else "txt2img" - - with gr.Row(elem_id=f"{id_part}_toprow", variant="compact"): - with gr.Column(elem_id=f"{id_part}_prompt_container", scale=6): - with gr.Row(): - with gr.Column(scale=80): - with gr.Row(): - prompt = gr.Textbox(label="Prompt", elem_id=f"{id_part}_prompt", show_label=False, lines=3, placeholder="Prompt (press Ctrl+Enter or Alt+Enter to generate)") - - with gr.Row(): - with gr.Column(scale=80): - with gr.Row(): - negative_prompt = gr.Textbox(label="Negative prompt", elem_id=f"{id_part}_neg_prompt", show_label=False, lines=2, placeholder="Negative prompt (press Ctrl+Enter or Alt+Enter to generate)") - - button_interrogate = None - button_deepbooru = None - if is_img2img: - with gr.Column(scale=1, elem_id="interrogate_col"): - button_interrogate = gr.Button('Interrogate\nCLIP', elem_id="interrogate") - button_deepbooru = gr.Button('Interrogate\nDeepBooru', elem_id="deepbooru") - - with gr.Column(scale=1, elem_id=f"{id_part}_actions_column"): - with gr.Row(elem_id=f"{id_part}_generate_box"): - interrupt = gr.Button('Interrupt', elem_id=f"{id_part}_interrupt") - skip = gr.Button('Skip', elem_id=f"{id_part}_skip") - submit = gr.Button('Generate', elem_id=f"{id_part}_generate", variant='primary') - - skip.click( - fn=lambda: shared.state.skip(), - inputs=[], - outputs=[], - ) - - interrupt.click( - fn=lambda: shared.state.interrupt(), - inputs=[], - outputs=[], - ) - - with gr.Row(elem_id=f"{id_part}_tools"): - paste = ToolButton(value=paste_symbol, elem_id="paste") - clear_prompt_button = ToolButton(value=clear_prompt_symbol, elem_id=f"{id_part}_clear_prompt") - extra_networks_button = ToolButton(value=extra_networks_symbol, elem_id=f"{id_part}_extra_networks") - prompt_style_apply = ToolButton(value=apply_style_symbol, elem_id=f"{id_part}_style_apply") - save_style = ToolButton(value=save_style_symbol, elem_id=f"{id_part}_style_create") - - token_counter = gr.HTML(value="", elem_id=f"{id_part}_token_counter") - token_button = gr.Button(visible=False, elem_id=f"{id_part}_token_button") - negative_token_counter = gr.HTML(value="", elem_id=f"{id_part}_negative_token_counter") - negative_token_button = gr.Button(visible=False, elem_id=f"{id_part}_negative_token_button") - - clear_prompt_button.click( - fn=lambda *x: x, - _js="confirm_clear_prompt", - inputs=[prompt, negative_prompt], - outputs=[prompt, negative_prompt], - ) - - with gr.Row(elem_id=f"{id_part}_styles_row"): - prompt_styles = gr.Dropdown(label="Styles", elem_id=f"{id_part}_styles", choices=[k for k, v in shared.prompt_styles.styles.items()], value=[], multiselect=True) - create_refresh_button(prompt_styles, shared.prompt_styles.reload, lambda: {"choices": [k for k, v in shared.prompt_styles.styles.items()]}, f"refresh_{id_part}_styles") - - return prompt, prompt_styles, negative_prompt, submit, button_interrogate, button_deepbooru, prompt_style_apply, save_style, paste, extra_networks_button, token_counter, token_button, negative_token_counter, negative_token_button - - -def setup_progressbar(*args, **kwargs): - pass - - -def apply_setting(key, value): - if value is None: - return gr.update() - - if shared.cmd_opts.freeze_settings: - return gr.update() - - # dont allow model to be swapped when model hash exists in prompt - if key == "sd_model_checkpoint" and opts.disable_weights_auto_swap: - return gr.update() - - if key == "sd_model_checkpoint": - ckpt_info = sd_models.get_closet_checkpoint_match(value) - - if ckpt_info is not None: - value = ckpt_info.title - else: - return gr.update() - - comp_args = opts.data_labels[key].component_args - if comp_args and isinstance(comp_args, dict) and comp_args.get('visible') is False: - return - - valtype = type(opts.data_labels[key].default) - oldval = opts.data.get(key, None) - opts.data[key] = valtype(value) if valtype != type(None) else value - if oldval != value and opts.data_labels[key].onchange is not None: - opts.data_labels[key].onchange() - - opts.save(shared.config_filename) - return getattr(opts, key) - - -def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_id): - def refresh(): - refresh_method() - args = refreshed_args() if callable(refreshed_args) else refreshed_args - - for k, v in args.items(): - setattr(refresh_component, k, v) - - return gr.update(**(args or {})) - - refresh_button = ToolButton(value=refresh_symbol, elem_id=elem_id) - refresh_button.click( - fn=refresh, - inputs=[], - outputs=[refresh_component] - ) - return refresh_button - - -def create_output_panel(tabname, outdir): - return ui_common.create_output_panel(tabname, outdir) - - -def create_sampler_and_steps_selection(choices, tabname): - if opts.samplers_in_dropdown: - with FormRow(elem_id=f"sampler_selection_{tabname}"): - sampler_index = gr.Dropdown(label='Sampling method', elem_id=f"{tabname}_sampling", choices=[x.name for x in choices], value=choices[0].name, type="index") - steps = gr.Slider(minimum=1, maximum=150, step=1, elem_id=f"{tabname}_steps", label="Sampling steps", value=20) - else: - with FormGroup(elem_id=f"sampler_selection_{tabname}"): - steps = gr.Slider(minimum=1, maximum=150, step=1, elem_id=f"{tabname}_steps", label="Sampling steps", value=20) - sampler_index = gr.Radio(label='Sampling method', elem_id=f"{tabname}_sampling", choices=[x.name for x in choices], value=choices[0].name, type="index") - - return steps, sampler_index - - -def ordered_ui_categories(): - user_order = {x.strip(): i * 2 + 1 for i, x in enumerate(shared.opts.ui_reorder.split(","))} - - for i, category in sorted(enumerate(shared.ui_reorder_categories), key=lambda x: user_order.get(x[1], x[0] * 2 + 0)): - yield category - - -def get_value_for_setting(key): - value = getattr(opts, key) - - info = opts.data_labels[key] - args = info.component_args() if callable(info.component_args) else info.component_args or {} - args = {k: v for k, v in args.items() if k not in {'precision'}} - - return gr.update(value=value, **args) - - -def create_override_settings_dropdown(tabname, row): - dropdown = gr.Dropdown([], label="Override settings", visible=False, elem_id=f"{tabname}_override_settings", multiselect=True) - - dropdown.change( - fn=lambda x: gr.Dropdown.update(visible=len(x) > 0), - inputs=[dropdown], - outputs=[dropdown], - ) - - return dropdown - - -def create_ui(): - import modules.img2img - import modules.txt2img - - reload_javascript() - - parameters_copypaste.reset() - - modules.scripts.scripts_current = modules.scripts.scripts_txt2img - modules.scripts.scripts_txt2img.initialize_scripts(is_img2img=False) - - with gr.Blocks(analytics_enabled=False) as txt2img_interface: - txt2img_prompt, txt2img_prompt_styles, txt2img_negative_prompt, submit, _, _, txt2img_prompt_style_apply, txt2img_save_style, txt2img_paste, extra_networks_button, token_counter, token_button, negative_token_counter, negative_token_button = create_toprow(is_img2img=False) - - dummy_component = gr.Label(visible=False) - txt_prompt_img = gr.File(label="", elem_id="txt2img_prompt_image", file_count="single", type="binary", visible=False) - - with FormRow(variant='compact', elem_id="txt2img_extra_networks", visible=False) as extra_networks: - from modules import ui_extra_networks - extra_networks_ui = ui_extra_networks.create_ui(extra_networks, extra_networks_button, 'txt2img') - - with gr.Row().style(equal_height=False): - with gr.Column(variant='compact', elem_id="txt2img_settings"): - for category in ordered_ui_categories(): - if category == "sampler": - steps, sampler_index = create_sampler_and_steps_selection(samplers, "txt2img") - - elif category == "dimensions": - with FormRow(): - with gr.Column(elem_id="txt2img_column_size", scale=4): - width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="txt2img_width") - height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="txt2img_height") - - res_switch_btn = ToolButton(value=switch_values_symbol, elem_id="txt2img_res_switch_btn") - if opts.dimensions_and_batch_together: - with gr.Column(elem_id="txt2img_column_batch"): - batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="txt2img_batch_count") - batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="txt2img_batch_size") - - elif category == "cfg": - cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0, elem_id="txt2img_cfg_scale") - - elif category == "seed": - seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox = create_seed_inputs('txt2img') - - elif category == "checkboxes": - with FormRow(elem_id="txt2img_checkboxes", variant="compact"): - restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1, elem_id="txt2img_restore_faces") - tiling = gr.Checkbox(label='Tiling', value=False, elem_id="txt2img_tiling") - enable_hr = gr.Checkbox(label='Hires. fix', value=False, elem_id="txt2img_enable_hr") - hr_final_resolution = FormHTML(value="", elem_id="txtimg_hr_finalres", label="Upscaled resolution", interactive=False) - - elif category == "hires_fix": - with FormGroup(visible=False, elem_id="txt2img_hires_fix") as hr_options: - with FormRow(elem_id="txt2img_hires_fix_row1", variant="compact"): - hr_upscaler = gr.Dropdown(label="Upscaler", elem_id="txt2img_hr_upscaler", choices=[*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]], value=shared.latent_upscale_default_mode) - hr_second_pass_steps = gr.Slider(minimum=0, maximum=150, step=1, label='Hires steps', value=0, elem_id="txt2img_hires_steps") - denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.7, elem_id="txt2img_denoising_strength") - - with FormRow(elem_id="txt2img_hires_fix_row2", variant="compact"): - hr_scale = gr.Slider(minimum=1.0, maximum=4.0, step=0.05, label="Upscale by", value=2.0, elem_id="txt2img_hr_scale") - hr_resize_x = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize width to", value=0, elem_id="txt2img_hr_resize_x") - hr_resize_y = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize height to", value=0, elem_id="txt2img_hr_resize_y") - - elif category == "batch": - if not opts.dimensions_and_batch_together: - with FormRow(elem_id="txt2img_column_batch"): - batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="txt2img_batch_count") - batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="txt2img_batch_size") - - elif category == "override_settings": - with FormRow(elem_id="txt2img_override_settings_row") as row: - override_settings = create_override_settings_dropdown('txt2img', row) - - elif category == "scripts": - with FormGroup(elem_id="txt2img_script_container"): - custom_inputs = modules.scripts.scripts_txt2img.setup_ui() - - hr_resolution_preview_inputs = [enable_hr, width, height, hr_scale, hr_resize_x, hr_resize_y] - for input in hr_resolution_preview_inputs: - input.change( - fn=calc_resolution_hires, - inputs=hr_resolution_preview_inputs, - outputs=[hr_final_resolution], - show_progress=False, - ) - input.change( - None, - _js="onCalcResolutionHires", - inputs=hr_resolution_preview_inputs, - outputs=[], - show_progress=False, - ) - - txt2img_gallery, generation_info, html_info, html_log = create_output_panel("txt2img", opts.outdir_txt2img_samples) - - connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False) - connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True) - - txt2img_args = dict( - fn=wrap_gradio_gpu_call(modules.txt2img.txt2img, extra_outputs=[None, '', '']), - _js="submit", - inputs=[ - dummy_component, - txt2img_prompt, - txt2img_negative_prompt, - txt2img_prompt_styles, - steps, - sampler_index, - restore_faces, - tiling, - batch_count, - batch_size, - cfg_scale, - seed, - subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox, - height, - width, - enable_hr, - denoising_strength, - hr_scale, - hr_upscaler, - hr_second_pass_steps, - hr_resize_x, - hr_resize_y, - override_settings, - ] + custom_inputs, - - outputs=[ - txt2img_gallery, - generation_info, - html_info, - html_log, - ], - show_progress=False, - ) - - txt2img_prompt.submit(**txt2img_args) - submit.click(**txt2img_args) - - res_switch_btn.click(lambda w, h: (h, w), inputs=[width, height], outputs=[width, height]) - - txt_prompt_img.change( - fn=modules.images.image_data, - inputs=[ - txt_prompt_img - ], - outputs=[ - txt2img_prompt, - txt_prompt_img - ] - ) - - enable_hr.change( - fn=lambda x: gr_show(x), - inputs=[enable_hr], - outputs=[hr_options], - show_progress = False, - ) - - txt2img_paste_fields = [ - (txt2img_prompt, "Prompt"), - (txt2img_negative_prompt, "Negative prompt"), - (steps, "Steps"), - (sampler_index, "Sampler"), - (restore_faces, "Face restoration"), - (cfg_scale, "CFG scale"), - (seed, "Seed"), - (width, "Size-1"), - (height, "Size-2"), - (batch_size, "Batch size"), - (subseed, "Variation seed"), - (subseed_strength, "Variation seed strength"), - (seed_resize_from_w, "Seed resize from-1"), - (seed_resize_from_h, "Seed resize from-2"), - (denoising_strength, "Denoising strength"), - (enable_hr, lambda d: "Denoising strength" in d), - (hr_options, lambda d: gr.Row.update(visible="Denoising strength" in d)), - (hr_scale, "Hires upscale"), - (hr_upscaler, "Hires upscaler"), - (hr_second_pass_steps, "Hires steps"), - (hr_resize_x, "Hires resize-1"), - (hr_resize_y, "Hires resize-2"), - *modules.scripts.scripts_txt2img.infotext_fields - ] - parameters_copypaste.add_paste_fields("txt2img", None, txt2img_paste_fields, override_settings) - parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding( - paste_button=txt2img_paste, tabname="txt2img", source_text_component=txt2img_prompt, source_image_component=None, - )) - - txt2img_preview_params = [ - txt2img_prompt, - txt2img_negative_prompt, - steps, - sampler_index, - cfg_scale, - seed, - width, - height, - ] - - token_button.click(fn=wrap_queued_call(update_token_counter), inputs=[txt2img_prompt, steps], outputs=[token_counter]) - negative_token_button.click(fn=wrap_queued_call(update_token_counter), inputs=[txt2img_negative_prompt, steps], outputs=[negative_token_counter]) - - ui_extra_networks.setup_ui(extra_networks_ui, txt2img_gallery) - - modules.scripts.scripts_current = modules.scripts.scripts_img2img - modules.scripts.scripts_img2img.initialize_scripts(is_img2img=True) - - with gr.Blocks(analytics_enabled=False) as img2img_interface: - img2img_prompt, img2img_prompt_styles, img2img_negative_prompt, submit, img2img_interrogate, img2img_deepbooru, img2img_prompt_style_apply, img2img_save_style, img2img_paste, extra_networks_button, token_counter, token_button, negative_token_counter, negative_token_button = create_toprow(is_img2img=True) - - img2img_prompt_img = gr.File(label="", elem_id="img2img_prompt_image", file_count="single", type="binary", visible=False) - - with FormRow(variant='compact', elem_id="img2img_extra_networks", visible=False) as extra_networks: - from modules import ui_extra_networks - extra_networks_ui_img2img = ui_extra_networks.create_ui(extra_networks, extra_networks_button, 'img2img') - - with FormRow().style(equal_height=False): - with gr.Column(variant='compact', elem_id="img2img_settings"): - copy_image_buttons = [] - copy_image_destinations = {} - - def add_copy_image_controls(tab_name, elem): - with gr.Row(variant="compact", elem_id=f"img2img_copy_to_{tab_name}"): - gr.HTML("Copy image to: ", elem_id=f"img2img_label_copy_to_{tab_name}") - - for title, name in zip(['img2img', 'sketch', 'inpaint', 'inpaint sketch'], ['img2img', 'sketch', 'inpaint', 'inpaint_sketch']): - if name == tab_name: - gr.Button(title, interactive=False) - copy_image_destinations[name] = elem - continue - - button = gr.Button(title) - copy_image_buttons.append((button, name, elem)) - - with gr.Tabs(elem_id="mode_img2img"): - with gr.TabItem('img2img', id='img2img', elem_id="img2img_img2img_tab") as tab_img2img: - init_img = gr.Image(label="Image for img2img", elem_id="img2img_image", show_label=False, source="upload", interactive=True, type="pil", tool="editor", image_mode="RGBA").style(height=480) - add_copy_image_controls('img2img', init_img) - - with gr.TabItem('Sketch', id='img2img_sketch', elem_id="img2img_img2img_sketch_tab") as tab_sketch: - sketch = gr.Image(label="Image for img2img", elem_id="img2img_sketch", show_label=False, source="upload", interactive=True, type="pil", tool="color-sketch", image_mode="RGBA").style(height=480) - add_copy_image_controls('sketch', sketch) - - with gr.TabItem('Inpaint', id='inpaint', elem_id="img2img_inpaint_tab") as tab_inpaint: - init_img_with_mask = gr.Image(label="Image for inpainting with mask", show_label=False, elem_id="img2maskimg", source="upload", interactive=True, type="pil", tool="sketch", image_mode="RGBA").style(height=480) - add_copy_image_controls('inpaint', init_img_with_mask) - - with gr.TabItem('Inpaint sketch', id='inpaint_sketch', elem_id="img2img_inpaint_sketch_tab") as tab_inpaint_color: - inpaint_color_sketch = gr.Image(label="Color sketch inpainting", show_label=False, elem_id="inpaint_sketch", source="upload", interactive=True, type="pil", tool="color-sketch", image_mode="RGBA").style(height=480) - inpaint_color_sketch_orig = gr.State(None) - add_copy_image_controls('inpaint_sketch', inpaint_color_sketch) - - def update_orig(image, state): - if image is not None: - same_size = state is not None and state.size == image.size - has_exact_match = np.any(np.all(np.array(image) == np.array(state), axis=-1)) - edited = same_size and has_exact_match - return image if not edited or state is None else state - - inpaint_color_sketch.change(update_orig, [inpaint_color_sketch, inpaint_color_sketch_orig], inpaint_color_sketch_orig) - - with gr.TabItem('Inpaint upload', id='inpaint_upload', elem_id="img2img_inpaint_upload_tab") as tab_inpaint_upload: - init_img_inpaint = gr.Image(label="Image for img2img", show_label=False, source="upload", interactive=True, type="pil", elem_id="img_inpaint_base") - init_mask_inpaint = gr.Image(label="Mask", source="upload", interactive=True, type="pil", elem_id="img_inpaint_mask") - - with gr.TabItem('Batch', id='batch', elem_id="img2img_batch_tab") as tab_batch: - hidden = '
    Disabled when launched with --hide-ui-dir-config.' if shared.cmd_opts.hide_ui_dir_config else '' - gr.HTML( - f"

    Process images in a directory on the same machine where the server is running." + - f"
    Use an empty output directory to save pictures normally instead of writing to the output directory." + - f"
    Add inpaint batch mask directory to enable inpaint batch processing." - f"{hidden}

    " - ) - img2img_batch_input_dir = gr.Textbox(label="Input directory", **shared.hide_dirs, elem_id="img2img_batch_input_dir") - img2img_batch_output_dir = gr.Textbox(label="Output directory", **shared.hide_dirs, elem_id="img2img_batch_output_dir") - img2img_batch_inpaint_mask_dir = gr.Textbox(label="Inpaint batch mask directory (required for inpaint batch processing only)", **shared.hide_dirs, elem_id="img2img_batch_inpaint_mask_dir") - - def copy_image(img): - if isinstance(img, dict) and 'image' in img: - return img['image'] - - return img - - for button, name, elem in copy_image_buttons: - button.click( - fn=copy_image, - inputs=[elem], - outputs=[copy_image_destinations[name]], - ) - button.click( - fn=lambda: None, - _js="switch_to_"+name.replace(" ", "_"), - inputs=[], - outputs=[], - ) - - with FormRow(): - resize_mode = gr.Radio(label="Resize mode", elem_id="resize_mode", choices=["Just resize", "Crop and resize", "Resize and fill", "Just resize (latent upscale)"], type="index", value="Just resize") - - for category in ordered_ui_categories(): - if category == "sampler": - steps, sampler_index = create_sampler_and_steps_selection(samplers_for_img2img, "img2img") - - elif category == "dimensions": - with FormRow(): - with gr.Column(elem_id="img2img_column_size", scale=4): - width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="img2img_width") - height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="img2img_height") - - res_switch_btn = ToolButton(value=switch_values_symbol, elem_id="img2img_res_switch_btn") - if opts.dimensions_and_batch_together: - with gr.Column(elem_id="img2img_column_batch"): - batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="img2img_batch_count") - batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="img2img_batch_size") - - elif category == "cfg": - with FormGroup(): - with FormRow(): - cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0, elem_id="img2img_cfg_scale") - image_cfg_scale = gr.Slider(minimum=0, maximum=3.0, step=0.05, label='Image CFG Scale', value=1.5, elem_id="img2img_image_cfg_scale", visible=shared.sd_model and shared.sd_model.cond_stage_key == "edit") - denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.75, elem_id="img2img_denoising_strength") - - elif category == "seed": - seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox = create_seed_inputs('img2img') - - elif category == "checkboxes": - with FormRow(elem_id="img2img_checkboxes", variant="compact"): - restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1, elem_id="img2img_restore_faces") - tiling = gr.Checkbox(label='Tiling', value=False, elem_id="img2img_tiling") - - elif category == "batch": - if not opts.dimensions_and_batch_together: - with FormRow(elem_id="img2img_column_batch"): - batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="img2img_batch_count") - batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="img2img_batch_size") - - elif category == "override_settings": - with FormRow(elem_id="img2img_override_settings_row") as row: - override_settings = create_override_settings_dropdown('img2img', row) - - elif category == "scripts": - with FormGroup(elem_id="img2img_script_container"): - custom_inputs = modules.scripts.scripts_img2img.setup_ui() - - elif category == "inpaint": - with FormGroup(elem_id="inpaint_controls", visible=False) as inpaint_controls: - with FormRow(): - mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4, elem_id="img2img_mask_blur") - mask_alpha = gr.Slider(label="Mask transparency", visible=False, elem_id="img2img_mask_alpha") - - with FormRow(): - inpainting_mask_invert = gr.Radio(label='Mask mode', choices=['Inpaint masked', 'Inpaint not masked'], value='Inpaint masked', type="index", elem_id="img2img_mask_mode") - - with FormRow(): - inpainting_fill = gr.Radio(label='Masked content', choices=['fill', 'original', 'latent noise', 'latent nothing'], value='original', type="index", elem_id="img2img_inpainting_fill") - - with FormRow(): - with gr.Column(): - inpaint_full_res = gr.Radio(label="Inpaint area", choices=["Whole picture", "Only masked"], type="index", value="Whole picture", elem_id="img2img_inpaint_full_res") - - with gr.Column(scale=4): - inpaint_full_res_padding = gr.Slider(label='Only masked padding, pixels', minimum=0, maximum=256, step=4, value=32, elem_id="img2img_inpaint_full_res_padding") - - def select_img2img_tab(tab): - return gr.update(visible=tab in [2, 3, 4]), gr.update(visible=tab == 3), - - for i, elem in enumerate([tab_img2img, tab_sketch, tab_inpaint, tab_inpaint_color, tab_inpaint_upload, tab_batch]): - elem.select( - fn=lambda tab=i: select_img2img_tab(tab), - inputs=[], - outputs=[inpaint_controls, mask_alpha], - ) - - img2img_gallery, generation_info, html_info, html_log = create_output_panel("img2img", opts.outdir_img2img_samples) - - connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False) - connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True) - - img2img_prompt_img.change( - fn=modules.images.image_data, - inputs=[ - img2img_prompt_img - ], - outputs=[ - img2img_prompt, - img2img_prompt_img - ] - ) - - img2img_args = dict( - fn=wrap_gradio_gpu_call(modules.img2img.img2img, extra_outputs=[None, '', '']), - _js="submit_img2img", - inputs=[ - dummy_component, - dummy_component, - img2img_prompt, - img2img_negative_prompt, - img2img_prompt_styles, - init_img, - sketch, - init_img_with_mask, - inpaint_color_sketch, - inpaint_color_sketch_orig, - init_img_inpaint, - init_mask_inpaint, - steps, - sampler_index, - mask_blur, - mask_alpha, - inpainting_fill, - restore_faces, - tiling, - batch_count, - batch_size, - cfg_scale, - image_cfg_scale, - denoising_strength, - seed, - subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox, - height, - width, - resize_mode, - inpaint_full_res, - inpaint_full_res_padding, - inpainting_mask_invert, - img2img_batch_input_dir, - img2img_batch_output_dir, - img2img_batch_inpaint_mask_dir, - override_settings, - ] + custom_inputs, - outputs=[ - img2img_gallery, - generation_info, - html_info, - html_log, - ], - show_progress=False, - ) - - interrogate_args = dict( - _js="get_img2img_tab_index", - inputs=[ - dummy_component, - img2img_batch_input_dir, - img2img_batch_output_dir, - init_img, - sketch, - init_img_with_mask, - inpaint_color_sketch, - init_img_inpaint, - ], - outputs=[img2img_prompt, dummy_component], - ) - - img2img_prompt.submit(**img2img_args) - submit.click(**img2img_args) - res_switch_btn.click(lambda w, h: (h, w), inputs=[width, height], outputs=[width, height]) - - img2img_interrogate.click( - fn=lambda *args: process_interrogate(interrogate, *args), - **interrogate_args, - ) - - img2img_deepbooru.click( - fn=lambda *args: process_interrogate(interrogate_deepbooru, *args), - **interrogate_args, - ) - - prompts = [(txt2img_prompt, txt2img_negative_prompt), (img2img_prompt, img2img_negative_prompt)] - style_dropdowns = [txt2img_prompt_styles, img2img_prompt_styles] - style_js_funcs = ["update_txt2img_tokens", "update_img2img_tokens"] - - for button, (prompt, negative_prompt) in zip([txt2img_save_style, img2img_save_style], prompts): - button.click( - fn=add_style, - _js="ask_for_style_name", - # Have to pass empty dummy component here, because the JavaScript and Python function have to accept - # the same number of parameters, but we only know the style-name after the JavaScript prompt - inputs=[dummy_component, prompt, negative_prompt], - outputs=[txt2img_prompt_styles, img2img_prompt_styles], - ) - - for button, (prompt, negative_prompt), styles, js_func in zip([txt2img_prompt_style_apply, img2img_prompt_style_apply], prompts, style_dropdowns, style_js_funcs): - button.click( - fn=apply_styles, - _js=js_func, - inputs=[prompt, negative_prompt, styles], - outputs=[prompt, negative_prompt, styles], - ) - - token_button.click(fn=update_token_counter, inputs=[img2img_prompt, steps], outputs=[token_counter]) - negative_token_button.click(fn=wrap_queued_call(update_token_counter), inputs=[txt2img_negative_prompt, steps], outputs=[negative_token_counter]) - - ui_extra_networks.setup_ui(extra_networks_ui_img2img, img2img_gallery) - - img2img_paste_fields = [ - (img2img_prompt, "Prompt"), - (img2img_negative_prompt, "Negative prompt"), - (steps, "Steps"), - (sampler_index, "Sampler"), - (restore_faces, "Face restoration"), - (cfg_scale, "CFG scale"), - (image_cfg_scale, "Image CFG scale"), - (seed, "Seed"), - (width, "Size-1"), - (height, "Size-2"), - (batch_size, "Batch size"), - (subseed, "Variation seed"), - (subseed_strength, "Variation seed strength"), - (seed_resize_from_w, "Seed resize from-1"), - (seed_resize_from_h, "Seed resize from-2"), - (denoising_strength, "Denoising strength"), - (mask_blur, "Mask blur"), - *modules.scripts.scripts_img2img.infotext_fields - ] - parameters_copypaste.add_paste_fields("img2img", init_img, img2img_paste_fields, override_settings) - parameters_copypaste.add_paste_fields("inpaint", init_img_with_mask, img2img_paste_fields, override_settings) - parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding( - paste_button=img2img_paste, tabname="img2img", source_text_component=img2img_prompt, source_image_component=None, - )) - - modules.scripts.scripts_current = None - - with gr.Blocks(analytics_enabled=False) as extras_interface: - ui_postprocessing.create_ui() - - with gr.Blocks(analytics_enabled=False) as pnginfo_interface: - with gr.Row().style(equal_height=False): - with gr.Column(variant='panel'): - image = gr.Image(elem_id="pnginfo_image", label="Source", source="upload", interactive=True, type="pil") - - with gr.Column(variant='panel'): - html = gr.HTML() - generation_info = gr.Textbox(visible=False, elem_id="pnginfo_generation_info") - html2 = gr.HTML() - with gr.Row(): - buttons = parameters_copypaste.create_buttons(["txt2img", "img2img", "inpaint", "extras"]) - - for tabname, button in buttons.items(): - parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding( - paste_button=button, tabname=tabname, source_text_component=generation_info, source_image_component=image, - )) - - image.change( - fn=wrap_gradio_call(modules.extras.run_pnginfo), - inputs=[image], - outputs=[html, generation_info, html2], - ) - - def update_interp_description(value): - interp_description_css = "

    {}

    " - interp_descriptions = { - "No interpolation": interp_description_css.format("No interpolation will be used. Requires one model; A. Allows for format conversion and VAE baking."), - "Weighted sum": interp_description_css.format("A weighted sum will be used for interpolation. Requires two models; A and B. The result is calculated as A * (1 - M) + B * M"), - "Add difference": interp_description_css.format("The difference between the last two models will be added to the first. Requires three models; A, B and C. The result is calculated as A + (B - C) * M") - } - return interp_descriptions[value] - - with gr.Blocks(analytics_enabled=False) as modelmerger_interface: - with gr.Row().style(equal_height=False): - with gr.Column(variant='compact'): - interp_description = gr.HTML(value=update_interp_description("Weighted sum"), elem_id="modelmerger_interp_description") - - with FormRow(elem_id="modelmerger_models"): - primary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_primary_model_name", label="Primary model (A)") - create_refresh_button(primary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_A") - - secondary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_secondary_model_name", label="Secondary model (B)") - create_refresh_button(secondary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_B") - - tertiary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_tertiary_model_name", label="Tertiary model (C)") - create_refresh_button(tertiary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_C") - - custom_name = gr.Textbox(label="Custom Name (Optional)", elem_id="modelmerger_custom_name") - interp_amount = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label='Multiplier (M) - set to 0 to get model A', value=0.3, elem_id="modelmerger_interp_amount") - interp_method = gr.Radio(choices=["No interpolation", "Weighted sum", "Add difference"], value="Weighted sum", label="Interpolation Method", elem_id="modelmerger_interp_method") - interp_method.change(fn=update_interp_description, inputs=[interp_method], outputs=[interp_description]) - - with FormRow(): - checkpoint_format = gr.Radio(choices=["ckpt", "safetensors"], value="ckpt", label="Checkpoint format", elem_id="modelmerger_checkpoint_format") - save_as_half = gr.Checkbox(value=False, label="Save as float16", elem_id="modelmerger_save_as_half") - - with FormRow(): - with gr.Column(): - config_source = gr.Radio(choices=["A, B or C", "B", "C", "Don't"], value="A, B or C", label="Copy config from", type="index", elem_id="modelmerger_config_method") - - with gr.Column(): - with FormRow(): - bake_in_vae = gr.Dropdown(choices=["None"] + list(sd_vae.vae_dict), value="None", label="Bake in VAE", elem_id="modelmerger_bake_in_vae") - create_refresh_button(bake_in_vae, sd_vae.refresh_vae_list, lambda: {"choices": ["None"] + list(sd_vae.vae_dict)}, "modelmerger_refresh_bake_in_vae") - - with FormRow(): - discard_weights = gr.Textbox(value="", label="Discard weights with matching name", elem_id="modelmerger_discard_weights") - - with gr.Row(): - modelmerger_merge = gr.Button(elem_id="modelmerger_merge", value="Merge", variant='primary') - - with gr.Column(variant='compact', elem_id="modelmerger_results_container"): - with gr.Group(elem_id="modelmerger_results_panel"): - modelmerger_result = gr.HTML(elem_id="modelmerger_result", show_label=False) - - with gr.Blocks(analytics_enabled=False) as train_interface: - with gr.Row().style(equal_height=False): - gr.HTML(value="

    See wiki for detailed explanation.

    ") - - with gr.Row(variant="compact").style(equal_height=False): - with gr.Tabs(elem_id="train_tabs"): - - with gr.Tab(label="Create embedding"): - new_embedding_name = gr.Textbox(label="Name", elem_id="train_new_embedding_name") - initialization_text = gr.Textbox(label="Initialization text", value="*", elem_id="train_initialization_text") - nvpt = gr.Slider(label="Number of vectors per token", minimum=1, maximum=75, step=1, value=1, elem_id="train_nvpt") - overwrite_old_embedding = gr.Checkbox(value=False, label="Overwrite Old Embedding", elem_id="train_overwrite_old_embedding") - - with gr.Row(): - with gr.Column(scale=3): - gr.HTML(value="") - - with gr.Column(): - create_embedding = gr.Button(value="Create embedding", variant='primary', elem_id="train_create_embedding") - - with gr.Tab(label="Create hypernetwork"): - new_hypernetwork_name = gr.Textbox(label="Name", elem_id="train_new_hypernetwork_name") - new_hypernetwork_sizes = gr.CheckboxGroup(label="Modules", value=["768", "320", "640", "1280"], choices=["768", "1024", "320", "640", "1280"], elem_id="train_new_hypernetwork_sizes") - new_hypernetwork_layer_structure = gr.Textbox("1, 2, 1", label="Enter hypernetwork layer structure", placeholder="1st and last digit must be 1. ex:'1, 2, 1'", elem_id="train_new_hypernetwork_layer_structure") - new_hypernetwork_activation_func = gr.Dropdown(value="linear", label="Select activation function of hypernetwork. Recommended : Swish / Linear(none)", choices=modules.hypernetworks.ui.keys, elem_id="train_new_hypernetwork_activation_func") - new_hypernetwork_initialization_option = gr.Dropdown(value = "Normal", label="Select Layer weights initialization. Recommended: Kaiming for relu-like, Xavier for sigmoid-like, Normal otherwise", choices=["Normal", "KaimingUniform", "KaimingNormal", "XavierUniform", "XavierNormal"], elem_id="train_new_hypernetwork_initialization_option") - new_hypernetwork_add_layer_norm = gr.Checkbox(label="Add layer normalization", elem_id="train_new_hypernetwork_add_layer_norm") - new_hypernetwork_use_dropout = gr.Checkbox(label="Use dropout", elem_id="train_new_hypernetwork_use_dropout") - new_hypernetwork_dropout_structure = gr.Textbox("0, 0, 0", label="Enter hypernetwork Dropout structure (or empty). Recommended : 0~0.35 incrementing sequence: 0, 0.05, 0.15", placeholder="1st and last digit must be 0 and values should be between 0 and 1. ex:'0, 0.01, 0'") - overwrite_old_hypernetwork = gr.Checkbox(value=False, label="Overwrite Old Hypernetwork", elem_id="train_overwrite_old_hypernetwork") - - with gr.Row(): - with gr.Column(scale=3): - gr.HTML(value="") - - with gr.Column(): - create_hypernetwork = gr.Button(value="Create hypernetwork", variant='primary', elem_id="train_create_hypernetwork") - - with gr.Tab(label="Preprocess images"): - process_src = gr.Textbox(label='Source directory', elem_id="train_process_src") - process_dst = gr.Textbox(label='Destination directory', elem_id="train_process_dst") - process_width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="train_process_width") - process_height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="train_process_height") - preprocess_txt_action = gr.Dropdown(label='Existing Caption txt Action', value="ignore", choices=["ignore", "copy", "prepend", "append"], elem_id="train_preprocess_txt_action") - - with gr.Row(): - process_flip = gr.Checkbox(label='Create flipped copies', elem_id="train_process_flip") - process_split = gr.Checkbox(label='Split oversized images', elem_id="train_process_split") - process_focal_crop = gr.Checkbox(label='Auto focal point crop', elem_id="train_process_focal_crop") - process_multicrop = gr.Checkbox(label='Auto-sized crop', elem_id="train_process_multicrop") - process_caption = gr.Checkbox(label='Use BLIP for caption', elem_id="train_process_caption") - process_caption_deepbooru = gr.Checkbox(label='Use deepbooru for caption', visible=True, elem_id="train_process_caption_deepbooru") - - with gr.Row(visible=False) as process_split_extra_row: - process_split_threshold = gr.Slider(label='Split image threshold', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="train_process_split_threshold") - process_overlap_ratio = gr.Slider(label='Split image overlap ratio', value=0.2, minimum=0.0, maximum=0.9, step=0.05, elem_id="train_process_overlap_ratio") - - with gr.Row(visible=False) as process_focal_crop_row: - process_focal_crop_face_weight = gr.Slider(label='Focal point face weight', value=0.9, minimum=0.0, maximum=1.0, step=0.05, elem_id="train_process_focal_crop_face_weight") - process_focal_crop_entropy_weight = gr.Slider(label='Focal point entropy weight', value=0.15, minimum=0.0, maximum=1.0, step=0.05, elem_id="train_process_focal_crop_entropy_weight") - process_focal_crop_edges_weight = gr.Slider(label='Focal point edges weight', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="train_process_focal_crop_edges_weight") - process_focal_crop_debug = gr.Checkbox(label='Create debug image', elem_id="train_process_focal_crop_debug") - - with gr.Column(visible=False) as process_multicrop_col: - gr.Markdown('Each image is center-cropped with an automatically chosen width and height.') - with gr.Row(): - process_multicrop_mindim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension lower bound", value=384, elem_id="train_process_multicrop_mindim") - process_multicrop_maxdim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension upper bound", value=768, elem_id="train_process_multicrop_maxdim") - with gr.Row(): - process_multicrop_minarea = gr.Slider(minimum=64*64, maximum=2048*2048, step=1, label="Area lower bound", value=64*64, elem_id="train_process_multicrop_minarea") - process_multicrop_maxarea = gr.Slider(minimum=64*64, maximum=2048*2048, step=1, label="Area upper bound", value=640*640, elem_id="train_process_multicrop_maxarea") - with gr.Row(): - process_multicrop_objective = gr.Radio(["Maximize area", "Minimize error"], value="Maximize area", label="Resizing objective", elem_id="train_process_multicrop_objective") - process_multicrop_threshold = gr.Slider(minimum=0, maximum=1, step=0.01, label="Error threshold", value=0.1, elem_id="train_process_multicrop_threshold") - - with gr.Row(): - with gr.Column(scale=3): - gr.HTML(value="") - - with gr.Column(): - with gr.Row(): - interrupt_preprocessing = gr.Button("Interrupt", elem_id="train_interrupt_preprocessing") - run_preprocess = gr.Button(value="Preprocess", variant='primary', elem_id="train_run_preprocess") - - process_split.change( - fn=lambda show: gr_show(show), - inputs=[process_split], - outputs=[process_split_extra_row], - ) - - process_focal_crop.change( - fn=lambda show: gr_show(show), - inputs=[process_focal_crop], - outputs=[process_focal_crop_row], - ) - - process_multicrop.change( - fn=lambda show: gr_show(show), - inputs=[process_multicrop], - outputs=[process_multicrop_col], - ) - - def get_textual_inversion_template_names(): - return sorted([x for x in textual_inversion.textual_inversion_templates]) - - with gr.Tab(label="Train"): - gr.HTML(value="

    Train an embedding or Hypernetwork; you must specify a directory with a set of 1:1 ratio images [wiki]

    ") - with FormRow(): - train_embedding_name = gr.Dropdown(label='Embedding', elem_id="train_embedding", choices=sorted(sd_hijack.model_hijack.embedding_db.word_embeddings.keys())) - create_refresh_button(train_embedding_name, sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings, lambda: {"choices": sorted(sd_hijack.model_hijack.embedding_db.word_embeddings.keys())}, "refresh_train_embedding_name") - - train_hypernetwork_name = gr.Dropdown(label='Hypernetwork', elem_id="train_hypernetwork", choices=[x for x in shared.hypernetworks.keys()]) - create_refresh_button(train_hypernetwork_name, shared.reload_hypernetworks, lambda: {"choices": sorted([x for x in shared.hypernetworks.keys()])}, "refresh_train_hypernetwork_name") - - with FormRow(): - embedding_learn_rate = gr.Textbox(label='Embedding Learning rate', placeholder="Embedding Learning rate", value="0.005", elem_id="train_embedding_learn_rate") - hypernetwork_learn_rate = gr.Textbox(label='Hypernetwork Learning rate', placeholder="Hypernetwork Learning rate", value="0.00001", elem_id="train_hypernetwork_learn_rate") - - with FormRow(): - clip_grad_mode = gr.Dropdown(value="disabled", label="Gradient Clipping", choices=["disabled", "value", "norm"]) - clip_grad_value = gr.Textbox(placeholder="Gradient clip value", value="0.1", show_label=False) - - with FormRow(): - batch_size = gr.Number(label='Batch size', value=1, precision=0, elem_id="train_batch_size") - gradient_step = gr.Number(label='Gradient accumulation steps', value=1, precision=0, elem_id="train_gradient_step") - - dataset_directory = gr.Textbox(label='Dataset directory', placeholder="Path to directory with input images", elem_id="train_dataset_directory") - log_directory = gr.Textbox(label='Log directory', placeholder="Path to directory where to write outputs", value="textual_inversion", elem_id="train_log_directory") - - with FormRow(): - template_file = gr.Dropdown(label='Prompt template', value="style_filewords.txt", elem_id="train_template_file", choices=get_textual_inversion_template_names()) - create_refresh_button(template_file, textual_inversion.list_textual_inversion_templates, lambda: {"choices": get_textual_inversion_template_names()}, "refrsh_train_template_file") - - training_width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="train_training_width") - training_height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="train_training_height") - varsize = gr.Checkbox(label="Do not resize images", value=False, elem_id="train_varsize") - steps = gr.Number(label='Max steps', value=100000, precision=0, elem_id="train_steps") - - with FormRow(): - create_image_every = gr.Number(label='Save an image to log directory every N steps, 0 to disable', value=500, precision=0, elem_id="train_create_image_every") - save_embedding_every = gr.Number(label='Save a copy of embedding to log directory every N steps, 0 to disable', value=500, precision=0, elem_id="train_save_embedding_every") - - use_weight = gr.Checkbox(label="Use PNG alpha channel as loss weight", value=False, elem_id="use_weight") - - save_image_with_stored_embedding = gr.Checkbox(label='Save images with embedding in PNG chunks', value=True, elem_id="train_save_image_with_stored_embedding") - preview_from_txt2img = gr.Checkbox(label='Read parameters (prompt, etc...) from txt2img tab when making previews', value=False, elem_id="train_preview_from_txt2img") - - shuffle_tags = gr.Checkbox(label="Shuffle tags by ',' when creating prompts.", value=False, elem_id="train_shuffle_tags") - tag_drop_out = gr.Slider(minimum=0, maximum=1, step=0.1, label="Drop out tags when creating prompts.", value=0, elem_id="train_tag_drop_out") - - latent_sampling_method = gr.Radio(label='Choose latent sampling method', value="once", choices=['once', 'deterministic', 'random'], elem_id="train_latent_sampling_method") - - with gr.Row(): - train_embedding = gr.Button(value="Train Embedding", variant='primary', elem_id="train_train_embedding") - interrupt_training = gr.Button(value="Interrupt", elem_id="train_interrupt_training") - train_hypernetwork = gr.Button(value="Train Hypernetwork", variant='primary', elem_id="train_train_hypernetwork") - - params = script_callbacks.UiTrainTabParams(txt2img_preview_params) - - script_callbacks.ui_train_tabs_callback(params) - - with gr.Column(elem_id='ti_gallery_container'): - ti_output = gr.Text(elem_id="ti_output", value="", show_label=False) - ti_gallery = gr.Gallery(label='Output', show_label=False, elem_id='ti_gallery').style(grid=4) - ti_progress = gr.HTML(elem_id="ti_progress", value="") - ti_outcome = gr.HTML(elem_id="ti_error", value="") - - create_embedding.click( - fn=modules.textual_inversion.ui.create_embedding, - inputs=[ - new_embedding_name, - initialization_text, - nvpt, - overwrite_old_embedding, - ], - outputs=[ - train_embedding_name, - ti_output, - ti_outcome, - ] - ) - - create_hypernetwork.click( - fn=modules.hypernetworks.ui.create_hypernetwork, - inputs=[ - new_hypernetwork_name, - new_hypernetwork_sizes, - overwrite_old_hypernetwork, - new_hypernetwork_layer_structure, - new_hypernetwork_activation_func, - new_hypernetwork_initialization_option, - new_hypernetwork_add_layer_norm, - new_hypernetwork_use_dropout, - new_hypernetwork_dropout_structure - ], - outputs=[ - train_hypernetwork_name, - ti_output, - ti_outcome, - ] - ) - - run_preprocess.click( - fn=wrap_gradio_gpu_call(modules.textual_inversion.ui.preprocess, extra_outputs=[gr.update()]), - _js="start_training_textual_inversion", - inputs=[ - dummy_component, - process_src, - process_dst, - process_width, - process_height, - preprocess_txt_action, - process_flip, - process_split, - process_caption, - process_caption_deepbooru, - process_split_threshold, - process_overlap_ratio, - process_focal_crop, - process_focal_crop_face_weight, - process_focal_crop_entropy_weight, - process_focal_crop_edges_weight, - process_focal_crop_debug, - process_multicrop, - process_multicrop_mindim, - process_multicrop_maxdim, - process_multicrop_minarea, - process_multicrop_maxarea, - process_multicrop_objective, - process_multicrop_threshold, - ], - outputs=[ - ti_output, - ti_outcome, - ], - ) - - train_embedding.click( - fn=wrap_gradio_gpu_call(modules.textual_inversion.ui.train_embedding, extra_outputs=[gr.update()]), - _js="start_training_textual_inversion", - inputs=[ - dummy_component, - train_embedding_name, - embedding_learn_rate, - batch_size, - gradient_step, - dataset_directory, - log_directory, - training_width, - training_height, - varsize, - steps, - clip_grad_mode, - clip_grad_value, - shuffle_tags, - tag_drop_out, - latent_sampling_method, - use_weight, - create_image_every, - save_embedding_every, - template_file, - save_image_with_stored_embedding, - preview_from_txt2img, - *txt2img_preview_params, - ], - outputs=[ - ti_output, - ti_outcome, - ] - ) - - train_hypernetwork.click( - fn=wrap_gradio_gpu_call(modules.hypernetworks.ui.train_hypernetwork, extra_outputs=[gr.update()]), - _js="start_training_textual_inversion", - inputs=[ - dummy_component, - train_hypernetwork_name, - hypernetwork_learn_rate, - batch_size, - gradient_step, - dataset_directory, - log_directory, - training_width, - training_height, - varsize, - steps, - clip_grad_mode, - clip_grad_value, - shuffle_tags, - tag_drop_out, - latent_sampling_method, - use_weight, - create_image_every, - save_embedding_every, - template_file, - preview_from_txt2img, - *txt2img_preview_params, - ], - outputs=[ - ti_output, - ti_outcome, - ] - ) - - interrupt_training.click( - fn=lambda: shared.state.interrupt(), - inputs=[], - outputs=[], - ) - - interrupt_preprocessing.click( - fn=lambda: shared.state.interrupt(), - inputs=[], - outputs=[], - ) - - def create_setting_component(key, is_quicksettings=False): - def fun(): - return opts.data[key] if key in opts.data else opts.data_labels[key].default - - info = opts.data_labels[key] - t = type(info.default) - - args = info.component_args() if callable(info.component_args) else info.component_args - - if info.component is not None: - comp = info.component - elif t == str: - comp = gr.Textbox - elif t == int: - comp = gr.Number - elif t == bool: - comp = gr.Checkbox - else: - raise Exception(f'bad options item type: {str(t)} for key {key}') - - elem_id = "setting_"+key - - if info.refresh is not None: - if is_quicksettings: - res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {})) - create_refresh_button(res, info.refresh, info.component_args, "refresh_" + key) - else: - with FormRow(): - res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {})) - create_refresh_button(res, info.refresh, info.component_args, "refresh_" + key) - else: - res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {})) - - return res - - components = [] - component_dict = {} - shared.settings_components = component_dict - - script_callbacks.ui_settings_callback() - opts.reorder() - - def run_settings(*args): - changed = [] - - for key, value, comp in zip(opts.data_labels.keys(), args, components): - assert comp == dummy_component or opts.same_type(value, opts.data_labels[key].default), f"Bad value for setting {key}: {value}; expecting {type(opts.data_labels[key].default).__name__}" - - for key, value, comp in zip(opts.data_labels.keys(), args, components): - if comp == dummy_component: - continue - - if opts.set(key, value): - changed.append(key) - - try: - opts.save(shared.config_filename) - except RuntimeError: - return opts.dumpjson(), f'{len(changed)} settings changed without save: {", ".join(changed)}.' - return opts.dumpjson(), f'{len(changed)} settings changed{": " if len(changed) > 0 else ""}{", ".join(changed)}.' - - def run_settings_single(value, key): - if not opts.same_type(value, opts.data_labels[key].default): - return gr.update(visible=True), opts.dumpjson() - - if not opts.set(key, value): - return gr.update(value=getattr(opts, key)), opts.dumpjson() - - opts.save(shared.config_filename) - - return get_value_for_setting(key), opts.dumpjson() - - with gr.Blocks(analytics_enabled=False) as settings_interface: - with gr.Row(): - with gr.Column(scale=6): - settings_submit = gr.Button(value="Apply settings", variant='primary', elem_id="settings_submit") - with gr.Column(): - restart_gradio = gr.Button(value='Reload UI', variant='primary', elem_id="settings_restart_gradio") - - result = gr.HTML(elem_id="settings_result") - - quicksettings_names = [x.strip() for x in opts.quicksettings.split(",")] - quicksettings_names = {x: i for i, x in enumerate(quicksettings_names) if x != 'quicksettings'} - - quicksettings_list = [] - - previous_section = None - current_tab = None - current_row = None - with gr.Tabs(elem_id="settings"): - for i, (k, item) in enumerate(opts.data_labels.items()): - section_must_be_skipped = item.section[0] is None - - if previous_section != item.section and not section_must_be_skipped: - elem_id, text = item.section - - if current_tab is not None: - current_row.__exit__() - current_tab.__exit__() - - gr.Group() - current_tab = gr.TabItem(elem_id="settings_{}".format(elem_id), label=text) - current_tab.__enter__() - current_row = gr.Column(variant='compact') - current_row.__enter__() - - previous_section = item.section - - if k in quicksettings_names and not shared.cmd_opts.freeze_settings: - quicksettings_list.append((i, k, item)) - components.append(dummy_component) - elif section_must_be_skipped: - components.append(dummy_component) - else: - component = create_setting_component(k) - component_dict[k] = component - components.append(component) - - if current_tab is not None: - current_row.__exit__() - current_tab.__exit__() - - with gr.TabItem("Actions"): - request_notifications = gr.Button(value='Request browser notifications', elem_id="request_notifications") - download_localization = gr.Button(value='Download localization template', elem_id="download_localization") - reload_script_bodies = gr.Button(value='Reload custom script bodies (No ui updates, No restart)', variant='secondary', elem_id="settings_reload_script_bodies") - - with gr.TabItem("Licenses"): - gr.HTML(shared.html("licenses.html"), elem_id="licenses") - - gr.Button(value="Show all pages", elem_id="settings_show_all_pages") - - request_notifications.click( - fn=lambda: None, - inputs=[], - outputs=[], - _js='function(){}' - ) - - download_localization.click( - fn=lambda: None, - inputs=[], - outputs=[], - _js='download_localization' - ) - - def reload_scripts(): - modules.scripts.reload_script_body_only() - reload_javascript() # need to refresh the html page - - reload_script_bodies.click( - fn=reload_scripts, - inputs=[], - outputs=[] - ) - - def request_restart(): - shared.state.interrupt() - shared.state.need_restart = True - - restart_gradio.click( - fn=request_restart, - _js='restart_reload', - inputs=[], - outputs=[], - ) - - interfaces = [ - (txt2img_interface, "txt2img", "txt2img"), - (img2img_interface, "img2img", "img2img"), - (extras_interface, "Extras", "extras"), - (pnginfo_interface, "PNG Info", "pnginfo"), - (modelmerger_interface, "Checkpoint Merger", "modelmerger"), - (train_interface, "Train", "ti"), - ] - - css = "" - - for cssfile in modules.scripts.list_files_with_name("style.css"): - if not os.path.isfile(cssfile): - continue - - with open(cssfile, "r", encoding="utf8") as file: - css += file.read() + "\n" - - if os.path.exists(os.path.join(data_path, "user.css")): - with open(os.path.join(data_path, "user.css"), "r", encoding="utf8") as file: - css += file.read() + "\n" - - if not cmd_opts.no_progressbar_hiding: - css += css_hide_progressbar - - interfaces += script_callbacks.ui_tabs_callback() - interfaces += [(settings_interface, "Settings", "settings")] - - extensions_interface = ui_extensions.create_ui() - interfaces += [(extensions_interface, "Extensions", "extensions")] - - with gr.Blocks(css=css, analytics_enabled=False, title="Stable Diffusion") as demo: - with gr.Row(elem_id="quicksettings", variant="compact"): - for i, k, item in sorted(quicksettings_list, key=lambda x: quicksettings_names.get(x[1], x[0])): - component = create_setting_component(k, is_quicksettings=True) - component_dict[k] = component - - parameters_copypaste.connect_paste_params_buttons() - - with gr.Tabs(elem_id="tabs") as tabs: - for interface, label, ifid in interfaces: - with gr.TabItem(label, id=ifid, elem_id='tab_' + ifid): - interface.render() - - if os.path.exists(os.path.join(script_path, "notification.mp3")): - audio_notification = gr.Audio(interactive=False, value=os.path.join(script_path, "notification.mp3"), elem_id="audio_notification", visible=False) - - footer = shared.html("footer.html") - footer = footer.format(versions=versions_html()) - gr.HTML(footer, elem_id="footer") - - text_settings = gr.Textbox(elem_id="settings_json", value=lambda: opts.dumpjson(), visible=False) - settings_submit.click( - fn=wrap_gradio_call(run_settings, extra_outputs=[gr.update()]), - inputs=components, - outputs=[text_settings, result], - ) - - for i, k, item in quicksettings_list: - component = component_dict[k] - - component.change( - fn=lambda value, k=k: run_settings_single(value, key=k), - inputs=[component], - outputs=[component, text_settings], - ) - - text_settings.change( - fn=lambda: gr.update(visible=shared.sd_model and shared.sd_model.cond_stage_key == "edit"), - inputs=[], - outputs=[image_cfg_scale], - ) - - button_set_checkpoint = gr.Button('Change checkpoint', elem_id='change_checkpoint', visible=False) - button_set_checkpoint.click( - fn=lambda value, _: run_settings_single(value, key='sd_model_checkpoint'), - _js="function(v){ var res = desiredCheckpointName; desiredCheckpointName = ''; return [res || v, null]; }", - inputs=[component_dict['sd_model_checkpoint'], dummy_component], - outputs=[component_dict['sd_model_checkpoint'], text_settings], - ) - - component_keys = [k for k in opts.data_labels.keys() if k in component_dict] - - def get_settings_values(): - return [get_value_for_setting(key) for key in component_keys] - - demo.load( - fn=get_settings_values, - inputs=[], - outputs=[component_dict[k] for k in component_keys], - ) - - def modelmerger(*args): - try: - results = modules.extras.run_modelmerger(*args) - except Exception as e: - print("Error loading/saving model file:", file=sys.stderr) - print(traceback.format_exc(), file=sys.stderr) - modules.sd_models.list_models() # to remove the potentially missing models from the list - return [*[gr.Dropdown.update(choices=modules.sd_models.checkpoint_tiles()) for _ in range(4)], f"Error merging checkpoints: {e}"] - return results - - modelmerger_merge.click(fn=lambda: '', inputs=[], outputs=[modelmerger_result]) - modelmerger_merge.click( - fn=wrap_gradio_gpu_call(modelmerger, extra_outputs=lambda: [gr.update() for _ in range(4)]), - _js='modelmerger', - inputs=[ - dummy_component, - primary_model_name, - secondary_model_name, - tertiary_model_name, - interp_method, - interp_amount, - save_as_half, - custom_name, - checkpoint_format, - config_source, - bake_in_vae, - discard_weights, - ], - outputs=[ - primary_model_name, - secondary_model_name, - tertiary_model_name, - component_dict['sd_model_checkpoint'], - modelmerger_result, - ] - ) - - ui_config_file = cmd_opts.ui_config_file - ui_settings = {} - settings_count = len(ui_settings) - error_loading = False - - try: - if os.path.exists(ui_config_file): - with open(ui_config_file, "r", encoding="utf8") as file: - ui_settings = json.load(file) - except Exception: - error_loading = True - print("Error loading settings:", file=sys.stderr) - print(traceback.format_exc(), file=sys.stderr) - - def loadsave(path, x): - def apply_field(obj, field, condition=None, init_field=None): - key = path + "/" + field - - if getattr(obj, 'custom_script_source', None) is not None: - key = 'customscript/' + obj.custom_script_source + '/' + key - - if getattr(obj, 'do_not_save_to_config', False): - return - - saved_value = ui_settings.get(key, None) - if saved_value is None: - ui_settings[key] = getattr(obj, field) - elif condition and not condition(saved_value): - pass - - # this warning is generally not useful; - # print(f'Warning: Bad ui setting value: {key}: {saved_value}; Default value "{getattr(obj, field)}" will be used instead.') - else: - setattr(obj, field, saved_value) - if init_field is not None: - init_field(saved_value) - - if type(x) in [gr.Slider, gr.Radio, gr.Checkbox, gr.Textbox, gr.Number, gr.Dropdown] and x.visible: - apply_field(x, 'visible') - - if type(x) == gr.Slider: - apply_field(x, 'value') - apply_field(x, 'minimum') - apply_field(x, 'maximum') - apply_field(x, 'step') - - if type(x) == gr.Radio: - apply_field(x, 'value', lambda val: val in x.choices) - - if type(x) == gr.Checkbox: - apply_field(x, 'value') - - if type(x) == gr.Textbox: - apply_field(x, 'value') - - if type(x) == gr.Number: - apply_field(x, 'value') - - if type(x) == gr.Dropdown: - def check_dropdown(val): - if getattr(x, 'multiselect', False): - return all([value in x.choices for value in val]) - else: - return val in x.choices - - apply_field(x, 'value', check_dropdown, getattr(x, 'init_field', None)) - - visit(txt2img_interface, loadsave, "txt2img") - visit(img2img_interface, loadsave, "img2img") - visit(extras_interface, loadsave, "extras") - visit(modelmerger_interface, loadsave, "modelmerger") - visit(train_interface, loadsave, "train") - - if not error_loading and (not os.path.exists(ui_config_file) or settings_count != len(ui_settings)): - with open(ui_config_file, "w", encoding="utf8") as file: - json.dump(ui_settings, file, indent=4) - - # Required as a workaround for change() event not triggering when loading values from ui-config.json - interp_description.value = update_interp_description(interp_method.value) - - return demo - - -def reload_javascript(): - head = f'\n' - - inline = f"{localization.localization_js(shared.opts.localization)};" - if cmd_opts.theme is not None: - inline += f"set_theme('{cmd_opts.theme}');" - - for script in modules.scripts.list_scripts("javascript", ".js"): - head += f'\n' - - head += f'\n' - - def template_response(*args, **kwargs): - res = shared.GradioTemplateResponseOriginal(*args, **kwargs) - res.body = res.body.replace(b'', f'{head}'.encode("utf8")) - res.init_headers() - return res - - gradio.routes.templates.TemplateResponse = template_response - - -if not hasattr(shared, 'GradioTemplateResponseOriginal'): - shared.GradioTemplateResponseOriginal = gradio.routes.templates.TemplateResponse - - -def versions_html(): - import torch - import launch - - python_version = ".".join([str(x) for x in sys.version_info[0:3]]) - commit = launch.commit_hash() - short_commit = commit[0:8] - - if shared.xformers_available: - import xformers - xformers_version = xformers.__version__ - else: - xformers_version = "N/A" - - return f""" -python: {python_version} - •  -torch: {getattr(torch, '__long_version__',torch.__version__)} - •  -xformers: {xformers_version} - •  -gradio: {gr.__version__} - •  -commit: {short_commit} - •  -checkpoint: N/A -""" diff --git a/spaces/aodianyun/stable-diffusion-webui/test/basic_features/utils_test.py b/spaces/aodianyun/stable-diffusion-webui/test/basic_features/utils_test.py deleted file mode 100644 index 0bfc28a0d30c070c292ff8154e9b93a74abecb85..0000000000000000000000000000000000000000 --- a/spaces/aodianyun/stable-diffusion-webui/test/basic_features/utils_test.py +++ /dev/null @@ -1,62 +0,0 @@ -import unittest -import requests - -class UtilsTests(unittest.TestCase): - def setUp(self): - self.url_options = "http://localhost:7860/sdapi/v1/options" - self.url_cmd_flags = "http://localhost:7860/sdapi/v1/cmd-flags" - self.url_samplers = "http://localhost:7860/sdapi/v1/samplers" - self.url_upscalers = "http://localhost:7860/sdapi/v1/upscalers" - self.url_sd_models = "http://localhost:7860/sdapi/v1/sd-models" - self.url_hypernetworks = "http://localhost:7860/sdapi/v1/hypernetworks" - self.url_face_restorers = "http://localhost:7860/sdapi/v1/face-restorers" - self.url_realesrgan_models = "http://localhost:7860/sdapi/v1/realesrgan-models" - self.url_prompt_styles = "http://localhost:7860/sdapi/v1/prompt-styles" - self.url_embeddings = "http://localhost:7860/sdapi/v1/embeddings" - - def test_options_get(self): - self.assertEqual(requests.get(self.url_options).status_code, 200) - - def test_options_write(self): - response = requests.get(self.url_options) - self.assertEqual(response.status_code, 200) - - pre_value = response.json()["send_seed"] - - self.assertEqual(requests.post(self.url_options, json={"send_seed":not pre_value}).status_code, 200) - - response = requests.get(self.url_options) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["send_seed"], not pre_value) - - requests.post(self.url_options, json={"send_seed": pre_value}) - - def test_cmd_flags(self): - self.assertEqual(requests.get(self.url_cmd_flags).status_code, 200) - - def test_samplers(self): - self.assertEqual(requests.get(self.url_samplers).status_code, 200) - - def test_upscalers(self): - self.assertEqual(requests.get(self.url_upscalers).status_code, 200) - - def test_sd_models(self): - self.assertEqual(requests.get(self.url_sd_models).status_code, 200) - - def test_hypernetworks(self): - self.assertEqual(requests.get(self.url_hypernetworks).status_code, 200) - - def test_face_restorers(self): - self.assertEqual(requests.get(self.url_face_restorers).status_code, 200) - - def test_realesrgan_models(self): - self.assertEqual(requests.get(self.url_realesrgan_models).status_code, 200) - - def test_prompt_styles(self): - self.assertEqual(requests.get(self.url_prompt_styles).status_code, 200) - - def test_embeddings(self): - self.assertEqual(requests.get(self.url_embeddings).status_code, 200) - -if __name__ == "__main__": - unittest.main() diff --git a/spaces/applsisujsus/qiangbing/Dockerfile b/spaces/applsisujsus/qiangbing/Dockerfile deleted file mode 100644 index 139c333a3bba5ac3680d42b6f356824207f05255..0000000000000000000000000000000000000000 --- a/spaces/applsisujsus/qiangbing/Dockerfile +++ /dev/null @@ -1,33 +0,0 @@ -# Build Stage -# 使用 golang:alpine 作为构建阶段的基础镜像 -FROM golang:alpine AS builder - -# 添加 git,并且清除缓存🧹 -RUN apk --no-cache add git && \ - git clone https://github.com/Harry-zklcdc/go-proxy-bingai.git /workspace/app && \ - apk del git - -# 设置工作目录 -WORKDIR /workspace/app - -# 编译 go 项目 -RUN go build -ldflags="-s -w" -tags netgo -trimpath -o go-proxy-bingai main.go - -# Runtime Stage -# 使用轻量级的 alpine 镜像🪞 -FROM alpine - -# 设置工作目录💼 -WORKDIR /workspace/app - -# 从构建阶段复制编译后的二进制文件👔 -COPY --from=builder /workspace/app/go-proxy-bingai . - -# (可选)设置环境变量✍️ -ENV Go_Proxy_BingAI_USER_TOKEN_1="G4hJ9k544565uhjjhjlkjh6356223p3EaYc0FvIjHmLzXeRfAq" - -# 端口 -EXPOSE 8080 - -# 容器运行✅ -CMD ["/workspace/app/go-proxy-bingai"] diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/PIL/features.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/PIL/features.py deleted file mode 100644 index 3838568f3a629d022a831eab376db51baeec445c..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/PIL/features.py +++ /dev/null @@ -1,320 +0,0 @@ -import collections -import os -import sys -import warnings - -import PIL - -from . import Image - -modules = { - "pil": ("PIL._imaging", "PILLOW_VERSION"), - "tkinter": ("PIL._tkinter_finder", "tk_version"), - "freetype2": ("PIL._imagingft", "freetype2_version"), - "littlecms2": ("PIL._imagingcms", "littlecms_version"), - "webp": ("PIL._webp", "webpdecoder_version"), -} - - -def check_module(feature): - """ - Checks if a module is available. - - :param feature: The module to check for. - :returns: ``True`` if available, ``False`` otherwise. - :raises ValueError: If the module is not defined in this version of Pillow. - """ - if not (feature in modules): - raise ValueError(f"Unknown module {feature}") - - module, ver = modules[feature] - - try: - __import__(module) - return True - except ImportError: - return False - - -def version_module(feature): - """ - :param feature: The module to check for. - :returns: - The loaded version number as a string, or ``None`` if unknown or not available. - :raises ValueError: If the module is not defined in this version of Pillow. - """ - if not check_module(feature): - return None - - module, ver = modules[feature] - - if ver is None: - return None - - return getattr(__import__(module, fromlist=[ver]), ver) - - -def get_supported_modules(): - """ - :returns: A list of all supported modules. - """ - return [f for f in modules if check_module(f)] - - -codecs = { - "jpg": ("jpeg", "jpeglib"), - "jpg_2000": ("jpeg2k", "jp2klib"), - "zlib": ("zip", "zlib"), - "libtiff": ("libtiff", "libtiff"), -} - - -def check_codec(feature): - """ - Checks if a codec is available. - - :param feature: The codec to check for. - :returns: ``True`` if available, ``False`` otherwise. - :raises ValueError: If the codec is not defined in this version of Pillow. - """ - if feature not in codecs: - raise ValueError(f"Unknown codec {feature}") - - codec, lib = codecs[feature] - - return codec + "_encoder" in dir(Image.core) - - -def version_codec(feature): - """ - :param feature: The codec to check for. - :returns: - The version number as a string, or ``None`` if not available. - Checked at compile time for ``jpg``, run-time otherwise. - :raises ValueError: If the codec is not defined in this version of Pillow. - """ - if not check_codec(feature): - return None - - codec, lib = codecs[feature] - - version = getattr(Image.core, lib + "_version") - - if feature == "libtiff": - return version.split("\n")[0].split("Version ")[1] - - return version - - -def get_supported_codecs(): - """ - :returns: A list of all supported codecs. - """ - return [f for f in codecs if check_codec(f)] - - -features = { - "webp_anim": ("PIL._webp", "HAVE_WEBPANIM", None), - "webp_mux": ("PIL._webp", "HAVE_WEBPMUX", None), - "transp_webp": ("PIL._webp", "HAVE_TRANSPARENCY", None), - "raqm": ("PIL._imagingft", "HAVE_RAQM", "raqm_version"), - "fribidi": ("PIL._imagingft", "HAVE_FRIBIDI", "fribidi_version"), - "harfbuzz": ("PIL._imagingft", "HAVE_HARFBUZZ", "harfbuzz_version"), - "libjpeg_turbo": ("PIL._imaging", "HAVE_LIBJPEGTURBO", "libjpeg_turbo_version"), - "libimagequant": ("PIL._imaging", "HAVE_LIBIMAGEQUANT", "imagequant_version"), - "xcb": ("PIL._imaging", "HAVE_XCB", None), -} - - -def check_feature(feature): - """ - Checks if a feature is available. - - :param feature: The feature to check for. - :returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown. - :raises ValueError: If the feature is not defined in this version of Pillow. - """ - if feature not in features: - raise ValueError(f"Unknown feature {feature}") - - module, flag, ver = features[feature] - - try: - imported_module = __import__(module, fromlist=["PIL"]) - return getattr(imported_module, flag) - except ImportError: - return None - - -def version_feature(feature): - """ - :param feature: The feature to check for. - :returns: The version number as a string, or ``None`` if not available. - :raises ValueError: If the feature is not defined in this version of Pillow. - """ - if not check_feature(feature): - return None - - module, flag, ver = features[feature] - - if ver is None: - return None - - return getattr(__import__(module, fromlist=[ver]), ver) - - -def get_supported_features(): - """ - :returns: A list of all supported features. - """ - return [f for f in features if check_feature(f)] - - -def check(feature): - """ - :param feature: A module, codec, or feature name. - :returns: - ``True`` if the module, codec, or feature is available, - ``False`` or ``None`` otherwise. - """ - - if feature in modules: - return check_module(feature) - if feature in codecs: - return check_codec(feature) - if feature in features: - return check_feature(feature) - warnings.warn(f"Unknown feature '{feature}'.", stacklevel=2) - return False - - -def version(feature): - """ - :param feature: - The module, codec, or feature to check for. - :returns: - The version number as a string, or ``None`` if unknown or not available. - """ - if feature in modules: - return version_module(feature) - if feature in codecs: - return version_codec(feature) - if feature in features: - return version_feature(feature) - return None - - -def get_supported(): - """ - :returns: A list of all supported modules, features, and codecs. - """ - - ret = get_supported_modules() - ret.extend(get_supported_features()) - ret.extend(get_supported_codecs()) - return ret - - -def pilinfo(out=None, supported_formats=True): - """ - Prints information about this installation of Pillow. - This function can be called with ``python3 -m PIL``. - - :param out: - The output stream to print to. Defaults to ``sys.stdout`` if ``None``. - :param supported_formats: - If ``True``, a list of all supported image file formats will be printed. - """ - - if out is None: - out = sys.stdout - - Image.init() - - print("-" * 68, file=out) - print(f"Pillow {PIL.__version__}", file=out) - py_version = sys.version.splitlines() - print(f"Python {py_version[0].strip()}", file=out) - for py_version in py_version[1:]: - print(f" {py_version.strip()}", file=out) - print("-" * 68, file=out) - print( - f"Python modules loaded from {os.path.dirname(Image.__file__)}", - file=out, - ) - print( - f"Binary modules loaded from {os.path.dirname(Image.core.__file__)}", - file=out, - ) - print("-" * 68, file=out) - - for name, feature in [ - ("pil", "PIL CORE"), - ("tkinter", "TKINTER"), - ("freetype2", "FREETYPE2"), - ("littlecms2", "LITTLECMS2"), - ("webp", "WEBP"), - ("transp_webp", "WEBP Transparency"), - ("webp_mux", "WEBPMUX"), - ("webp_anim", "WEBP Animation"), - ("jpg", "JPEG"), - ("jpg_2000", "OPENJPEG (JPEG2000)"), - ("zlib", "ZLIB (PNG/ZIP)"), - ("libtiff", "LIBTIFF"), - ("raqm", "RAQM (Bidirectional Text)"), - ("libimagequant", "LIBIMAGEQUANT (Quantization method)"), - ("xcb", "XCB (X protocol)"), - ]: - if check(name): - if name == "jpg" and check_feature("libjpeg_turbo"): - v = "libjpeg-turbo " + version_feature("libjpeg_turbo") - else: - v = version(name) - if v is not None: - version_static = name in ("pil", "jpg") - if name == "littlecms2": - # this check is also in src/_imagingcms.c:setup_module() - version_static = tuple(int(x) for x in v.split(".")) < (2, 7) - t = "compiled for" if version_static else "loaded" - if name == "raqm": - for f in ("fribidi", "harfbuzz"): - v2 = version_feature(f) - if v2 is not None: - v += f", {f} {v2}" - print("---", feature, "support ok,", t, v, file=out) - else: - print("---", feature, "support ok", file=out) - else: - print("***", feature, "support not installed", file=out) - print("-" * 68, file=out) - - if supported_formats: - extensions = collections.defaultdict(list) - for ext, i in Image.EXTENSION.items(): - extensions[i].append(ext) - - for i in sorted(Image.ID): - line = f"{i}" - if i in Image.MIME: - line = f"{line} {Image.MIME[i]}" - print(line, file=out) - - if i in extensions: - print( - "Extensions: {}".format(", ".join(sorted(extensions[i]))), file=out - ) - - features = [] - if i in Image.OPEN: - features.append("open") - if i in Image.SAVE: - features.append("save") - if i in Image.SAVE_ALL: - features.append("save_all") - if i in Image.DECODERS: - features.append("decode") - if i in Image.ENCODERS: - features.append("encode") - - print("Features: {}".format(", ".join(features)), file=out) - print("-" * 68, file=out) diff --git a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/candlestick_chart.py b/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/candlestick_chart.py deleted file mode 100644 index 1997cda3d280defeb11d45c8e7f1f3051dc7bc43..0000000000000000000000000000000000000000 --- a/spaces/arxify/RVC-beta-v2-0618/runtime/Lib/site-packages/altair/examples/candlestick_chart.py +++ /dev/null @@ -1,44 +0,0 @@ -""" -Candlestick Chart -================= -A candlestick chart inspired from `Protovis `_. -This example shows the performance of the Chicago Board Options Exchange `Volatility Index `_ (VIX) -in the summer of 2009. The thick bar represents the opening and closing prices, -while the thin bar shows intraday high and low prices; if the index closed higher on a given day, the bars are colored green rather than red. -""" -# category: other charts -import altair as alt -from vega_datasets import data - -source = data.ohlc() - -open_close_color = alt.condition("datum.open <= datum.close", - alt.value("#06982d"), - alt.value("#ae1325")) - -base = alt.Chart(source).encode( - alt.X('date:T', - axis=alt.Axis( - format='%m/%d', - labelAngle=-45, - title='Date in 2009' - ) - ), - color=open_close_color -) - -rule = base.mark_rule().encode( - alt.Y( - 'low:Q', - title='Price', - scale=alt.Scale(zero=False), - ), - alt.Y2('high:Q') -) - -bar = base.mark_bar().encode( - alt.Y('open:Q'), - alt.Y2('close:Q') -) - -rule + bar \ No newline at end of file diff --git a/spaces/ashwin3005/first-space/README.md b/spaces/ashwin3005/first-space/README.md deleted file mode 100644 index fcb5456afbad960dda8368a41ed3158b6340e425..0000000000000000000000000000000000000000 --- a/spaces/ashwin3005/first-space/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Cat or Dog -emoji: 🐶 -colorFrom: pink -colorTo: purple -sdk: gradio -sdk_version: 3.38.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/aslasdlkj/Podfusion/hacks/pip-install.sh b/spaces/aslasdlkj/Podfusion/hacks/pip-install.sh deleted file mode 100644 index 7050a432219ffe58cf718abec7960d91cbc2aff6..0000000000000000000000000000000000000000 --- a/spaces/aslasdlkj/Podfusion/hacks/pip-install.sh +++ /dev/null @@ -1 +0,0 @@ -PIP_CACHE_DIR=/notebooks/.cache/pip pip install -r /notebooks/stablepod/requirements.txt \ No newline at end of file diff --git a/spaces/awacke1/CardWriterPro/combined.md b/spaces/awacke1/CardWriterPro/combined.md deleted file mode 100644 index 900d1889e4b08f4dfe56ffbe9704f107807141ff..0000000000000000000000000000000000000000 --- a/spaces/awacke1/CardWriterPro/combined.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -language: -- es -license: apache-2.0 -library_name: keras -tags: -- autogenerated-modelcard ---- - -# MyModelName - -## Table of Contents -- [MyModelName](#-model_id--defaultmymodelname-true) - - [Table of Contents](#table-of-contents) - - [Model Details](#model-details) - - [How to Get Started with the Model](#how-to-get-started-with-the-model) - - [Uses](#uses) - - [Direct Use](#direct-use) - - [Downstream Use](#downstream-use) - - [Misuse and Out-of-scope Use](#misuse-and-out-of-scope-use) - - [Limitations and Biases](#limitations-and-biases) - - [Training](#training) - - [Training Data](#training-data) - - [Training Procedure](#training-procedure) - - [Evaluation Results](#evaluation-results) - - [Environmental Impact](#environmental-impact) - - [Citation Information](#citation-information) - - - -## Model Details - - - -Some cool model... - -- Developed by: -- Language(s): -- License: This model is licensed under the apache-2.0 license -- Resources for more information: - - - - - - -## How to Get Started with the Model - -Use the code below to get started with the model. - -```python -# A nice code snippet here that describes how to use the model... -``` - - - - -## Uses - -#### Direct Use - - - -[More Information Needed] - -#### Downstream Use - - - -[More Information Needed] - -#### Misuse and Out-of-scope Use - - - -[More Information Needed] - - - - -## Limitations and Biases - - - -**CONTENT WARNING: Readers should be aware this section contains content that is disturbing, offensive, and can propogate historical and current stereotypes.** - -[More Information Needed] - - - - - -## Training - -#### Training Data - - - - -See the data card for additional information. - -#### Training Procedure - - - -[More Information Needed] - - - - -## Evaluation Results - - - -[More Information Needed] - - - - -## Environmental Impact - - - -You can estimate carbon emissions using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700) - -- **Hardware Type:** -- **Hours used:** -- **Cloud Provider:** -- **Compute Region:** -- **Carbon Emitted:** - - - - - -## Citation Information - -```bibtex - -``` - \ No newline at end of file diff --git a/spaces/awacke1/HL-V2.x-Transformer-Parser/app.py b/spaces/awacke1/HL-V2.x-Transformer-Parser/app.py deleted file mode 100644 index 1ea825941a1c4d56612e2e91d7cb15a968bae5e1..0000000000000000000000000000000000000000 --- a/spaces/awacke1/HL-V2.x-Transformer-Parser/app.py +++ /dev/null @@ -1,982 +0,0 @@ -import streamlit as st -import hl7 -import definitions -from enum import Enum - -class AdtEvents(Enum): - """ADT events for MSH segment""" - Patient_Admit = 'A01' - Patient_Transfer = 'A02' - Patient_Discharge = 'A03' - Patient_Registration = 'A04' - Patient_Pre_Admission = 'A05' - Patient_Information_Update = 'A08' - Cancel_Patient_Admit = 'A11' - Cancel_Patient_Transfer = 'A12' - Cancel_Patient_Discharge = 'A13' - Pending_Admit = 'A14' - Pending_Transfer = 'A15' - Pending_Discharge = 'A16' - - def is_match(self, event) -> bool: - return self.value == event - - @staticmethod - def get_label(event_type: str) -> str: - try: - enum_val = AdtEvents(event_type) - label = enum_val.name.replace('_', ' ') - except IndexError: - label = 'Unknown {}'.format(event_type) - return label - - -class DiagnosisType(Enum): - """Diagnosis type for DG1 segment""" - A = "Admitting" - AD = 'admitting diagnosis' - BD = 'treating diagnosis' - ED = 'referral diagnosis' - EL = 'discharge/transfer diagnosis' - F = "Final" - ND = 'diagnosis' - NO = 'diagnosis operation' - NU = 'follow-up diagnosis that has justified the incapacity to work' - UD = 'referral diagnosis' - VO = 'preoperative diagnosis' - W = 'Waiting' - ZD = 'ZD' - - -class PatientClass(Enum): - E = 'EMERGENCY' - I = 'INPATIENT' - O = 'OUTPATIENT' - P = 'PREADMIT' - R = 'RECURRING PATIENT' - B = 'OBSTETRICS' - C = 'COMMERCIAL ACCOUNT' - N = 'NOT APPLICABLE' - U = 'UNKNOWN' - NO_MATCH = 'UNKNOWN' - - -class CleanPatientClass(Enum): - ER = 'E' - IP = 'I' - - -class PatientClassText(Enum): - EMERGENCY = 'E' - INPATIENT = 'I' - OUTPATIENT = 'O' - PREADMIT = 'P' - RECURRING_PATIENT = 'R' - OBSTETRICS = 'B' - COMMERCIAL_ACCOUNT = 'C' - NOT_APPLICABLE = 'N' - UNKNOWN = 'U' - - -class AdmitSource(Enum): - Physician_Referral = '1' - PR = '1' - Clinic_Referral = '2' - HMO_Referral = '3' - HMO = '3' - Transfer_From_Hospital = '4' - Transfer_From_Skilled_Nursing_Facility = '5' - SNF = '5' - Transfer_From_Another_Health_Care_Facility = '6' - Emergency_Room = '7' - ER = '7' - Court_or_Law_Enforcement = '8' - Information_Not_Available = '9' - Transfer_From_Critical_Access_Hospital = 'A' - Transfer_From_Another_Home_Health_Agency = 'B' - Readmission_to_Same_Home_Health_Agency = 'C' - Transfer_from_Hospital_Inpatient_In_Same_Facility = 'D' - - @staticmethod - def get_value(attribute: str) -> str: - try: - return AdmitSource[attribute].value - except KeyError: - hl7tools_logger.warning("No match found for Admit Source '{}', returning 0.".format(attribute)) - return '0' - - -class DiagnosisPriority(Enum): - """Diagnosis priority for DG1 segment""" - DP_1 = '1 The primary diagnosis' - DP_1_1 = '1.1 main diagnosis (primary)' - DP_1_2 = '1.2 main diagnosis (secondary)' - - -class MshSegment(Enum): - """Message Header""" - Sending_Application_Name = 'MSH{}.F3.R1.C1' - Sending_Application_Universal_ID = 'MSH{}.F3.R1.C2' - Sending_Application_Universal_ID_Type = 'MSH{}.F3.R1.C3' - Sending_Facility_Name = 'MSH{}.F4.R1.C1' - Sending_Facility_Universal_ID = 'MSH{}.F4.R1.C2' - Sending_Facility_Universal_ID_Type = 'MSH{}.F4.R1.C3' - Receiving_Application_Name = 'MSH{}.F5.R1.C1' - Receiving_Application_Universal_ID = 'MSH{}.F5.R1.C2' - Receiving_Application_Universal_ID_Type = 'MSH{}.F5.R1.C3' - Receiving_Facility_Name = 'MSH{}.F6.R1.C1' - Receiving_Facility_Universal_ID = 'MSH{}.F6.R1.C2' - Receiving_Facility_Universal_ID_Type = 'MSH{}.F6.R1.C3' - Msg_Timestamp = 'MSH{}.F7.R1.C1' - Security = 'MSH{}.F8' - Msg_Type = 'MSH{}.F9.R1.C1' - Msg_Trigger_Event = 'MSH{}.F9.R1.C2' - Msg_Structure_ID = 'MSH{}.F9.R1.C3' - Msg_control_ID = 'MSH{}.F10.R1.C1' - Processing_ID = 'MSH{}.F11.R1.C1' - Processing_Mode_ID = 'MSH{}.F11.R1.C2' - Version_ID = 'MSH{}.F12.R1.C1' - Version_Internationalization_Code = 'MSH{}.F12.R1.C2' - Version_Internationalization_Version = 'MSH{}.F12.R1.C3' - Sequence_Number = 'MSH{}.F13' - Accept_Ack_Type = 'MSH{}.F15' - Application_Ack_Type = 'MSH{}.F16' - Country_Code = 'MSH{}.F17' - Character_Set = 'MSH{}.F18' - ODX_Id = 'MSH{}.F21' - - @staticmethod - def get_segment_name() -> str: - return 'MSH' - - @staticmethod - def get_segment_title() -> str: - return 'Message Header' - - -class EvnSegment(Enum): - """Event""" - Event_Type_Code = 'EVN{}.F1' - Recorded_Date_Time = 'EVN{}.F2.R1.C1' - Recorded_Date_Time_Degree_of_Precision = 'EVN{}.F2.R1.C2' - Date_Time_Planned_Event_Time = 'EVN{}.F3.R1.C1' - Date_Time_Planned_Degree_of_Precision = 'EVN{}.F3.R1.C2' - Event_Reason_Code = 'EVN{}.F4' - Operator_ID_Number = 'EVN{}.F5.R1.C1' - Operator_ID_Family_Name_Surname = 'EVN{}.F5.R1.C2.S1' - Operator_ID_Family_Name_Own_Surname_Prefix = 'EVN{}.F5.R1.C2.S2' - Operator_ID_Given_Name = 'EVN{}.F5.R1.C3' - Operator_ID_Middle_Initial = 'EVN{}.F5.R1.C4' - Operator_ID_Suffix = 'EVN{}.F5.R1.C5' - Operator_ID_Prefix = 'EVN{}.F5.R1.C6' - Operator_ID_Degree = 'EVN{}.F5.R1.C7' - Operator_ID_Source_Table = 'EVN{}.F5.R1.C8' - Operator_ID_Assigning_Authority = 'EVN{}.F5.R1.C9' - Operator_ID_Name_Type_Code = 'EVN{}.F5.R1.C10' - Operator_ID_Identifier_Check_Digit = 'EVN{}.F5.R1.C11' - Operator_ID_Check_Digit_Scheme = 'EVN{}.F5.R1.C12' - Operator_ID_Identifier_Type_Code = 'EVN{}.F5.R1.C13' - Operator_ID_Assigning_Facility = 'EVN{}.F5.R1.C14' - Operator_ID_Name_Representation_Code = 'EVN{}.F5.R1.C15' - Operator_ID_Name_Context = 'EVN{}.F5.R1.C16' - Operator_ID_Name_Validity_Range = 'EVN{}.F5.R1.C17' - Operator_ID_Name_Assembly_Order = 'EVN{}.F5.R1.C18' - Operator_ID_Effective_Date = 'EVN{}.F5.R1.C19' - Operator_ID_Expiration_Date = 'EVN{}.F5.R1.C20' - Operator_ID_Professional_Suffix = 'EVN{}.F5.R1.C21' - Operator_ID_Assigning_Jurisdiction = 'EVN{}.F5.R1.C22' - Operator_ID_Assigning_Agency_or_Department = 'EVN{}.F5.R1.C23' - Event_Occurred_Time = 'EVN{}.F6.R1.C1' - Event_Occurred_Degree_of_Precision = 'EVN{}.F6.R1.C2' - Event_Facility_Namespace_ID = 'EVN{}.F7.R1.C1' - Event_Facility_Universal_ID = 'EVN{}.F7.R1.C2' - Event_Facility_Universal_ID_Type = 'EVN{}.F7.R1.C3' - - @staticmethod - def get_segment_name() -> str: - return 'EVN' - - @staticmethod - def get_segment_title() -> str: - return 'Event' - - -class PidSegment(Enum): - """Patient Identification""" - Patient_ID = 'PID{}.F2.R1.C1' - Patient_ID_Assigning_Auth = 'PID{}.F2.R1.C4' - Patient_ID_Type_Code = 'PID{}.F2.R1.C5' - Patient_ID_List = 'PID{}.F3.R1.C1' - Patient_ID_List_Assigning_Auth = 'PID{}.F3.R1.C4' - Patient_ID_List_Type_Code = 'PID{}.F3.R1.C5' - Patient_ID_Alt = 'PID{}.F4.R1.C1' - Patient_ID_Alt_Assigning_Auth = 'PID{}.F4.R1.C4' - Patient_ID_Alt_Type_Code = 'PID{}.F4.R1.C5' - Patient_Last_Name = 'PID{}.F5.R1.C1' - Patient_First_Name = 'PID{}.F5.R1.C2' - Patient_Middle_Name = 'PID{}.F5.R1.C3' - Patient_DOB = 'PID{}.F7' - Patient_Gender = 'PID{}.F8' - Patient_Address_Street_1 = 'PID{}.F11.R1.C1' - Patient_Address_Street_2 = 'PID{}.F11.R1.C2' - Patient_Address_City = 'PID{}.F11.R1.C3' - Patient_Address_State = 'PID{}.F11.R1.C4' - Patient_Address_Zip = 'PID{}.F11.R1.C5' - Patient_Phone_Number_Home = 'PID{}.F13.R1.C1' - Marital_Status = 'PID{}.F16' - Patient_Account_Number = 'PID{}.F18.R1.C1' - Patient_SSN = 'PID{}.F19' - - @staticmethod - def get_segment_name() -> str: - return 'PID' - - @staticmethod - def get_segment_title() -> str: - return 'Patient ID' - - -class Pd1Segment(Enum): - """Patient Additional Demographic""" - Living_Dependency = 'PD1{}.F1' - Living_Arrangement = 'PD1{}.F2' - Patient_Primary_Facility_Org_Name = 'PD1{}.F3.R1.C1' - Patient_Primary_Facility_Org_Name_Type_Code = 'PD1{}.F3.R1.C2' - Patient_Primary_Facility_Org_ID_Number = 'PD1{}.F3.R1.C3' - Patient_Primary_Facility_Org_Check_Digit = 'PD1{}.F3.R1.C4' - Patient_Primary_Facility_Org_Check_Digit_Scheme = 'PD1{}.F3.R1.C5' - Patient_Primary_Facility_Org_Assigning_Authority = 'PD1{}.F3.R1.C6' - Patient_Primary_Facility_Org_Identifier_Type_Code = 'PD1{}.F3.R1.C7' - Patient_Primary_Facility_Org_Assigning_Facility = 'PD1{}.F3.R1.C8' - Patient_Primary_Facility_Org_Name_Representation_Code = 'PD1{}.F3.R1.C9' - Patient_Primary_Facility_Org_Name_Organization_Identifier = 'PD1{}.F3.R1.C10' - Patient_PCP_ID_Number = 'PD1{}.F4.R1.C1' - Patient_PCP_ID_Family_Name = 'PD1{}.F4.R1.C2' - Patient_PCP_ID_Given_Name = 'PD1{}.F4.R1.C3' - Patient_PCP_ID_Middle_Initial = 'PD1{}.F4.R1.C4' - Patient_PCP_ID_Suffix = 'PD1{}.F4.R1.C5' - Patient_PCP_ID_Prefix = 'PD1{}.F4.R1.C6' - Patient_PCP_ID_Degree = 'PD1{}.F4.R1.C7' - Patient_PCP_ID_Source_Table = 'PD1{}.F4.R1.C8' - Patient_PCP_ID_Assigning_Authority = 'PD1{}.F4.R1.C9' - Patient_PCP_ID_Name_Type_Code = 'PD1{}.F4.R1.C10' - Patient_PCP_ID_Identifier_Check_Digit = 'PD1{}.F4.R1.C11' - Patient_PCP_ID_Check_Digit_Scheme = 'PD1{}.F4.R1.C12' - Patient_PCP_ID_Identifier_Type_Code = 'PD1{}.F4.R1.C13' - Patient_PCP_ID_Assigning_Facility = 'PD1{}.F4.R1.C14' - Patient_PCP_ID_Name_Representation_Code = 'PD1{}.F4.R1.C15' - Patient_PCP_ID_Name_Context = 'PD1{}.F4.R1.C16' - Patient_PCP_ID_Name_Validity_Range = 'PD1{}.F4.R1.C17' - Patient_PCP_ID_Name_Assembly_Order = 'PD1{}.F4.R1.C18' - Patient_PCP_ID_Effective_Date = 'PD1{}.F4.R1.C19' - Patient_PCP_ID_Expiration_Date = 'PD1{}.F4.R1.C20' - Patient_PCP_ID_Professional_Suffix = 'PD1{}.F4.R1.C21' - Patient_PCP_ID_Assigning_Jurisdiction = 'PD1{}.F4.R1.C22' - Patient_PCP_ID_Assigning_Agency_or_Dept = 'PD1{}.F4.R1.C23' - Student_Indicator = 'PD1{}.F5' - Handicap = 'PD1{}.F6' - Living_Will_Code = 'PD1{}.F7' - Organ_Donor_Code = 'PD1{}.F8' - Separate_Bill = 'PD1{}.F9' - Duplicate_Patient_ID_Number = 'PD1{}.F10.R1.C1' - Duplicate_Patient_Check_Digit = 'PD1{}.F10.R1.C2' - Duplicate_Patient_Check_Digit_Scheme = 'PD1{}.F10.R1.C3' - Duplicate_Patient_Assigning_Authority = 'PD1{}.F10.R1.C4' - Duplicate_Patient_Identifier_Type_Code = 'PD1{}.F10.R1.C5' - Duplicate_Patient_Assigning_Facility = 'PD1{}.F10.R1.C6' - Duplicate_Patient_Effective_Date = 'PD1{}.F10.R1.C7' - Duplicate_Patient_Expiration_Date = 'PD1{}.F10.R1.C8' - Duplicate_Patient_Assigning_Jurisdiction = 'PD1{}.F10.R1.C9' - Duplicate_Patient_Assigning_Agency_or_Dept = 'PD1{}.F10.R1.C10' - Publicity_Code = 'PD1{}.F11' - Protection_Indicator = 'PD1{}.F12' - Protection_Indicator_Effective_Date = 'PD1{}.F13' - Place_of_Worship_Organization_Name = 'PD1{}.F14.R1.C1' - Place_of_Worship_Organization_Name_Type_Code = 'PD1{}.F14.R1.C2' - Place_of_Worship_ID_Number = 'PD1{}.F14.R1.C3' - Place_of_Worship_Check_Digit = 'PD1{}.F14.R1.C4' - Place_of_Worship_Check_Digit_Scheme = 'PD1{}.F14.R1.C5' - Place_of_Worship_Assigning_Authority = 'PD1{}.F14.R1.C6' - Place_of_Worship_Identifier_Type_Code = 'PD1{}.F14.R1.C7' - Place_of_Worship_Assigning_Facility = 'PD1{}.F14.R1.C8' - Place_of_Worship_Name_Representation_Code = 'PD1{}.F14.R1.C9' - Place_of_Worship_Organization_Identifier = 'PD1{}.F14.R1.C10' - Advance_Directive_Code_Identifier = 'PD1{}.F15.R1.C1' - Advance_Directive_Code_Text = 'PD1{}.F15.R1.C2' - Advance_Directive_Code_Name_of_Coding_System = 'PD1{}.F15.R1.C3' - Advance_Directive_Code_Alternate_Identifier = 'PD1{}.F15.R1.C4' - Advance_Directive_Code_Alternate_Text = 'PD1{}.F15.R1.C5' - Advance_Directive_Code_Name_of_Alternate_Coding_System = 'PD1{}.F15.R1.C6' - Immunization_Registry_Status = 'PD1{}.F16' - Immunization_Registry_Status_Effective_Date = 'PD1{}.F17' - Publicity_Code_Effective_Date = 'PD1{}.F18' - Military_Branch = 'PD1{}.F19' - Military_Rank_Grade = 'PD1{}.F20' - Military_Status = 'PD1{}.F21' - - @staticmethod - def get_segment_name() -> str: - return 'PD1' - - @staticmethod - def get_segment_title() -> str: - return 'Patient Additional Demographic' - - -class RolSegment(Enum): - Role_Instance_ID = 'ROL{}.F1' - Action_Code = 'ROL{}.F2' - Role_ROL = 'ROL{}.F3' - Role_Person = 'ROL{}.F4' - Role_Begin_Date_Time = 'ROL{}.F5' - Role_End_Date_Time = 'ROL{}.F6' - Role_Duration = 'ROL{}.F7' - Role_Action_Reason = 'ROL{}.F8' - Provider_Type = 'ROL{}.F9' - Organization_Unit_Type = 'ROL{}.F10' - Office_Home_Address_Birthplace = 'ROL{}.F11' - Phone = 'ROL{}.F12' - Persons_Location = 'ROL{}.F13' - Organization = 'ROL{}.F14' - - @staticmethod - def get_segment_name() -> str: - return 'ROL' - - @staticmethod - def get_segment_title() -> str: - return 'Role' - - -class Pv1Segment(Enum): - Set_ID = 'PV1{}.F1' - Patient_Class_ID = 'PV1{}.F2.R1.C1' - Patient_Class_Text = 'PV1{}.F2.R1.C2' # inpatient, outpatient, etc - Patient_Class_Name_of_Coding_System = 'PV1{}.F2.R1.C3' - Patient_Class_Alt_ID = 'PV1{}.F2.R1.C4' - Patient_Class_Alt_Text = 'PV1{}.F2.R1.C5' - Patient_Class_2nd_Alt_ID = 'PV1{}.F2.R1.C10' - Patient_Class_2nd_Alt_Text = 'PV1{}.F2.R1.C11' - Patient_Loc_Point_of_Care = 'PV1{}.F3.R1.C1' - Patient_Loc_Room = 'PV1{}.F3.R1.C2' - Patient_Loc_Bed = 'PV1{}.F3.R1.C3' - Patient_Loc_Facility = 'PV1{}.F3.R1.C4' - Patient_Loc_Location_Status = 'PV1{}.F3.R1.C5' - Patient_Loc_Assigning_Authority = 'PV1{}.F3.R1.C11' - Admission_Type_ID = 'PV1{}.F4.R1.C1' - Admission_Type_Text = 'PV1{}.F4.R1.C2' - Admission_Type_Alt_ID = 'PV1{}.F4.R1.C4' - Admission_Type_Alt_Text = 'PV1{}.F4.R1.C5' - Admission_Type_2nd_Alt_ID = 'PV1{}.F4.R1.C10' - Admission_Type_2nd_Alt_Text = 'PV1{}.F4.R1.C11' - Attending_Doctor = 'PV1{}.F7' - Attending_Doctor_Person_ID = 'PV1{}.F7.R1.C1' - Attending_Doctor_Family_Name = 'PV1{}.F7.R1.C2.S1' - Attending_Doctor_Family_Name_Own_Surname_Prefix = 'PV1{}.F7.R1.C2.S2' - Attending_Doctor_Given_Name = 'PV1{}.F7.R1.C3' - Attending_Doctor_Middle_Initial = 'PV1{}.F7.R1.C4' - Attending_Doctor_Suffix = 'PV1{}.F7.R1.C5' - Attending_Doctor_Prefix = 'PV1{}.F7.R1.C6' - Attending_Doctor_Degree = 'PV1{}.F7.R1.C7' - Attending_Doctor_Source_Table = 'PV1{}.F7.R1.C8' - Attending_Doctor_Assigning_Authority = 'PV1{}.F7.R1.C9' - Attending_Doctor_Name_Type_Code = 'PV1{}.F7.R1.C10' - Attending_Doctor_Identifier_Check_Digit = 'PV1{}.F7.R1.C11' - Attending_Doctor_Check_Digit_Scheme = 'PV1{}.F7.R1.C12' - Attending_Doctor_Identifier_Type_Code = 'PV1{}.F7.R1.C13' - Attending_Doctor_Assigning_Facility = 'PV1{}.F7.R1.C14' - Attending_Doctor_Name_Representation_Code = 'PV1{}.F7.R1.C15' - Attending_Doctor_Name_Context = 'PV1{}.F7.R1.C16' - Attending_Doctor_Name_Validity_Range = 'PV1{}.F7.R1.C17' - Attending_Doctor_Name_Assembly_Order = 'PV1{}.F7.R1.C18' - Attending_Doctor_Effective_Date = 'PV1{}.F7.R1.C19' - Attending_Doctor_Expiration_Date = 'PV1{}.F7.R1.C20' - Attending_Doctor_Professional_Suffix = 'PV1{}.F7.R1.C21' - Attending_Doctor_Assigning_Jurisdiction = 'PV1{}.F7.R1.C22' - Attending_Doctor_Assigning_Agency_or_Department = 'PV1{}.F7.R1.C23' - Referring_Doctor = 'PV1{}.F8' - Referring_Doctor_Person_ID = 'PV1{}.F8.R1.C1' - Referring_Doctor_Family_Name = 'PV1{}.F8.R1.C2.S1' - Referring_Doctor_Family_Name_Own_Surname_Prefix = 'PV1{}.F8.R1.C2.S2' - Referring_Doctor_Given_Name = 'PV1{}.F8.R1.C3' - Referring_Doctor_Middle_Initial = 'PV1{}.F8.R1.C4' - Referring_Doctor_Suffix = 'PV1{}.F8.R1.C5' - Referring_Doctor_Prefix = 'PV1{}.F8.R1.C6' - Referring_Doctor_Degree = 'PV1{}.F8.R1.C7' - Referring_Doctor_Source_Table = 'PV1{}.F8.R1.C8' - Referring_Doctor_Assigning_Authority = 'PV1{}.F8.R1.C9' - Referring_Doctor_Name_Type_Code = 'PV1{}.F8.R1.C10' - Referring_Doctor_Identifier_Check_Digit = 'PV1{}.F8.R1.C11' - Referring_Doctor_Check_Digit_Scheme = 'PV1{}.F8.R1.C12' - Referring_Doctor_Identifier_Type_Code = 'PV1{}.F8.R1.C13' - Referring_Doctor_Assigning_Facility = 'PV1{}.F8.R1.C14' - Referring_Doctor_Name_Representation_Code = 'PV1{}.F8.R1.C15' - Referring_Doctor_Name_Context = 'PV1{}.F8.R1.C16' - Referring_Doctor_Name_Validity_Range = 'PV1{}.F8.R1.C17' - Referring_Doctor_Name_Assembly_Order = 'PV1{}.F8.R1.C18' - Referring_Doctor_Effective_Date = 'PV1{}.F8.R1.C19' - Referring_Doctor_Expiration_Date = 'PV1{}.F8.R1.C20' - Referring_Doctor_Professional_Suffix = 'PV1{}.F8.R1.C21' - Referring_Doctor_Assigning_Jurisdiction = 'PV1{}.F8.R1.C22' - Referring_Doctor_Assigning_Agency_or_Department = 'PV1{}.F8.R1.C23' - Consulting_Doctor = 'PV1{}.F9' - Consulting_Doctor_Person_ID = 'PV1{}.F9.R1.C1' - Consulting_Doctor_Family_Name = 'PV1{}.F9.R1.C2.S1' - Consulting_Doctor_Family_Name_Own_Surname_Prefix = 'PV1{}.F9.R1.C2.S2' - Consulting_Doctor_Given_Name = 'PV1{}.F9.R1.C3' - Consulting_Doctor_Middle_Initial = 'PV1{}.F9.R1.C4' - Consulting_Doctor_Suffix = 'PV1{}.F9.R1.C5' - Consulting_Doctor_Prefix = 'PV1{}.F9.R1.C6' - Consulting_Doctor_Degree = 'PV1{}.F9.R1.C7' - Consulting_Doctor_Source_Table = 'PV1{}.F9.R1.C8' - Consulting_Doctor_Assigning_Authority = 'PV1{}.F9.R1.C9' - Consulting_Doctor_Name_Type_Code = 'PV1{}.F9.R1.C10' - Consulting_Doctor_Identifier_Check_Digit = 'PV1{}.F9.R1.C11' - Consulting_Doctor_Check_Digit_Scheme = 'PV1{}.F9.R1.C12' - Consulting_Doctor_Identifier_Type_Code = 'PV1{}.F9.R1.C13' - Consulting_Doctor_Assigning_Facility = 'PV1{}.F9.R1.C14' - Consulting_Doctor_Name_Representation_Code = 'PV1{}.F9.R1.C15' - Consulting_Doctor_Name_Context = 'PV1{}.F9.R1.C16' - Consulting_Doctor_Name_Validity_Range = 'PV1{}.F9.R1.C17' - Consulting_Doctor_Name_Assembly_Order = 'PV1{}.F9.R1.C18' - Consulting_Doctor_Effective_Date = 'PV1{}.F9.R1.C19' - Consulting_Doctor_Expiration_Date = 'PV1{}.F9.R1.C20' - Consulting_Doctor_Professional_Suffix = 'PV1{}.F9.R1.C21' - Consulting_Doctor_Assigning_Jurisdiction = 'PV1{}.F9.R1.C22' - Consulting_Doctor_Assigning_Agency_or_Department = 'PV1{}.F9.R1.C23' - Hospital_Service = 'PV1{}.F10' - Hospital_Service_Identifier = 'PV1{}.F10.R1.C1' - Hospital_Service_Text = 'PV1{}.F10.R1.C2' - Readmission_Indicator = 'PV1{}.F13' - Admit_Source = 'PV1{}.F14' - Admit_Source_ID = 'PV1{}.F14.R1.C1' - Admit_Source_Text = 'PV1{}.F14.R1.C2' - Admitting_Doctor = 'PV1{}.F17' - Admitting_Doctor_Person_ID = 'PV1{}.F17.R1.C1' - Admitting_Doctor_Family_Name = 'PV1{}.F17.R1.C2.S1' - Admitting_Doctor_Family_Name_Own_Surname_Prefix = 'PV1{}.F17.R1.C2.S2' - Admitting_Doctor_Given_Name = 'PV1{}.F17.R1.C3' - Admitting_Doctor_Middle_Initial = 'PV1{}.F17.R1.C4' - Admitting_Doctor_Suffix = 'PV1{}.F17.R1.C5' - Admitting_Doctor_Prefix = 'PV1{}.F17.R1.C6' - Admitting_Doctor_Degree = 'PV1{}.F17.R1.C7' - Admitting_Doctor_Source_Table = 'PV1{}.F17.R1.C8' - Admitting_Doctor_Assigning_Authority = 'PV1{}.F17.R1.C9' - Admitting_Doctor_Name_Type_Code = 'PV1{}.F17.R1.C10' - Admitting_Doctor_Identifier_Check_Digit = 'PV1{}.F17.R1.C11' - Admitting_Doctor_Check_Digit_Scheme = 'PV1{}.F17.R1.C12' - Admitting_Doctor_Identifier_Type_Code = 'PV1{}.F17.R1.C13' - Admitting_Doctor_Assigning_Facility = 'PV1{}.F17.R1.C14' - Admitting_Doctor_Name_Representation_Code = 'PV1{}.F17.R1.C15' - Admitting_Doctor_Name_Context = 'PV1{}.F17.R1.C16' - Admitting_Doctor_Name_Validity_Range = 'PV1{}.F17.R1.C17' - Admitting_Doctor_Name_Assembly_Order = 'PV1{}.F17.R1.C18' - Admitting_Doctor_Effective_Date = 'PV1{}.F17.R1.C19' - Admitting_Doctor_Expiration_Date = 'PV1{}.F17.R1.C20' - Admitting_Doctor_Professional_Suffix = 'PV1{}.F17.R1.C21' - Admitting_Doctor_Assigning_Jurisdiction = 'PV1{}.F17.R1.C22' - Admitting_Doctor_Assigning_Agency_or_Department = 'PV1{}.F17.R1.C23' - Patient_Type_ID = 'PV1{}.F18.R1.C1' - Patient_Type_Text = 'PV1{}.F18.R1.C2' - Patient_Type_Alt_ID = 'PV1{}.F18.R1.C4' - Patient_Type_Alt_Text = 'PV1{}.F18.R1.C5' - Visit_Number = 'PV1{}.F19.R1.C1' - Discharge_Disposition = 'PV1{}.F36.R1.C1' - Discharge_Disposition_Text = 'PV1{}.F36.R1.C2' - Discharge_Disposition_Coding = 'PV1{}.F36.R1.C3' - Discharge_Disposition_Alt = 'PV1{}.F36.R1.C4' - Discharge_Disposition_Text_Alt = 'PV1{}.F36.R1.C5' - Discharge_Disposition_Coding_Alt = 'PV1{}.F36.R1.C6' - Discharge_Disposition_Original_Text = 'PV1{}.F36.R1.C9' - Discharge_Disposition_Alt2 = 'PV1{}.F36.R1.C10' - Discharge_Disposition_Text_Alt2 = 'PV1{}.F36.R1.C11' - Discharge_Disposition_Coding_Alt2 = 'PV1{}.F36.R1.C12' - Discharge_to_Location = 'PV1{}.F37' - # Some records come in with Servicing Facility as a multi-part field. - # First part might be NPI. The next could be facility name. - Servicing_Facility = 'PV1{}.F39' - Servicing_Facility_Name = 'PV1{}.F39.R1.C2' - Admit_Date_Time = 'PV1{}.F44' - Discharge_Date_Time = 'PV1{}.F45' - Current_Patient_Balance = 'PV1{}.F45' - Total_Charges = 'PV1{}.F47' - Visit_Ind = 'PV1{}.F51' - Other_HealthCare_Provider = 'PV1{}.F52' - Service_Episode_Description = 'PV1{}.F53' - - @staticmethod - def get_segment_name() -> str: - return 'PV1' - - @staticmethod - def get_segment_title() -> str: - return 'Patient Visit' - - -# PV2||Routine|^Medicine Refill|||||||||103|||||||||n|N||||||||||N||||||Public Trans -class Pv2Segment(Enum): - Prior_Pending_Location = 'PV2{}.F1' - Prior_Pending_Location_Point_of_Care = 'PV2{}.F1.R1.C1' - Prior_Pending_Location_Room = 'PV2{}.F1.R1.C2' - Prior_Pending_Location_Bed = 'PV2{}.F1.R1.C3' - Prior_Pending_Location_Facility = 'PV2{}.F1.R1.C4' - Prior_Pending_Location_Location_Status = 'PV2{}.F1.R1.C5' - Accommodation_Code = 'PV2{}.F2' - Admit_Reason = 'PV2{}.F3' - Transfer_Reason_ID = 'PV2{}.F4.R1.C1' - Transfer_Reason_Text = 'PV2{}.F4.R1.C2' - Transfer_Reason_Alt_ID = 'PV2{}.F4.R1.C4' - Transfer_Reason_Alt_Text = 'PV2{}.F4.R1.C5' - Transfer_Reason_2nd_Alt_ID = 'PV2{}.F4.R1.C10' - Transfer_Reason_2nd_Alt_Text = 'PV2{}.F4.R1.C11' - Patient_Valuables = 'PV2{}.F5' - Patient_Valuables_Location = 'PV2{}.F6' - Visit_User_Code = 'PV2{}.F7' - Expected_Admit_DateTime = 'PV2{}.F8' - Expected_Discharge_DateTime = 'PV2{}.F9' - Estimated_Length_of_Inpatient_Stay = 'PV2{}.F10' - Visit_Description = 'PV2{}.F12' - Referral_Source_Code = 'PV2{}.F13' - Previous_Service_Date = 'PV2{}.F14' - Retention_Indicator = 'PV2{}.F19' - Previous_Treatment_Date = 'PV2{}.F26' - Military_Partnership_Code = 'PV2{}.F34' # indicates that a military healthcare facility has contracted with a non-military healthcare facility for the use of its services. - Military_NonAvailability_Code = 'PV2{}.F35' # N - the patient does not have permissions to use a non-military healthcare facility - Mode_of_Arrival = 'PV2{}.F38' - Admission_Level_of_Care_Text = 'PV2{}.F40.R1.C2' - Patient_Condition_Code = 'PV2{}.F42' - - @staticmethod - def get_segment_name() -> str: - return 'PV2' - - @staticmethod - def get_segment_title() -> str: - return 'Patient Visit Part 2' - - -class Al1Segment(Enum): - """Patient Allergy Information""" - Set_ID = 'AL1{}.F1' - Allergen_Type_Code_Identifier = 'AL1{}.F2.R1.C1' - Allergen_Type_Code_Name_of_Coding_System = 'AL1{}.F2.R1.C2' - Allergen_Type_Code_Text = 'AL1{}.F2.R1.C3' - Allergen_Type_Code_Alternate_Identifier = 'AL1{}.F2.R1.C4' - Allergen_Type_Code_Alternate_Text = 'AL1{}.F2.R1.C5' - Allergen_Type_Code_Name_of_Alternate_Coding_System = 'AL1{}.F2.R1.C6' - - Allergen_Code_Mnemonic_Desc_Identifier = 'AL1{}.F3.R1.C1' - Allergen_Code_Mnemonic_Desc_Text = 'AL1{}.F3.R1.C2' - Allergen_Code_Mnemonic_Desc_Name_of_Coding_System = 'AL1{}.F3.R1.C3' - Allergen_Code_Mnemonic_Desc_Alternate_Identifier = 'AL1{}.F3.R1.C4' - Allergen_Code_Mnemonic_Desc_Alternate_Text = 'AL1{}.F3.R1.C5' - Allergen_Code_Mnemonic_Desc_Name_of_Alternate_Coding_System = 'AL1{}.F3.R1.C6' - Allergy_Reaction_Code = 'AL1{}.F5' - Identification_Date = 'AL1{}.F6' - - @staticmethod - def get_segment_name() -> str: - return 'AL1' - - @staticmethod - def get_segment_title() -> str: - return 'Patient Allergy' - - -class Dg1Segment(Enum): - Set_ID = 'DG1{}.F1' - Diagnosis_Coding_Method = 'DG1{}.F2' - Diagnosis_Code_ID = 'DG1{}.F3.R1.C1' - Diagnosis_Code_Desc = 'DG1{}.F3.R1.C2' - Diagnosis_Code_Code_System = 'DG1{}.F3.R1.C3' - Diagnosis_Description = 'DG1{}.F4' - # Diagnosis_Date_Time - Diagnosis_Type = 'DG1{}.F6' - - # Major_Diagnostic_Category - # Diagnostic_Related_Group - # DRG_Approval_Indicator - # DRG_Grouper_Review_Code - # Outlier_Type - # Outlier_Days - # Outlier_Cost - # Grouper_Version_And_Type - # Diagnosis_Priority - # Diagnosing_Clinician - # Diagnosis_Classification - # Confidential_Indicator - # Attestation_Date_Time - # Diagnosis_Identifier - # Diagnosis_Action_Code - - @staticmethod - def get_segment_name() -> str: - return 'DG1' - - @staticmethod - def get_segment_title() -> str: - return 'Diagnosis' - - -class Pr1Segment(Enum): - """Procedures""" - Set_ID = 'PR1{}.F1' - Procedure_Coding_Method = 'PR1{}.F2' - Procedure_Code_Identifier = 'PR1{}.F3.R1.C1' - Procedure_Code_Text = 'PR1{}.F3.R1.C2' - Procedure_Code_Name_of_Coding_System = 'PR1{}.F3.R1.C3' - Procedure_Code_Alternate_Identifier = 'PR1{}.F3.R1.C4' - Procedure_Code_Alternate_Text = 'PR1{}.F3.R1.C5' - Procedure_Code_Name_of_Alternate_Coding_System = 'PR1{}.F3.R1.C6' - Procedure_Description = 'PR1{}.F4' - Procedure_Time = 'PR1{}.F5.R1.C1' - Procedure_Functional_Type = 'PR1{}.F6' - Procedure_Minutes = 'PR1{}.F7' - Anesthesiologist_ID_Number = 'PR1{}.F8.R1.C1' - Anesthesiologist_Family_Name = 'PR1{}.F8.R1.C2' - Anesthesiologist_Given_Name = 'PR1{}.F8.R1.C3' - Anesthesiologist_Middle_Initial = 'PR1{}.F8.R1.C4' - Anesthesiologist_Suffix = 'PR1{}.F8.R1.C5' - Anesthesiologist_Prefix = 'PR1{}.F8.R1.C6' - Anesthesiologist_Source_Table = 'PR1{}.F8.R1.C8' - Anesthesiologist_Assigning_Authority = 'PR1{}.F8.R1.C9' - Anesthesiologist_Name_Type_Code = 'PR1{}.F8.R1.C10' - Anesthesiologist_Identifier_Check_Digit = 'PR1{}.F8.R1.C11' - Anesthesiologist_Check_Digit_Scheme = 'PR1{}.F8.R1.C12' - Anesthesiologist_Identifier_Type_Code = 'PR1{}.F8.R1.C13' - Anesthesiologist_Assigning_Facility = 'PR1{}.F8.R1.C14' - Anesthesiologist_Name_Representation_Code = 'PR1{}.F8.R1.C15' - Anesthesiologist_Name_Context = 'PR1{}.F8.R1.C16' - Anesthesiologist_Name_Assembly_Order = 'PR1{}.F8.R1.C18' - Anesthesiologist_Effective_Date = 'PR1{}.F8.R1.C19' - Anesthesiologist_Expiration_Date = 'PR1{}.F8.R1.C20' - Anesthesiologist_Professional_Suffix = 'PR1{}.F8.R1.C21' - Anesthesiologist_Assigning_Jurisdiction = 'PR1{}.F8.R1.C22' - Anesthesiologist_Assigning_Agency_or_Dept = 'PR1{}.F8.R1.C23' - Anesthesia_Code = 'PR1{}.F9' - Anesthesia_Minutes = 'PR1{}.F10' - Surgeon_ID_Number = 'PR1{}.F11.R1.C1' - Surgeon_Family_Name = 'PR1{}.F11.R1.C2' - Surgeon_Given_Name = 'PR1{}.F1.R1.C3' - Surgeon_Middle_Initial = 'PR1{}.F11.R1.C4' - Surgeon_Suffix = 'PR1{}.F11.R1.C5' - Surgeon_Prefix = 'PR1{}.F11.R1.C6' - Surgeon_Source_Table = 'PR1{}.F11.R1.C8' - Surgeon_Assigning_Authority = 'PR1{}.F11.R1.C9' - Surgeon_Name_Type_Code = 'PR1{}.F11.R1.C10' - Surgeon_Identifier_Check_Digit = 'PR1{}.F11.R1.C11' - Surgeon_Check_Digit_Scheme = 'PR1{}.F11.R1.C12' - Surgeon_Identifier_Type_Code = 'PR1{}.F11.R1.C13' - Surgeon_Assigning_Facility = 'PR1{}.F11.R1.C14' - Surgeon_Name_Representation_Code = 'PR1{}.F11.R1.C15' - Surgeon_Name_Context = 'PR1{}.F11.R1.C16' - Surgeon_Name_Assembly_Order = 'PR1{}.F11.R1.C18' - Surgeon_Effective_Date = 'PR1{}.F11.R1.C19' - Surgeon_Expiration_Date = 'PR1{}.F11.R1.C20' - Surgeon_Professional_Suffix = 'PR1{}.F11.R1.C21' - Surgeon_Assigning_Jurisdiction = 'PR1{}.F11.R1.C22' - Surgeon_Assigning_Agency_or_Dept = 'PR1{}.F11.R1.C23' - Procedure_Practitioner_ID_Number = 'PR1{}.F12.R1.C1' - Procedure_Practitioner_Family_Name = 'PR1{}.F12.R1.C2' - Procedure_Practitioner_Given_Name = 'PR1{}.F12.R1.C3' - Procedure_Practitioner_Middle_Initial = 'PR1{}.F12.R1.C4' - Procedure_Practitioner_Suffix = 'PR1{}.F12.R1.C5' - Procedure_Practitioner_Prefix = 'PR1{}.F12.R1.C6' - Procedure_Practitioner_Source_Table = 'PR1{}.F12.R1.C8' - Procedure_Practitioner_Assigning_Authority = 'PR1{}.F12.R1.C9' - Procedure_Practitioner_Name_Type_Code = 'PR1{}.F12.R1.C10' - Procedure_Practitioner_Identifier_Check_Digit = 'PR1{}.F12.R1.C11' - Procedure_Practitioner_Check_Digit_Scheme = 'PR1{}.F12.R1.C12' - Procedure_Practitioner_Identifier_Type_Code = 'PR1{}.F12.R1.C13' - Procedure_Practitioner_Assigning_Facility = 'PR1{}.F12.R1.C14' - Procedure_Practitioner_Name_Representation_Code = 'PR1{}.F12.R1.C15' - Procedure_Practitioner_Name_Context = 'PR1{}.F12.R1.C16' - Procedure_Practitioner_Name_Assembly_Order = 'PR1{}.F12.R1.C18' - Procedure_Practitioner_Effective_Date = 'PR1{}.F12.R1.C19' - Procedure_Practitioner_Expiration_Date = 'PR1{}.F12.R1.C20' - Procedure_Practitioner_Professional_Suffix = 'PR1{}.F12.R1.C21' - Procedure_Practitioner_Assigning_Jurisdiction = 'PR1{}.F12.R1.C22' - Procedure_Practitioner_Assigning_Agency_or_Dept = 'PR1{}.F12.R1.C23' - Consent_Code_Identifier = 'PR1{}.F13.R1.C1' - Consent_Code_Text = 'PR1{}.F13.R1.C2' - Consent_Code_Name_of_Coding_System = 'PR1{}.F13.R1.C3' - Consent_Code_Alternate_Identifier = 'PR1{}.F13.R1.C4' - Consent_Code_Alternate_Text = 'PR1{}.F13.R1.C5' - Consent_Code_Name_of_Alternate_Coding_System = 'PR1{}.F13.R1.C6' - Procedure_Priority = 'PR1{}.F14' - Associated_Diag_Code_Identifier = 'PR1{}.F15.R1.C1' - Associated_Diag_Code_Text = 'PR1{}.F15.R1.C2' - Associated_Diag_Code_Name_of_Coding_System = 'PR1{}.F15.R1.C3' - Associated_Diag_Code_Alternate_Identifier = 'PR1{}.F15.R1.C4' - Associated_Diag_Code_Alternate_Text = 'PR1{}.F15.R1.C5' - Associated_Diag_Code_Name_of_Alternate_Coding_System = 'PR1{}.F15.R1.C6' - Proc_Code_Mod_Identifier = 'PR1{}.F16.R1.C1' - Proc_Code_Mod_Text = 'PR1{}.F16.R1.C2' - Proc_Code_Mod_Name_of_Coding_System = 'PR1{}.F16.R1.C3' - Proc_Code_Mod_Alternate_Identifier = 'PR1{}.F16.R1.C4' - Proc_Code_Mod_Alternate_Text = 'PR1{}.F16.R1.C5' - Proc_Code_Mod_Name_of_Alternate_Coding_System = 'PR1{}.F16.R1.C6' - Procedure_DRG_Type = 'PR1{}.F17' - Tissue_Type_Code_Identifier = 'PR1{}.F18.R1.C1' - Tissue_Type_Code_Text = 'PR1{}.F18.R1.C2' - Tissue_Type_Code_Name_of_Coding_System = 'PR1{}.F18.R1.C3' - Tissue_Type_Code_Alternate_Identifier = 'PR1{}.F18.R1.C4' - Tissue_Type_Code_Alternate_Text = 'PR1{}.F18.R1.C5' - Tissue_Type_Code_Name_of_Alternate_Coding_System = 'PR1{}.F18.R1.C6' - Procedure_Identifier_Entity_Identifier = 'PR1{}.F19.R1.C1' - Procedure_Identifier_Namespace_ID = 'PR1{}.F19.R1.C2' - Procedure_Identifier_Universal_ID = 'PR1{}.F19.R1.C3' - Procedure_Identifier_Universal_ID_Type = 'PR1{}.F19.R1.C4' - Procedure_Action_Code = 'PR1{}.F20' - - @staticmethod - def get_segment_name() -> str: - return 'PR1' - - @staticmethod - def get_segment_title() -> str: - return 'Procedures' - - -class In1Segment(Enum): - """Insurance Company Info""" - Set_ID = 'IN1{}.F1' - Health_Plan_ID = 'IN1{}.F2.R1.C1' - Health_Plan_Text = 'IN1{}.F2.R1.C2' - Health_Plan_Coding = 'IN1{}.F2.R1.C3' - Health_Plan_Alt_ID = 'IN1{}.F2.R1.C4' - Health_Plan_Alt_Text = 'IN1{}.F2.R1.C5' - Health_Plan_Alt_Coding = 'IN1{}.F2.R1.C6' - Health_Plan_Coding_System_Version = 'IN1{}.F2.R1.C7' - Health_Plan_Alt_Coding_System_Version = 'IN1{}.F2.R1.C8' - Original_Text = 'IN1{}.F2.R1.C9' - - Insurance_Company_ID_Number = 'IN1{}.F3.R1.C1' - Insurance_Company_ID_Assigning_Facility = 'IN1{}.F3.R1.C6' - Insurance_Company_ID_Effective_Date = 'IN1{}.F3.R1.C7' - Insurance_Company_ID_Expiration_Date = 'IN1{}.F3.R1.C8' - Insurance_Company_ID_Assigning_Jurisdiction = 'IN1{}.F3.R1.C9' - - Insurance_Company_Organization_Name = 'IN1{}.F4.R1.C1' - Insurance_Company_Organization_Name_Code = 'IN1{}.F4.R1.C2' - - Insurance_Company_Street_Address = 'IN1{}.F5.R1.C1' - Insurance_Company_Other_Designation = 'IN1{}.F5.R1.C2' - Insurance_Company_City = 'IN1{}.F5.R1.C3' - Insurance_Company_State_or_Province = 'IN1{}.F5.R1.C4' - Insurance_Company_Zip_or_Postal_Code = 'IN1{}.F5.R1.C5' - Insurance_Company_Country = 'IN1{}.F5.R1.C6' - Insurance_Company_Address_Type = 'IN1{}.F5.R1.C7' - - Insurance_Company_Phone_Number_Area_Code = 'IN1{}.F7.R1.C6' - Insurance_Company_Phone_Number_Local_Number = 'IN1{}.F7.R1.C7' - Insurance_Company_Phone_Number_Ext = 'IN1{}.F7.R1.C8' - Insurance_Company_Phone_Number_Any_Text = 'IN1{}.F7.R1.C9' - Insurance_Company_Phone_Number_Ext_Prefix = 'IN1{}.F7.R1.C10' - Insurance_Company_Phone_Number_Unformatted = 'IN1{}.F7.R1.C12' - - Group_Number = 'IN1{}.F8' - Group_Name = 'IN1{}.F9' - Insured_Group_Emp_ID_Number = 'IN1{}.F10.R1.C1' - Insured_Group_Emp_Name = 'IN1{}.F11.R1.C1' - Plan_Effective_Date = 'IN1{}.F12' - Plan_Expiration_Date = 'IN1{}.F13' - - Name_of_Insured_Family_Name = 'IN1{}.F16.R1.C1.S1' - Name_of_Insured_Family_Name_Surname = 'IN1{}.F16.R1.C1.S2' - Name_of_Insured_Family_Own_Surname_Prefix = 'IN1{}.F16.R1.C1.S3' - Name_of_Insured_Given_Name = 'IN1{}.F16.R1.C2' - Name_of_Insured_Other_Given_Names = 'IN1{}.F16.R1.C3' - Name_of_Insured_Suffix = 'IN1{}.F16.R1.C4' - Name_of_Insured_Prefix = 'IN1{}.F16.R1.C5' - - Policy_Number = 'IN1{}.F36' - Coverage_Type = 'IN1{}.F47' - Subscriber_ID = 'IN1{}.F49' - - @staticmethod - def get_segment_name() -> str: - return 'IN1' - - @staticmethod - def get_segment_title() -> str: - return 'Insurance Company Info' - - -class In2Segment(Enum): - """Additional Insurance Info""" - Insureds_Employee_ID = 'IN2{}.F1' - Insureds_Social_Security_Number = 'IN2{}.F2' - Insureds_Employers_Name_and_ID = 'IN2{}.F3' - Employer_Information_Data = 'IN2{}.F4' - Medicare_Health_Ins_Card_Number = 'IN2{}.F6' - Non_Covered_Insurance_Code = 'IN2{}.F24' - - @staticmethod - def get_segment_name() -> str: - return 'IN2' - - @staticmethod - def get_segment_title() -> str: - return 'Insurance Company Additional Info' - - -class NteSegment(Enum): - Set_ID = 'NTE{}.F1' - Source_Of_Comment = 'NTE{}.F2' - Comment = 'NTE{}.F3' - Comment_Type = 'NTE{}.F4' - - @staticmethod - def get_segment_name() -> str: - return 'NTE' - - @staticmethod - def get_segment_title() -> str: - return 'Note' - - -class OvrSegment(Enum): - """Business Rule Overide""" - BRO_Type_ID = 'OVR{}.F1.R1.C1' - BRO_Type_Text = 'OVR{}.F1.R1.C2' - BRO_Type_Name_of_Coding_System = 'OVR{}.F1.R1.C3' - BRO_Type_Alt_ID = 'OVR{}.F1.R1.C4' - BRO_Type_Alt_Text = 'OVR{}.F1.R1.C5' - BRO_Type_Alt_Name_of_Coding_System = 'OVR{}.F1.R1.C6' - BRO_Type_Coding_System_Version = 'OVR{}.F1.R1.C7' - BRO_Type_Coding_System_Version_Alt = 'OVR{}.F1.R1.C8' - BRO_Type_Original_Text = 'OVR{}.F1.R1.C9' - BRO_Code_ID = 'OVR{}.21.R1.C1' - BRO_Code_Text = 'OVR{}.F2.R1.C2' - BRO_Code_Name_of_Coding_System = 'OVR{}.F2.R1.C3' - BRO_Code_Alt_ID = 'OVR{}.F2.R1.C4' - BRO_Code_Alt_Text = 'OVR{}.F2.R1.C5' - BRO_Code_Alt_Name_of_Coding_System = 'OVR{}.F2.R1.C6' - BRO_Code_Coding_System_Version = 'OVR{}.F2.R1.C7' - BRO_Code_Coding_System_Version_Alt = 'OVR{}.F2.R1.C8' - BRO_Code_Original_Text = 'OVR{}.F2.R1.C9' - Override_Comments = 'OVR{}.F3' - - @staticmethod - def get_segment_name() -> str: - return 'OVR' - - @staticmethod - def get_segment_title() -> str: - return 'Business Rule Override' - - -class Gt1Segment(Enum): - """Guarantor Segment""" - Guarantor_Name = 'GT1{}.F3' - - @staticmethod - def get_segment_name() -> str: - return 'GT1' - - @staticmethod - def get_segment_title() -> str: - return 'Guarantor' - - -class Rf1Segment(Enum): - """Referral Information Segment""" - Process_Date = 'RF1{}.F9' - - @staticmethod - def get_segment_name() -> str: - return 'RF1' - - @staticmethod - def get_segment_title() -> str: - return 'Referral Information' - - -class IvcSegment(Enum): - Provider_Tax_Id = 'IVC{}.F26' - - @staticmethod - def get_segment_name() -> str: - return 'IVC' - - @staticmethod - def get_segment_title() -> str: - return 'Invoice' - - -class OruSegment(Enum): - Set_ID = 'ORU.F1' - - @staticmethod - def get_segment_name() -> str: - return 'ORU' - - @staticmethod - def get_segment_title() -> str: - return 'ORU' - - -class OrnSegment(Enum): - Set_ID = 'ORN.F1' - - @staticmethod - def get_segment_name() -> str: - return 'ORN' - - @staticmethod - def get_segment_title() -> str: - return 'ORN' - - -class ZonSegment(Enum): - Zon_Flag = 'ZON.F1' - - @staticmethod - def get_segment_name() -> str: - return 'ZON' - - @staticmethod - def get_segment_title() -> str: - return 'ZON' - -def parse_hl7(message): - # Parse the HL7 message using the hl7 library - parsed_message = hl7.parse(message) - - # Loop through the segments in the message - for segment in parsed_message: - # Get the segment type - segment_type = segment[0] - - # Get the field names for the segment type - field_names = get_segment_fields(segment_type) - - # Loop through the fields in the segment - for i, field in enumerate(segment): - # Label the field with its corresponding field name - if i < len(field_names): - st.write(f"{field_names[i]}: {field}") - else: - st.write(f"Unknown field: {field}") - -# Define the Streamlit app -def app(): - # Add a text input field for the HL7 message - hl7_message = st.text_area("Enter HL7 message here", value="MSH|^~\&|ANYSHARE^2.16.840.1.113883.1.2966.500.1.1.17.1.312.1|ABCCHHH|AnyCompanyHIE|ADX|20190408235621||ADT^A03|183000519^248647541|P|2.5.1\r") - - # Parse the HL7 message and display the labeled fields - if hl7_message: - parse_hl7(hl7_message) - -# if __name__ == "__main__": - - -if __name__ == '__main__': - app() - print(AdmitSource['PR'].value) - print(AdmitSource['HMO'].value) - for i in range(1, 10): - print(AdmitSource.get_value(str(i))) - print(AdmitSource.get_value('PR')) - print(AdmitSource.get_value('Emergency_Room')) diff --git a/spaces/awacke1/HTML5-Aframe-3dMap-Flight/style.css b/spaces/awacke1/HTML5-Aframe-3dMap-Flight/style.css deleted file mode 100644 index 114adf441e9032febb46bc056b2a8bb651075f0d..0000000000000000000000000000000000000000 --- a/spaces/awacke1/HTML5-Aframe-3dMap-Flight/style.css +++ /dev/null @@ -1,28 +0,0 @@ -body { - padding: 2rem; - font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif; -} - -h1 { - font-size: 16px; - margin-top: 0; -} - -p { - color: rgb(107, 114, 128); - font-size: 15px; - margin-bottom: 10px; - margin-top: 5px; -} - -.card { - max-width: 620px; - margin: 0 auto; - padding: 16px; - border: 1px solid lightgray; - border-radius: 16px; -} - -.card p:last-child { - margin-bottom: 0; -} diff --git a/spaces/awacke1/RLHF.Evals/README.md b/spaces/awacke1/RLHF.Evals/README.md deleted file mode 100644 index fb35b137b67c33b4508a40e6ac9303ce6f6cc278..0000000000000000000000000000000000000000 --- a/spaces/awacke1/RLHF.Evals/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: RLHF.Evals -emoji: 🔥😻🔥 -colorFrom: yellow -colorTo: pink -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/badayvedat/AudioSep/models/CLAP/open_clip/linear_probe.py b/spaces/badayvedat/AudioSep/models/CLAP/open_clip/linear_probe.py deleted file mode 100644 index 9d7e23b6b67a53e16d050d675a99d01d7d04d581..0000000000000000000000000000000000000000 --- a/spaces/badayvedat/AudioSep/models/CLAP/open_clip/linear_probe.py +++ /dev/null @@ -1,66 +0,0 @@ -import numpy as np -import torch.nn.functional as F -from torch import nn -from .model import MLPLayers - - -class LinearProbe(nn.Module): - def __init__(self, model, mlp, freeze, in_ch, out_ch, act=None): - """ - Args: - model: nn.Module - mlp: bool, if True, then use the MLP layer as the linear probe module - freeze: bool, if Ture, then freeze all the CLAP model's layers when training the linear probe - in_ch: int, the output channel from CLAP model - out_ch: int, the output channel from linear probe (class_num) - act: torch.nn.functional, the activation function before the loss function - """ - super().__init__() - in_ch = 512 - self.clap_model = model - self.clap_model.text_branch = None # to save memory - self.freeze = freeze - if mlp: - self.lp_layer = MLPLayers(units=[in_ch, in_ch * 2, out_ch]) - else: - self.lp_layer = nn.Linear(in_ch, out_ch) - - if self.freeze: - for param in self.clap_model.parameters(): - param.requires_grad = False - - if act == "None": - self.act = None - elif act == "relu": - self.act = nn.ReLU() - elif act == "elu": - self.act = nn.ELU() - elif act == "prelu": - self.act = nn.PReLU(num_parameters=in_ch) - elif act == "softmax": - self.act = nn.Softmax(dim=-1) - elif act == "sigmoid": - self.act = nn.Sigmoid() - - def forward(self, x, mix_lambda=None, device=None): - """ - Args: - x: waveform, torch.tensor [batch, t_samples] / batch of mel_spec and longer list - mix_lambda: torch.tensor [batch], the mixup lambda - Returns: - class_prob: torch.tensor [batch, class_num] - - """ - # batchnorm cancel grandient - if self.freeze: - self.clap_model.eval() - - x = self.clap_model.audio_projection( - self.clap_model.audio_branch(x, mixup_lambda=mix_lambda, device=device)[ - "embedding" - ] - ) - out = self.lp_layer(x) - if self.act is not None: - out = self.act(out) - return out diff --git a/spaces/banana-projects/web3d/node_modules/three/src/extras/core/Path.js b/spaces/banana-projects/web3d/node_modules/three/src/extras/core/Path.js deleted file mode 100644 index d2b978c3ab0dad069ccf364fd6105b360239589c..0000000000000000000000000000000000000000 --- a/spaces/banana-projects/web3d/node_modules/three/src/extras/core/Path.js +++ /dev/null @@ -1,183 +0,0 @@ -import { Vector2 } from '../../math/Vector2.js'; -import { CurvePath } from './CurvePath.js'; -import { EllipseCurve } from '../curves/EllipseCurve.js'; -import { SplineCurve } from '../curves/SplineCurve.js'; -import { CubicBezierCurve } from '../curves/CubicBezierCurve.js'; -import { QuadraticBezierCurve } from '../curves/QuadraticBezierCurve.js'; -import { LineCurve } from '../curves/LineCurve.js'; - -/** - * @author zz85 / http://www.lab4games.net/zz85/blog - * Creates free form 2d path using series of points, lines or curves. - **/ - -function Path( points ) { - - CurvePath.call( this ); - - this.type = 'Path'; - - this.currentPoint = new Vector2(); - - if ( points ) { - - this.setFromPoints( points ); - - } - -} - -Path.prototype = Object.assign( Object.create( CurvePath.prototype ), { - - constructor: Path, - - setFromPoints: function ( points ) { - - this.moveTo( points[ 0 ].x, points[ 0 ].y ); - - for ( var i = 1, l = points.length; i < l; i ++ ) { - - this.lineTo( points[ i ].x, points[ i ].y ); - - } - - }, - - moveTo: function ( x, y ) { - - this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? - - }, - - lineTo: function ( x, y ) { - - var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); - this.curves.push( curve ); - - this.currentPoint.set( x, y ); - - }, - - quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { - - var curve = new QuadraticBezierCurve( - this.currentPoint.clone(), - new Vector2( aCPx, aCPy ), - new Vector2( aX, aY ) - ); - - this.curves.push( curve ); - - this.currentPoint.set( aX, aY ); - - }, - - bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { - - var curve = new CubicBezierCurve( - this.currentPoint.clone(), - new Vector2( aCP1x, aCP1y ), - new Vector2( aCP2x, aCP2y ), - new Vector2( aX, aY ) - ); - - this.curves.push( curve ); - - this.currentPoint.set( aX, aY ); - - }, - - splineThru: function ( pts /*Array of Vector*/ ) { - - var npts = [ this.currentPoint.clone() ].concat( pts ); - - var curve = new SplineCurve( npts ); - this.curves.push( curve ); - - this.currentPoint.copy( pts[ pts.length - 1 ] ); - - }, - - arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; - - this.absarc( aX + x0, aY + y0, aRadius, - aStartAngle, aEndAngle, aClockwise ); - - }, - - absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { - - this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); - - }, - - ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - - var x0 = this.currentPoint.x; - var y0 = this.currentPoint.y; - - this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - - }, - - absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { - - var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); - - if ( this.curves.length > 0 ) { - - // if a previous curve is present, attempt to join - var firstPoint = curve.getPoint( 0 ); - - if ( ! firstPoint.equals( this.currentPoint ) ) { - - this.lineTo( firstPoint.x, firstPoint.y ); - - } - - } - - this.curves.push( curve ); - - var lastPoint = curve.getPoint( 1 ); - this.currentPoint.copy( lastPoint ); - - }, - - copy: function ( source ) { - - CurvePath.prototype.copy.call( this, source ); - - this.currentPoint.copy( source.currentPoint ); - - return this; - - }, - - toJSON: function () { - - var data = CurvePath.prototype.toJSON.call( this ); - - data.currentPoint = this.currentPoint.toArray(); - - return data; - - }, - - fromJSON: function ( json ) { - - CurvePath.prototype.fromJSON.call( this, json ); - - this.currentPoint.fromArray( json.currentPoint ); - - return this; - - } - -} ); - - -export { Path }; diff --git a/spaces/banana-projects/web3d/node_modules/three/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl.js b/spaces/banana-projects/web3d/node_modules/three/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl.js deleted file mode 100644 index 3c2855627971fdd4a9f03c0d223520286f64035f..0000000000000000000000000000000000000000 --- a/spaces/banana-projects/web3d/node_modules/three/src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl.js +++ /dev/null @@ -1,11 +0,0 @@ -export default /* glsl */` -#ifdef USE_EMISSIVEMAP - - vec4 emissiveColor = texture2D( emissiveMap, vUv ); - - emissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb; - - totalEmissiveRadiance *= emissiveColor.rgb; - -#endif -`; diff --git a/spaces/bioriAsaeru/text-to-voice/?w???????g???j??k? ? F??o??or?G?????r?k ?v On ?k????w????v V???k??z?rytrmdsl _VERIFIED_.md b/spaces/bioriAsaeru/text-to-voice/?w???????g???j??k? ? F??o??or?G?????r?k ?v On ?k????w????v V???k??z?rytrmdsl _VERIFIED_.md deleted file mode 100644 index 5ad9814f652c3733eb049eb3361c1ed8d0f4880a..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/?w???????g???j??k? ? F??o??or?G?????r?k ?v On ?k????w????v V???k??z?rytrmdsl _VERIFIED_.md +++ /dev/null @@ -1,6 +0,0 @@ -

    ?w???????g???j??k? ? f??o??or?砻G??Ʋ???r?k ?v on ?k????w????v v???k??z?rytrmdsl


    Download File ★★★★★ https://urloso.com/2uyQot



    - - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/bioriAsaeru/text-to-voice/Kaplan Test Prep MCAT Physics And Math Review Online Book Download EPUB PDF.md b/spaces/bioriAsaeru/text-to-voice/Kaplan Test Prep MCAT Physics And Math Review Online Book Download EPUB PDF.md deleted file mode 100644 index 249047a775f2ee9d8840c4f79049f9bc2e808934..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Kaplan Test Prep MCAT Physics And Math Review Online Book Download EPUB PDF.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Kaplan Test Prep: MCAT Physics and Math Review : Online Book download EPUB, PDF


    Download Ziphttps://urloso.com/2uyRIh



    -
    - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/boomsss/gamedayspx/intraCols.py b/spaces/boomsss/gamedayspx/intraCols.py deleted file mode 100644 index dbf32accdedc012513e3aa525b6791fae3a5f286..0000000000000000000000000000000000000000 --- a/spaces/boomsss/gamedayspx/intraCols.py +++ /dev/null @@ -1,48 +0,0 @@ -model_cols = [ - 'BigNewsDay', - 'Quarter', - 'Perf5Day', - 'Perf5Day_n1', - 'DaysGreen', - 'DaysRed', - 'CurrentHigh30toClose', - 'CurrentLow30toClose', - 'CurrentClose30toClose', - 'CurrentRange30', - 'GapFill30', - 'CurrentGap', - 'RangePct', - 'RangePct_n1', - 'RangePct_n2', - 'OHLC4_VIX', - 'OHLC4_VIX_n1', - 'OHLC4_VIX_n2', - 'OHLC4_Current_Trend', - 'OHLC4_Trend', - 'CurrentVIXTrend', - 'SPX30IntraPerf', - 'VIX30IntraPerf', - 'VVIX30IntraPerf', - # 'OpenL1', - # 'OpenL2', - # 'OpenH1', - # 'OpenH2', - 'L1TouchPct', - 'L2TouchPct', - 'H1TouchPct', - 'H2TouchPct', - 'L1BreakPct', - 'L2BreakPct', - 'H1BreakPct', - 'H2BreakPct', - 'GreenProbas', - 'H1BreakTouchPct', - 'H2BreakTouchPct', - 'L1BreakTouchPct', - 'L2BreakTouchPct', - 'H1BreakH2TouchPct', - 'L1BreakL2TouchPct', - 'H1TouchGreenPct', - 'L1TouchRedPct' - # 'GapFillGreenProba' -] diff --git a/spaces/botlik100/kaki/i18n/locale_diff.py b/spaces/botlik100/kaki/i18n/locale_diff.py deleted file mode 100644 index 257277965e0866a86d0361863a8f1b408c4f71ab..0000000000000000000000000000000000000000 --- a/spaces/botlik100/kaki/i18n/locale_diff.py +++ /dev/null @@ -1,45 +0,0 @@ -import json -import os -from collections import OrderedDict - -# Define the standard file name -standard_file = "zh_CN.json" - -# Find all JSON files in the directory -dir_path = "./" -languages = [ - f for f in os.listdir(dir_path) if f.endswith(".json") and f != standard_file -] - -# Load the standard file -with open(standard_file, "r", encoding="utf-8") as f: - standard_data = json.load(f, object_pairs_hook=OrderedDict) - -# Loop through each language file -for lang_file in languages: - # Load the language file - with open(lang_file, "r", encoding="utf-8") as f: - lang_data = json.load(f, object_pairs_hook=OrderedDict) - - # Find the difference between the language file and the standard file - diff = set(standard_data.keys()) - set(lang_data.keys()) - - miss = set(lang_data.keys()) - set(standard_data.keys()) - - # Add any missing keys to the language file - for key in diff: - lang_data[key] = key - - # Del any extra keys to the language file - for key in miss: - del lang_data[key] - - # Sort the keys of the language file to match the order of the standard file - lang_data = OrderedDict( - sorted(lang_data.items(), key=lambda x: list(standard_data.keys()).index(x[0])) - ) - - # Save the updated language file - with open(lang_file, "w", encoding="utf-8") as f: - json.dump(lang_data, f, ensure_ascii=False, indent=4) - f.write("\n") diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/backbone/vit.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/backbone/vit.py deleted file mode 100644 index 31cc28ac887773dbc8aea2a663bacd5f7b63bb0c..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/backbone/vit.py +++ /dev/null @@ -1,524 +0,0 @@ -import logging -import math -import fvcore.nn.weight_init as weight_init -import torch -import torch.nn as nn - -from detectron2.layers import CNNBlockBase, Conv2d, get_norm -from detectron2.modeling.backbone.fpn import _assert_strides_are_log2_contiguous - -from .backbone import Backbone -from .utils import ( - PatchEmbed, - add_decomposed_rel_pos, - get_abs_pos, - window_partition, - window_unpartition, -) - -logger = logging.getLogger(__name__) - - -__all__ = ["ViT", "SimpleFeaturePyramid", "get_vit_lr_decay_rate"] - - -class Attention(nn.Module): - """Multi-head Attention block with relative position embeddings.""" - - def __init__( - self, - dim, - num_heads=8, - qkv_bias=True, - use_rel_pos=False, - rel_pos_zero_init=True, - input_size=None, - ): - """ - Args: - dim (int): Number of input channels. - num_heads (int): Number of attention heads. - qkv_bias (bool: If True, add a learnable bias to query, key, value. - rel_pos (bool): If True, add relative positional embeddings to the attention map. - rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. - input_size (int or None): Input resolution for calculating the relative positional - parameter size. - """ - super().__init__() - self.num_heads = num_heads - head_dim = dim // num_heads - self.scale = head_dim**-0.5 - - self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) - self.proj = nn.Linear(dim, dim) - - self.use_rel_pos = use_rel_pos - if self.use_rel_pos: - # initialize relative positional embeddings - self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) - self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) - - if not rel_pos_zero_init: - nn.init.trunc_normal_(self.rel_pos_h, std=0.02) - nn.init.trunc_normal_(self.rel_pos_w, std=0.02) - - def forward(self, x): - B, H, W, _ = x.shape - # qkv with shape (3, B, nHead, H * W, C) - qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) - # q, k, v with shape (B * nHead, H * W, C) - q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) - - attn = (q * self.scale) @ k.transpose(-2, -1) - - if self.use_rel_pos: - attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) - - attn = attn.softmax(dim=-1) - x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) - x = self.proj(x) - - return x - - -class ResBottleneckBlock(CNNBlockBase): - """ - The standard bottleneck residual block without the last activation layer. - It contains 3 conv layers with kernels 1x1, 3x3, 1x1. - """ - - def __init__( - self, - in_channels, - out_channels, - bottleneck_channels, - norm="LN", - act_layer=nn.GELU, - ): - """ - Args: - in_channels (int): Number of input channels. - out_channels (int): Number of output channels. - bottleneck_channels (int): number of output channels for the 3x3 - "bottleneck" conv layers. - norm (str or callable): normalization for all conv layers. - See :func:`layers.get_norm` for supported format. - act_layer (callable): activation for all conv layers. - """ - super().__init__(in_channels, out_channels, 1) - - self.conv1 = Conv2d(in_channels, bottleneck_channels, 1, bias=False) - self.norm1 = get_norm(norm, bottleneck_channels) - self.act1 = act_layer() - - self.conv2 = Conv2d( - bottleneck_channels, - bottleneck_channels, - 3, - padding=1, - bias=False, - ) - self.norm2 = get_norm(norm, bottleneck_channels) - self.act2 = act_layer() - - self.conv3 = Conv2d(bottleneck_channels, out_channels, 1, bias=False) - self.norm3 = get_norm(norm, out_channels) - - for layer in [self.conv1, self.conv2, self.conv3]: - weight_init.c2_msra_fill(layer) - for layer in [self.norm1, self.norm2]: - layer.weight.data.fill_(1.0) - layer.bias.data.zero_() - # zero init last norm layer. - self.norm3.weight.data.zero_() - self.norm3.bias.data.zero_() - - def forward(self, x): - out = x - for layer in self.children(): - out = layer(out) - - out = x + out - return out - - -class Block(nn.Module): - """Transformer blocks with support of window attention and residual propagation blocks""" - - def __init__( - self, - dim, - num_heads, - mlp_ratio=4.0, - qkv_bias=True, - drop_path=0.0, - norm_layer=nn.LayerNorm, - act_layer=nn.GELU, - use_rel_pos=False, - rel_pos_zero_init=True, - window_size=0, - use_residual_block=False, - input_size=None, - ): - """ - Args: - dim (int): Number of input channels. - num_heads (int): Number of attention heads in each ViT block. - mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. - qkv_bias (bool): If True, add a learnable bias to query, key, value. - drop_path (float): Stochastic depth rate. - norm_layer (nn.Module): Normalization layer. - act_layer (nn.Module): Activation layer. - use_rel_pos (bool): If True, add relative positional embeddings to the attention map. - rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. - window_size (int): Window size for window attention blocks. If it equals 0, then not - use window attention. - use_residual_block (bool): If True, use a residual block after the MLP block. - input_size (int or None): Input resolution for calculating the relative positional - parameter size. - """ - super().__init__() - self.norm1 = norm_layer(dim) - self.attn = Attention( - dim, - num_heads=num_heads, - qkv_bias=qkv_bias, - use_rel_pos=use_rel_pos, - rel_pos_zero_init=rel_pos_zero_init, - input_size=input_size if window_size == 0 else (window_size, window_size), - ) - - from timm.models.layers import DropPath, Mlp - - self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() - self.norm2 = norm_layer(dim) - self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer) - - self.window_size = window_size - - self.use_residual_block = use_residual_block - if use_residual_block: - # Use a residual block with bottleneck channel as dim // 2 - self.residual = ResBottleneckBlock( - in_channels=dim, - out_channels=dim, - bottleneck_channels=dim // 2, - norm="LN", - act_layer=act_layer, - ) - - def forward(self, x): - shortcut = x - x = self.norm1(x) - # Window partition - if self.window_size > 0: - H, W = x.shape[1], x.shape[2] - x, pad_hw = window_partition(x, self.window_size) - - x = self.attn(x) - # Reverse window partition - if self.window_size > 0: - x = window_unpartition(x, self.window_size, pad_hw, (H, W)) - - x = shortcut + self.drop_path(x) - x = x + self.drop_path(self.mlp(self.norm2(x))) - - if self.use_residual_block: - x = self.residual(x.permute(0, 3, 1, 2)).permute(0, 2, 3, 1) - - return x - - -class ViT(Backbone): - """ - This module implements Vision Transformer (ViT) backbone in :paper:`vitdet`. - "Exploring Plain Vision Transformer Backbones for Object Detection", - https://arxiv.org/abs/2203.16527 - """ - - def __init__( - self, - img_size=1024, - patch_size=16, - in_chans=3, - embed_dim=768, - depth=12, - num_heads=12, - mlp_ratio=4.0, - qkv_bias=True, - drop_path_rate=0.0, - norm_layer=nn.LayerNorm, - act_layer=nn.GELU, - use_abs_pos=True, - use_rel_pos=False, - rel_pos_zero_init=True, - window_size=0, - window_block_indexes=(), - residual_block_indexes=(), - use_act_checkpoint=False, - pretrain_img_size=224, - pretrain_use_cls_token=True, - out_feature="last_feat", - ): - """ - Args: - img_size (int): Input image size. - patch_size (int): Patch size. - in_chans (int): Number of input image channels. - embed_dim (int): Patch embedding dimension. - depth (int): Depth of ViT. - num_heads (int): Number of attention heads in each ViT block. - mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. - qkv_bias (bool): If True, add a learnable bias to query, key, value. - drop_path_rate (float): Stochastic depth rate. - norm_layer (nn.Module): Normalization layer. - act_layer (nn.Module): Activation layer. - use_abs_pos (bool): If True, use absolute positional embeddings. - use_rel_pos (bool): If True, add relative positional embeddings to the attention map. - rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. - window_size (int): Window size for window attention blocks. - window_block_indexes (list): Indexes for blocks using window attention. - residual_block_indexes (list): Indexes for blocks using conv propagation. - use_act_checkpoint (bool): If True, use activation checkpointing. - pretrain_img_size (int): input image size for pretraining models. - pretrain_use_cls_token (bool): If True, pretrainig models use class token. - out_feature (str): name of the feature from the last block. - """ - super().__init__() - self.pretrain_use_cls_token = pretrain_use_cls_token - - self.patch_embed = PatchEmbed( - kernel_size=(patch_size, patch_size), - stride=(patch_size, patch_size), - in_chans=in_chans, - embed_dim=embed_dim, - ) - - if use_abs_pos: - # Initialize absolute positional embedding with pretrain image size. - num_patches = (pretrain_img_size // patch_size) * (pretrain_img_size // patch_size) - num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches - self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim)) - else: - self.pos_embed = None - - # stochastic depth decay rule - dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] - - self.blocks = nn.ModuleList() - for i in range(depth): - block = Block( - dim=embed_dim, - num_heads=num_heads, - mlp_ratio=mlp_ratio, - qkv_bias=qkv_bias, - drop_path=dpr[i], - norm_layer=norm_layer, - act_layer=act_layer, - use_rel_pos=use_rel_pos, - rel_pos_zero_init=rel_pos_zero_init, - window_size=window_size if i in window_block_indexes else 0, - use_residual_block=i in residual_block_indexes, - input_size=(img_size // patch_size, img_size // patch_size), - ) - if use_act_checkpoint: - # TODO: use torch.utils.checkpoint - from fairscale.nn.checkpoint import checkpoint_wrapper - - block = checkpoint_wrapper(block) - self.blocks.append(block) - - self._out_feature_channels = {out_feature: embed_dim} - self._out_feature_strides = {out_feature: patch_size} - self._out_features = [out_feature] - - if self.pos_embed is not None: - nn.init.trunc_normal_(self.pos_embed, std=0.02) - - self.apply(self._init_weights) - - def _init_weights(self, m): - if isinstance(m, nn.Linear): - nn.init.trunc_normal_(m.weight, std=0.02) - if isinstance(m, nn.Linear) and m.bias is not None: - nn.init.constant_(m.bias, 0) - elif isinstance(m, nn.LayerNorm): - nn.init.constant_(m.bias, 0) - nn.init.constant_(m.weight, 1.0) - - def forward(self, x): - x = self.patch_embed(x) - if self.pos_embed is not None: - x = x + get_abs_pos( - self.pos_embed, self.pretrain_use_cls_token, (x.shape[1], x.shape[2]) - ) - - for blk in self.blocks: - x = blk(x) - - outputs = {self._out_features[0]: x.permute(0, 3, 1, 2)} - return outputs - - -class SimpleFeaturePyramid(Backbone): - """ - This module implements SimpleFeaturePyramid in :paper:`vitdet`. - It creates pyramid features built on top of the input feature map. - """ - - def __init__( - self, - net, - in_feature, - out_channels, - scale_factors, - top_block=None, - norm="LN", - square_pad=0, - ): - """ - Args: - net (Backbone): module representing the subnetwork backbone. - Must be a subclass of :class:`Backbone`. - in_feature (str): names of the input feature maps coming - from the net. - out_channels (int): number of channels in the output feature maps. - scale_factors (list[float]): list of scaling factors to upsample or downsample - the input features for creating pyramid features. - top_block (nn.Module or None): if provided, an extra operation will - be performed on the output of the last (smallest resolution) - pyramid output, and the result will extend the result list. The top_block - further downsamples the feature map. It must have an attribute - "num_levels", meaning the number of extra pyramid levels added by - this block, and "in_feature", which is a string representing - its input feature (e.g., p5). - norm (str): the normalization to use. - square_pad (int): If > 0, require input images to be padded to specific square size. - """ - super(SimpleFeaturePyramid, self).__init__() - assert isinstance(net, Backbone) - - self.scale_factors = scale_factors - - input_shapes = net.output_shape() - strides = [int(input_shapes[in_feature].stride / scale) for scale in scale_factors] - _assert_strides_are_log2_contiguous(strides) - - dim = input_shapes[in_feature].channels - self.stages = [] - use_bias = norm == "" - for idx, scale in enumerate(scale_factors): - out_dim = dim - if scale == 4.0: - layers = [ - nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2), - get_norm(norm, dim // 2), - nn.GELU(), - nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2), - ] - out_dim = dim // 4 - elif scale == 2.0: - layers = [nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2)] - out_dim = dim // 2 - elif scale == 1.0: - layers = [] - elif scale == 0.5: - layers = [nn.MaxPool2d(kernel_size=2, stride=2)] - else: - raise NotImplementedError(f"scale_factor={scale} is not supported yet.") - - layers.extend( - [ - Conv2d( - out_dim, - out_channels, - kernel_size=1, - bias=use_bias, - norm=get_norm(norm, out_channels), - ), - Conv2d( - out_channels, - out_channels, - kernel_size=3, - padding=1, - bias=use_bias, - norm=get_norm(norm, out_channels), - ), - ] - ) - layers = nn.Sequential(*layers) - - stage = int(math.log2(strides[idx])) - self.add_module(f"simfp_{stage}", layers) - self.stages.append(layers) - - self.net = net - self.in_feature = in_feature - self.top_block = top_block - # Return feature names are "p", like ["p2", "p3", ..., "p6"] - self._out_feature_strides = {"p{}".format(int(math.log2(s))): s for s in strides} - # top block output feature maps. - if self.top_block is not None: - for s in range(stage, stage + self.top_block.num_levels): - self._out_feature_strides["p{}".format(s + 1)] = 2 ** (s + 1) - - self._out_features = list(self._out_feature_strides.keys()) - self._out_feature_channels = {k: out_channels for k in self._out_features} - self._size_divisibility = strides[-1] - self._square_pad = square_pad - - @property - def padding_constraints(self): - return { - "size_divisiblity": self._size_divisibility, - "square_size": self._square_pad, - } - - def forward(self, x): - """ - Args: - x: Tensor of shape (N,C,H,W). H, W must be a multiple of ``self.size_divisibility``. - - Returns: - dict[str->Tensor]: - mapping from feature map name to pyramid feature map tensor - in high to low resolution order. Returned feature names follow the FPN - convention: "p", where stage has stride = 2 ** stage e.g., - ["p2", "p3", ..., "p6"]. - """ - bottom_up_features = self.net(x) - features = bottom_up_features[self.in_feature] - results = [] - - for stage in self.stages: - results.append(stage(features)) - - if self.top_block is not None: - if self.top_block.in_feature in bottom_up_features: - top_block_in_feature = bottom_up_features[self.top_block.in_feature] - else: - top_block_in_feature = results[self._out_features.index(self.top_block.in_feature)] - results.extend(self.top_block(top_block_in_feature)) - assert len(self._out_features) == len(results) - return {f: res for f, res in zip(self._out_features, results)} - - -def get_vit_lr_decay_rate(name, lr_decay_rate=1.0, num_layers=12): - """ - Calculate lr decay rate for different ViT blocks. - Args: - name (string): parameter name. - lr_decay_rate (float): base lr decay rate. - num_layers (int): number of ViT blocks. - - Returns: - lr decay rate for the given parameter. - """ - layer_id = num_layers + 1 - if name.startswith("backbone"): - if ".pos_embed" in name or ".patch_embed" in name: - layer_id = 0 - elif ".blocks." in name and ".residual." not in name: - layer_id = int(name[name.find(".blocks.") :].split(".")[2]) + 1 - - return lr_decay_rate ** (num_layers + 1 - layer_id) diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/meta_arch/dense_detector.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/meta_arch/dense_detector.py deleted file mode 100644 index 33066b6ad3255f61101b4b53687c15fc5d04ddd1..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/modeling/meta_arch/dense_detector.py +++ /dev/null @@ -1,294 +0,0 @@ -import numpy as np -from typing import Dict, List, Optional, Tuple -import torch -from torch import Tensor, nn - -from detectron2.data.detection_utils import convert_image_to_rgb -from detectron2.layers import move_device_like -from detectron2.modeling import Backbone -from detectron2.structures import Boxes, ImageList, Instances -from detectron2.utils.events import get_event_storage - -from ..postprocessing import detector_postprocess - - -def permute_to_N_HWA_K(tensor, K: int): - """ - Transpose/reshape a tensor from (N, (Ai x K), H, W) to (N, (HxWxAi), K) - """ - assert tensor.dim() == 4, tensor.shape - N, _, H, W = tensor.shape - tensor = tensor.view(N, -1, K, H, W) - tensor = tensor.permute(0, 3, 4, 1, 2) - tensor = tensor.reshape(N, -1, K) # Size=(N,HWA,K) - return tensor - - -class DenseDetector(nn.Module): - """ - Base class for dense detector. We define a dense detector as a fully-convolutional model that - makes per-pixel (i.e. dense) predictions. - """ - - def __init__( - self, - backbone: Backbone, - head: nn.Module, - head_in_features: Optional[List[str]] = None, - *, - pixel_mean, - pixel_std, - ): - """ - Args: - backbone: backbone module - head: head module - head_in_features: backbone features to use in head. Default to all backbone features. - pixel_mean (Tuple[float]): - Values to be used for image normalization (BGR order). - To train on images of different number of channels, set different mean & std. - Default values are the mean pixel value from ImageNet: [103.53, 116.28, 123.675] - pixel_std (Tuple[float]): - When using pre-trained models in Detectron1 or any MSRA models, - std has been absorbed into its conv1 weights, so the std needs to be set 1. - Otherwise, you can use [57.375, 57.120, 58.395] (ImageNet std) - """ - super().__init__() - - self.backbone = backbone - self.head = head - if head_in_features is None: - shapes = self.backbone.output_shape() - self.head_in_features = sorted(shapes.keys(), key=lambda x: shapes[x].stride) - else: - self.head_in_features = head_in_features - self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False) - self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False) - - @property - def device(self): - return self.pixel_mean.device - - def _move_to_current_device(self, x): - return move_device_like(x, self.pixel_mean) - - def forward(self, batched_inputs: List[Dict[str, Tensor]]): - """ - Args: - batched_inputs: a list, batched outputs of :class:`DatasetMapper` . - Each item in the list contains the inputs for one image. - For now, each item in the list is a dict that contains: - - * image: Tensor, image in (C, H, W) format. - * instances: Instances - - Other information that's included in the original dicts, such as: - - * "height", "width" (int): the output resolution of the model, used in inference. - See :meth:`postprocess` for details. - - Returns: - In training, dict[str, Tensor]: mapping from a named loss to a tensor storing the - loss. Used during training only. In inference, the standard output format, described - in :doc:`/tutorials/models`. - """ - images = self.preprocess_image(batched_inputs) - features = self.backbone(images.tensor) - features = [features[f] for f in self.head_in_features] - predictions = self.head(features) - - if self.training: - assert not torch.jit.is_scripting(), "Not supported" - assert "instances" in batched_inputs[0], "Instance annotations are missing in training!" - gt_instances = [x["instances"].to(self.device) for x in batched_inputs] - return self.forward_training(images, features, predictions, gt_instances) - else: - results = self.forward_inference(images, features, predictions) - if torch.jit.is_scripting(): - return results - - processed_results = [] - for results_per_image, input_per_image, image_size in zip( - results, batched_inputs, images.image_sizes - ): - height = input_per_image.get("height", image_size[0]) - width = input_per_image.get("width", image_size[1]) - r = detector_postprocess(results_per_image, height, width) - processed_results.append({"instances": r}) - return processed_results - - def forward_training(self, images, features, predictions, gt_instances): - raise NotImplementedError() - - def preprocess_image(self, batched_inputs: List[Dict[str, Tensor]]): - """ - Normalize, pad and batch the input images. - """ - images = [self._move_to_current_device(x["image"]) for x in batched_inputs] - images = [(x - self.pixel_mean) / self.pixel_std for x in images] - images = ImageList.from_tensors( - images, - self.backbone.size_divisibility, - padding_constraints=self.backbone.padding_constraints, - ) - return images - - def _transpose_dense_predictions( - self, predictions: List[List[Tensor]], dims_per_anchor: List[int] - ) -> List[List[Tensor]]: - """ - Transpose the dense per-level predictions. - - Args: - predictions: a list of outputs, each is a list of per-level - predictions with shape (N, Ai x K, Hi, Wi), where N is the - number of images, Ai is the number of anchors per location on - level i, K is the dimension of predictions per anchor. - dims_per_anchor: the value of K for each predictions. e.g. 4 for - box prediction, #classes for classification prediction. - - Returns: - List[List[Tensor]]: each prediction is transposed to (N, Hi x Wi x Ai, K). - """ - assert len(predictions) == len(dims_per_anchor) - res: List[List[Tensor]] = [] - for pred, dim_per_anchor in zip(predictions, dims_per_anchor): - pred = [permute_to_N_HWA_K(x, dim_per_anchor) for x in pred] - res.append(pred) - return res - - def _ema_update(self, name: str, value: float, initial_value: float, momentum: float = 0.9): - """ - Apply EMA update to `self.name` using `value`. - - This is mainly used for loss normalizer. In Detectron1, loss is normalized by number - of foreground samples in the batch. When batch size is 1 per GPU, #foreground has a - large variance and using it lead to lower performance. Therefore we maintain an EMA of - #foreground to stabilize the normalizer. - - Args: - name: name of the normalizer - value: the new value to update - initial_value: the initial value to start with - momentum: momentum of EMA - - Returns: - float: the updated EMA value - """ - if hasattr(self, name): - old = getattr(self, name) - else: - old = initial_value - new = old * momentum + value * (1 - momentum) - setattr(self, name, new) - return new - - def _decode_per_level_predictions( - self, - anchors: Boxes, - pred_scores: Tensor, - pred_deltas: Tensor, - score_thresh: float, - topk_candidates: int, - image_size: Tuple[int, int], - ) -> Instances: - """ - Decode boxes and classification predictions of one featuer level, by - the following steps: - 1. filter the predictions based on score threshold and top K scores. - 2. transform the box regression outputs - 3. return the predicted scores, classes and boxes - - Args: - anchors: Boxes, anchor for this feature level - pred_scores: HxWxA,K - pred_deltas: HxWxA,4 - - Returns: - Instances: with field "scores", "pred_boxes", "pred_classes". - """ - # Apply two filtering to make NMS faster. - # 1. Keep boxes with confidence score higher than threshold - keep_idxs = pred_scores > score_thresh - pred_scores = pred_scores[keep_idxs] - topk_idxs = torch.nonzero(keep_idxs) # Kx2 - - # 2. Keep top k top scoring boxes only - topk_idxs_size = topk_idxs.shape[0] - if isinstance(topk_idxs_size, Tensor): - # It's a tensor in tracing - num_topk = torch.clamp(topk_idxs_size, max=topk_candidates) - else: - num_topk = min(topk_idxs_size, topk_candidates) - pred_scores, idxs = pred_scores.topk(num_topk) - topk_idxs = topk_idxs[idxs] - - anchor_idxs, classes_idxs = topk_idxs.unbind(dim=1) - - pred_boxes = self.box2box_transform.apply_deltas( - pred_deltas[anchor_idxs], anchors.tensor[anchor_idxs] - ) - return Instances( - image_size, pred_boxes=Boxes(pred_boxes), scores=pred_scores, pred_classes=classes_idxs - ) - - def _decode_multi_level_predictions( - self, - anchors: List[Boxes], - pred_scores: List[Tensor], - pred_deltas: List[Tensor], - score_thresh: float, - topk_candidates: int, - image_size: Tuple[int, int], - ) -> Instances: - """ - Run `_decode_per_level_predictions` for all feature levels and concat the results. - """ - predictions = [ - self._decode_per_level_predictions( - anchors_i, - box_cls_i, - box_reg_i, - self.test_score_thresh, - self.test_topk_candidates, - image_size, - ) - # Iterate over every feature level - for box_cls_i, box_reg_i, anchors_i in zip(pred_scores, pred_deltas, anchors) - ] - return predictions[0].cat(predictions) # 'Instances.cat' is not scriptale but this is - - def visualize_training(self, batched_inputs, results): - """ - A function used to visualize ground truth images and final network predictions. - It shows ground truth bounding boxes on the original image and up to 20 - predicted object bounding boxes on the original image. - - Args: - batched_inputs (list): a list that contains input to the model. - results (List[Instances]): a list of #images elements returned by forward_inference(). - """ - from detectron2.utils.visualizer import Visualizer - - assert len(batched_inputs) == len( - results - ), "Cannot visualize inputs and results of different sizes" - storage = get_event_storage() - max_boxes = 20 - - image_index = 0 # only visualize a single image - img = batched_inputs[image_index]["image"] - img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format) - v_gt = Visualizer(img, None) - v_gt = v_gt.overlay_instances(boxes=batched_inputs[image_index]["instances"].gt_boxes) - anno_img = v_gt.get_image() - processed_results = detector_postprocess(results[image_index], img.shape[0], img.shape[1]) - predicted_boxes = processed_results.pred_boxes.tensor.detach().cpu().numpy() - - v_pred = Visualizer(img, None) - v_pred = v_pred.overlay_instances(boxes=predicted_boxes[0:max_boxes]) - prop_img = v_pred.get_image() - vis_img = np.vstack((anno_img, prop_img)) - vis_img = vis_img.transpose(2, 0, 1) - vis_name = f"Top: GT bounding boxes; Bottom: {max_boxes} Highest Scoring Results" - storage.put_image(vis_name, vis_img) diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/densepose/modeling/roi_heads/deeplab.py b/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/densepose/modeling/roi_heads/deeplab.py deleted file mode 100644 index 4e5cb483037b302ff1fb2c305275a65e4ba4e941..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/densepose/modeling/roi_heads/deeplab.py +++ /dev/null @@ -1,263 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. - -import fvcore.nn.weight_init as weight_init -import torch -from torch import nn -from torch.nn import functional as F - -from detectron2.config import CfgNode -from detectron2.layers import Conv2d - -from .registry import ROI_DENSEPOSE_HEAD_REGISTRY - - -@ROI_DENSEPOSE_HEAD_REGISTRY.register() -class DensePoseDeepLabHead(nn.Module): - """ - DensePose head using DeepLabV3 model from - "Rethinking Atrous Convolution for Semantic Image Segmentation" - . - """ - - def __init__(self, cfg: CfgNode, input_channels: int): - super(DensePoseDeepLabHead, self).__init__() - # fmt: off - hidden_dim = cfg.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_DIM - kernel_size = cfg.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_KERNEL - norm = cfg.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB.NORM - self.n_stacked_convs = cfg.MODEL.ROI_DENSEPOSE_HEAD.NUM_STACKED_CONVS - self.use_nonlocal = cfg.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB.NONLOCAL_ON - # fmt: on - pad_size = kernel_size // 2 - n_channels = input_channels - - self.ASPP = ASPP(input_channels, [6, 12, 56], n_channels) # 6, 12, 56 - self.add_module("ASPP", self.ASPP) - - if self.use_nonlocal: - self.NLBlock = NONLocalBlock2D(input_channels, bn_layer=True) - self.add_module("NLBlock", self.NLBlock) - # weight_init.c2_msra_fill(self.ASPP) - - for i in range(self.n_stacked_convs): - norm_module = nn.GroupNorm(32, hidden_dim) if norm == "GN" else None - layer = Conv2d( - n_channels, - hidden_dim, - kernel_size, - stride=1, - padding=pad_size, - bias=not norm, - norm=norm_module, - ) - weight_init.c2_msra_fill(layer) - n_channels = hidden_dim - layer_name = self._get_layer_name(i) - self.add_module(layer_name, layer) - self.n_out_channels = hidden_dim - # initialize_module_params(self) - - def forward(self, features): - x0 = features - x = self.ASPP(x0) - if self.use_nonlocal: - x = self.NLBlock(x) - output = x - for i in range(self.n_stacked_convs): - layer_name = self._get_layer_name(i) - x = getattr(self, layer_name)(x) - x = F.relu(x) - output = x - return output - - def _get_layer_name(self, i: int): - layer_name = "body_conv_fcn{}".format(i + 1) - return layer_name - - -# Copied from -# https://github.com/pytorch/vision/blob/master/torchvision/models/segmentation/deeplabv3.py -# See https://arxiv.org/pdf/1706.05587.pdf for details -class ASPPConv(nn.Sequential): - def __init__(self, in_channels, out_channels, dilation): - modules = [ - nn.Conv2d( - in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False - ), - nn.GroupNorm(32, out_channels), - nn.ReLU(), - ] - super(ASPPConv, self).__init__(*modules) - - -class ASPPPooling(nn.Sequential): - def __init__(self, in_channels, out_channels): - super(ASPPPooling, self).__init__( - nn.AdaptiveAvgPool2d(1), - nn.Conv2d(in_channels, out_channels, 1, bias=False), - nn.GroupNorm(32, out_channels), - nn.ReLU(), - ) - - def forward(self, x): - size = x.shape[-2:] - x = super(ASPPPooling, self).forward(x) - return F.interpolate(x, size=size, mode="bilinear", align_corners=False) - - -class ASPP(nn.Module): - def __init__(self, in_channels, atrous_rates, out_channels): - super(ASPP, self).__init__() - modules = [] - modules.append( - nn.Sequential( - nn.Conv2d(in_channels, out_channels, 1, bias=False), - nn.GroupNorm(32, out_channels), - nn.ReLU(), - ) - ) - - rate1, rate2, rate3 = tuple(atrous_rates) - modules.append(ASPPConv(in_channels, out_channels, rate1)) - modules.append(ASPPConv(in_channels, out_channels, rate2)) - modules.append(ASPPConv(in_channels, out_channels, rate3)) - modules.append(ASPPPooling(in_channels, out_channels)) - - self.convs = nn.ModuleList(modules) - - self.project = nn.Sequential( - nn.Conv2d(5 * out_channels, out_channels, 1, bias=False), - # nn.BatchNorm2d(out_channels), - nn.ReLU() - # nn.Dropout(0.5) - ) - - def forward(self, x): - res = [] - for conv in self.convs: - res.append(conv(x)) - res = torch.cat(res, dim=1) - return self.project(res) - - -# copied from -# https://github.com/AlexHex7/Non-local_pytorch/blob/master/lib/non_local_embedded_gaussian.py -# See https://arxiv.org/abs/1711.07971 for details -class _NonLocalBlockND(nn.Module): - def __init__( - self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True - ): - super(_NonLocalBlockND, self).__init__() - - assert dimension in [1, 2, 3] - - self.dimension = dimension - self.sub_sample = sub_sample - - self.in_channels = in_channels - self.inter_channels = inter_channels - - if self.inter_channels is None: - self.inter_channels = in_channels // 2 - if self.inter_channels == 0: - self.inter_channels = 1 - - if dimension == 3: - conv_nd = nn.Conv3d - max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) - bn = nn.GroupNorm # (32, hidden_dim) #nn.BatchNorm3d - elif dimension == 2: - conv_nd = nn.Conv2d - max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) - bn = nn.GroupNorm # (32, hidden_dim)nn.BatchNorm2d - else: - conv_nd = nn.Conv1d - max_pool_layer = nn.MaxPool1d(kernel_size=2) - bn = nn.GroupNorm # (32, hidden_dim)nn.BatchNorm1d - - self.g = conv_nd( - in_channels=self.in_channels, - out_channels=self.inter_channels, - kernel_size=1, - stride=1, - padding=0, - ) - - if bn_layer: - self.W = nn.Sequential( - conv_nd( - in_channels=self.inter_channels, - out_channels=self.in_channels, - kernel_size=1, - stride=1, - padding=0, - ), - bn(32, self.in_channels), - ) - nn.init.constant_(self.W[1].weight, 0) - nn.init.constant_(self.W[1].bias, 0) - else: - self.W = conv_nd( - in_channels=self.inter_channels, - out_channels=self.in_channels, - kernel_size=1, - stride=1, - padding=0, - ) - nn.init.constant_(self.W.weight, 0) - nn.init.constant_(self.W.bias, 0) - - self.theta = conv_nd( - in_channels=self.in_channels, - out_channels=self.inter_channels, - kernel_size=1, - stride=1, - padding=0, - ) - self.phi = conv_nd( - in_channels=self.in_channels, - out_channels=self.inter_channels, - kernel_size=1, - stride=1, - padding=0, - ) - - if sub_sample: - self.g = nn.Sequential(self.g, max_pool_layer) - self.phi = nn.Sequential(self.phi, max_pool_layer) - - def forward(self, x): - """ - :param x: (b, c, t, h, w) - :return: - """ - - batch_size = x.size(0) - - g_x = self.g(x).view(batch_size, self.inter_channels, -1) - g_x = g_x.permute(0, 2, 1) - - theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) - theta_x = theta_x.permute(0, 2, 1) - phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) - f = torch.matmul(theta_x, phi_x) - f_div_C = F.softmax(f, dim=-1) - - y = torch.matmul(f_div_C, g_x) - y = y.permute(0, 2, 1).contiguous() - y = y.view(batch_size, self.inter_channels, *x.size()[2:]) - W_y = self.W(y) - z = W_y + x - - return z - - -class NONLocalBlock2D(_NonLocalBlockND): - def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): - super(NONLocalBlock2D, self).__init__( - in_channels, - inter_channels=inter_channels, - dimension=2, - sub_sample=sub_sample, - bn_layer=bn_layer, - ) diff --git a/spaces/bryanmildort/stockpricepredict/app.py b/spaces/bryanmildort/stockpricepredict/app.py deleted file mode 100644 index 534d01a0ea97aeea5e0b7efbc18abc43e1a7e292..0000000000000000000000000000000000000000 --- a/spaces/bryanmildort/stockpricepredict/app.py +++ /dev/null @@ -1,91 +0,0 @@ -import streamlit as st -import pandas as pd -import numpy as np -from pandas_datareader import data -from datetime import date, datetime -from sklearn.model_selection import train_test_split -from sklearn.metrics import r2_score - -def dateArrange(data): - dates = data['Date'].to_list() - epochDates = [] - for i in dates: - date_time = np.datetime64(i).astype(datetime) - splitDate = date_time.strftime("%Y-%#m-%d").split('-') - epochDate = datetime(int(splitDate[0]),int(splitDate[1]),int(splitDate[2]),0,0).timestamp() - epochDates.append(epochDate) - data['Date'] = epochDates - -def dataScraper(ticker): - startdate = '2012-01-01' - today = date.today().strftime("%Y-%m-%d") - enddate = today - try: - panel_data = data.DataReader(ticker, 'yahoo', startdate, enddate).reset_index() - price_close = panel_data['Adj Close'] - price_20dma = price_close.rolling(window=20).mean().to_list()[100:] # 20 Day Moving Average - price_50dma = price_close.rolling(window=50).mean().to_list()[100:] # 50 day - price_100dma = price_close.rolling(window=100).mean().to_list()[100:] # 100 day - panel_data = panel_data.iloc[100: , :] - panel_data['20dma'] = price_20dma - panel_data['50dma'] = price_50dma - panel_data['100dma'] = price_100dma - dateArrange(panel_data) - return panel_data - except: - print("Error while scraping data") - return - -def predictor(stock_ticker): - prediction_list = [] - stock_data = dataScraper(stock_ticker) - try: - stock_data.iat[0,0] - except: - print('Error with stock data') - return - from sklearn.linear_model import Lasso - alpha = 1.0 - tol = 0.0008 - max_iter = 10000 - lasso = Lasso(alpha=alpha, max_iter=max_iter, tol=tol) - test_size = 0.1 - print('\nModel = ' + str(lasso)) - print('\n~ ' + stock_ticker.upper() + ' Next Day Price Predictions ~\n') - X = stock_data.iloc[:-1 , :] - y = { - 'High' : stock_data.iloc[1: , :]['High'], - 'Low' : stock_data.iloc[1: , :]['Low'], - 'Close (Adjusted)': stock_data.iloc[1: , :]['Close'] - } - sample = stock_data.iloc[-1:, :] - for i in y: - X_train, X_test, y_train, y_test = train_test_split(X, y[i], test_size=test_size) - y_pred_lasso = lasso.fit(np.array(X_train), np.array(y_train)) - r2_score_lasso = r2_score(np.array(y_test), y_pred_lasso.predict(np.array(X_test))) - prediction = y_pred_lasso.predict(np.array(sample)) - prediction_list.append(prediction) - output = "
    " + i + ' - ' + str(prediction) + '\n' + "
    " - st.markdown(output, unsafe_allow_html=True) - prediction_list.append(lasso) - prediction_list.append(r2_score_lasso) - r2score = 'R2 = ' + str(r2_score_lasso) - print(r2score) - -st.markdown("

    Stock Price Predictor v2.0

    ", unsafe_allow_html=True) -st.markdown("
    by Bryan Mildort
    ", unsafe_allow_html=True) -ticker = st.text_input('Enter Ticker to Scrape:', placeholder='SPY') -col1, col2, col3, col4, col5 = st.columns(5) -with col1: - st.write(' ') -with col2: - st.write(' ') -with col3: - if st.button('Scrape!'): - predictor(ticker) -with col4: - st.write(' ') -with col5: - st.write(' ') - - diff --git a/spaces/cancanasoyak/CropBased-TissueMasking/README.md b/spaces/cancanasoyak/CropBased-TissueMasking/README.md deleted file mode 100644 index c50d63f9de5d2579fbbc4f8a542145b0085adc4d..0000000000000000000000000000000000000000 --- a/spaces/cancanasoyak/CropBased-TissueMasking/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: CropBased TissueMasking -emoji: 🏃 -colorFrom: pink -colorTo: blue -sdk: streamlit -sdk_version: 1.28.0 -app_file: Deployment/webapp.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/DensePose/densepose/structures/chart_result.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/DensePose/densepose/structures/chart_result.py deleted file mode 100644 index 003933d03d153d045c0bf551c465bc7a224d90cb..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/DensePose/densepose/structures/chart_result.py +++ /dev/null @@ -1,183 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. - -from dataclasses import dataclass -from typing import Any, Optional, Tuple -import torch - - -@dataclass -class DensePoseChartResult: - """ - DensePose results for chart-based methods represented by labels and inner - coordinates (U, V) of individual charts. Each chart is a 2D manifold - that has an associated label and is parameterized by two coordinates U and V. - Both U and V take values in [0, 1]. - Thus the results are represented by two tensors: - - labels (tensor [H, W] of long): contains estimated label for each pixel of - the detection bounding box of size (H, W) - - uv (tensor [2, H, W] of float): contains estimated U and V coordinates - for each pixel of the detection bounding box of size (H, W) - """ - - labels: torch.Tensor - uv: torch.Tensor - - def to(self, device: torch.device): - """ - Transfers all tensors to the given device - """ - labels = self.labels.to(device) - uv = self.uv.to(device) - return DensePoseChartResult(labels=labels, uv=uv) - - -@dataclass -class DensePoseChartResultWithConfidences: - """ - We add confidence values to DensePoseChartResult - Thus the results are represented by two tensors: - - labels (tensor [H, W] of long): contains estimated label for each pixel of - the detection bounding box of size (H, W) - - uv (tensor [2, H, W] of float): contains estimated U and V coordinates - for each pixel of the detection bounding box of size (H, W) - Plus one [H, W] tensor of float for each confidence type - """ - - labels: torch.Tensor - uv: torch.Tensor - sigma_1: Optional[torch.Tensor] = None - sigma_2: Optional[torch.Tensor] = None - kappa_u: Optional[torch.Tensor] = None - kappa_v: Optional[torch.Tensor] = None - fine_segm_confidence: Optional[torch.Tensor] = None - coarse_segm_confidence: Optional[torch.Tensor] = None - - def to(self, device: torch.device): - """ - Transfers all tensors to the given device, except if their value is None - """ - - def to_device_if_tensor(var: Any): - if isinstance(var, torch.Tensor): - return var.to(device) - return var - - return DensePoseChartResultWithConfidences( - labels=self.labels.to(device), - uv=self.uv.to(device), - sigma_1=to_device_if_tensor(self.sigma_1), - sigma_2=to_device_if_tensor(self.sigma_2), - kappa_u=to_device_if_tensor(self.kappa_u), - kappa_v=to_device_if_tensor(self.kappa_v), - fine_segm_confidence=to_device_if_tensor(self.fine_segm_confidence), - coarse_segm_confidence=to_device_if_tensor(self.coarse_segm_confidence), - ) - - -@dataclass -class DensePoseChartResultQuantized: - """ - DensePose results for chart-based methods represented by labels and quantized - inner coordinates (U, V) of individual charts. Each chart is a 2D manifold - that has an associated label and is parameterized by two coordinates U and V. - Both U and V take values in [0, 1]. - Quantized coordinates Uq and Vq have uint8 values which are obtained as: - Uq = U * 255 (hence 0 <= Uq <= 255) - Vq = V * 255 (hence 0 <= Vq <= 255) - Thus the results are represented by one tensor: - - labels_uv_uint8 (tensor [3, H, W] of uint8): contains estimated label - and quantized coordinates Uq and Vq for each pixel of the detection - bounding box of size (H, W) - """ - - labels_uv_uint8: torch.Tensor - - def to(self, device: torch.device): - """ - Transfers all tensors to the given device - """ - labels_uv_uint8 = self.labels_uv_uint8.to(device) - return DensePoseChartResultQuantized(labels_uv_uint8=labels_uv_uint8) - - -@dataclass -class DensePoseChartResultCompressed: - """ - DensePose results for chart-based methods represented by a PNG-encoded string. - The tensor of quantized DensePose results of size [3, H, W] is considered - as an image with 3 color channels. PNG compression is applied and the result - is stored as a Base64-encoded string. The following attributes are defined: - - shape_chw (tuple of 3 int): contains shape of the result tensor - (number of channels, height, width) - - labels_uv_str (str): contains Base64-encoded results tensor of size - [3, H, W] compressed with PNG compression methods - """ - - shape_chw: Tuple[int, int, int] - labels_uv_str: str - - -def quantize_densepose_chart_result(result: DensePoseChartResult) -> DensePoseChartResultQuantized: - """ - Applies quantization to DensePose chart-based result. - - Args: - result (DensePoseChartResult): DensePose chart-based result - Return: - Quantized DensePose chart-based result (DensePoseChartResultQuantized) - """ - h, w = result.labels.shape - labels_uv_uint8 = torch.zeros([3, h, w], dtype=torch.uint8, device=result.labels.device) - labels_uv_uint8[0] = result.labels - labels_uv_uint8[1:] = (result.uv * 255).clamp(0, 255).byte() - return DensePoseChartResultQuantized(labels_uv_uint8=labels_uv_uint8) - - -def compress_quantized_densepose_chart_result( - result: DensePoseChartResultQuantized, -) -> DensePoseChartResultCompressed: - """ - Compresses quantized DensePose chart-based result - - Args: - result (DensePoseChartResultQuantized): quantized DensePose chart-based result - Return: - Compressed DensePose chart-based result (DensePoseChartResultCompressed) - """ - import base64 - import numpy as np - from io import BytesIO - from PIL import Image - - labels_uv_uint8_np_chw = result.labels_uv_uint8.cpu().numpy() - labels_uv_uint8_np_hwc = np.moveaxis(labels_uv_uint8_np_chw, 0, -1) - im = Image.fromarray(labels_uv_uint8_np_hwc) - fstream = BytesIO() - im.save(fstream, format="png", optimize=True) - labels_uv_str = base64.encodebytes(fstream.getvalue()).decode() - shape_chw = labels_uv_uint8_np_chw.shape - return DensePoseChartResultCompressed(labels_uv_str=labels_uv_str, shape_chw=shape_chw) - - -def decompress_compressed_densepose_chart_result( - result: DensePoseChartResultCompressed, -) -> DensePoseChartResultQuantized: - """ - Decompresses DensePose chart-based result encoded into a base64 string - - Args: - result (DensePoseChartResultCompressed): compressed DensePose chart result - Return: - Quantized DensePose chart-based result (DensePoseChartResultQuantized) - """ - import base64 - import numpy as np - from io import BytesIO - from PIL import Image - - fstream = BytesIO(base64.decodebytes(result.labels_uv_str.encode())) - im = Image.open(fstream) - labels_uv_uint8_np_chw = np.moveaxis(np.array(im, dtype=np.uint8), -1, 0) - return DensePoseChartResultQuantized( - labels_uv_uint8=torch.from_numpy(labels_uv_uint8_np_chw.reshape(result.shape_chw)) - ) diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/ViTDet/configs/LVIS/cascade_mask_rcnn_swin_l_in21k_50ep.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/ViTDet/configs/LVIS/cascade_mask_rcnn_swin_l_in21k_50ep.py deleted file mode 100644 index 9e22e3b28777003776774f61273c04bbb2abea1e..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/projects/ViTDet/configs/LVIS/cascade_mask_rcnn_swin_l_in21k_50ep.py +++ /dev/null @@ -1,12 +0,0 @@ -from .cascade_mask_rcnn_swin_b_in21k_50ep import ( - dataloader, - lr_multiplier, - model, - train, - optimizer, -) - -model.backbone.bottom_up.embed_dim = 192 -model.backbone.bottom_up.num_heads = [6, 12, 24, 48] - -train.init_checkpoint = "detectron2://ImageNetPretrained/swin/swin_large_patch4_window7_224_22k.pth" diff --git a/spaces/ceckenrode/AI-Dashboard-03142023/index.html b/spaces/ceckenrode/AI-Dashboard-03142023/index.html deleted file mode 100644 index 744a752c14a0d9057aaf1d1fa969cc9de581e78b..0000000000000000000000000000000000000000 --- a/spaces/ceckenrode/AI-Dashboard-03142023/index.html +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - My static Space - - - - - - - - - - - - - - - - - -
    - journey - title Create AI - section Training - Format DataSet Inputs Files, Data Splits: 5: Teacher - Model Build w/ SKLearn, TF, Pytorch: 3: Student - Determine Model Performance: 1: Teacher, Student - section Deploy - Web Deploy Local and Cloud: 5: Teacher - Architecture Spaces Gradio Streamlit Heroku AWS Azure and GCCP: 5: Teacher - section Testing - Test Model with Input Datasets: 5: Teacher - Examples. Inputs that Work, Inputs That Break Model: 5: Teacher - Governance - Analyze, Publish Fairness, Equity, Bias for Datasets and Outputs: 5: Teacher -
    - -
    - sequenceDiagram - participant Alice - participant Bob - Alice->>John: Hello John, how are you? - loop Healthcheck - John->>John: Fight against hypochondria - end - Note right of John: Rational thoughts
    prevail... - John-->>Alice: Great! - John->>Bob: How about you? - Bob-->>John: Jolly good! -
    - -
    -

    Welcome to the Mermaid Modeler Tip Sheet

    -

    - You can use Mermaid inside HTML5 by including the script and a div with the class or mermaid. -

    -

    - Documentation is located here: - Mermaid documentation. -

    -
    - - - \ No newline at end of file diff --git a/spaces/chansung/zero2story/interfaces/export_ui.py b/spaces/chansung/zero2story/interfaces/export_ui.py deleted file mode 100644 index d5072162acd6cea697a9f8346a139c664603e19d..0000000000000000000000000000000000000000 --- a/spaces/chansung/zero2story/interfaces/export_ui.py +++ /dev/null @@ -1,56 +0,0 @@ -import gradio as gr -from templates import parser -from interfaces import utils -from modules.llms import get_llm_factory - -template_file = "templates/basic.jinja" - -async def title_gen(cursors, llm_type="PaLM"): - stories = "" - for cursor in cursors: - stories = stories + cursor["story"] - - factory = get_llm_factory(llm_type) - prompts = factory.create_prompt_manager().prompts - llm_service = factory.create_llm_service() - - prompt = prompts['story_gen']['title'].format(stories=stories) - - parameters = llm_service.make_params(mode="text", temperature=0.7, top_k=40, top_p=1.0, max_output_tokens=4096) - _, title = await llm_service.gen_text(prompt, mode="text", parameters=parameters) - return title - -def export( - title, cursors, - main_char_img, main_char_name, main_char_age, main_char_personality, main_char_job, - side_char_enable1, side_char_img1, side_char_name1, side_char_age1, side_char_personality1, side_char_job1, - side_char_enable2, side_char_img2, side_char_name2, side_char_age2, side_char_personality2, side_char_job2, - side_char_enable3, side_char_img3, side_char_name3, side_char_age3, side_char_personality3, side_char_job3, -): - print(main_char_img) - characters = [ - { - 'img': main_char_img, - 'name': main_char_name, - } - ] - utils.add_side_character_to_export( - characters, side_char_enable1, side_char_img1, side_char_name1, side_char_age1, side_char_personality1, side_char_job1 - ) - utils.add_side_character_to_export( - characters, side_char_enable2, side_char_img2, side_char_name2, side_char_age2, side_char_personality2, side_char_job2 - ) - utils.add_side_character_to_export( - characters, side_char_enable3, side_char_img3, side_char_name3, side_char_age3, side_char_personality3, side_char_job3 - ) - - html_as_string = parser.gen_from_file( - template_file, - kwargs={ - "title": title, - "characters": characters, - "items": cursors - } - ) - - return html_as_string diff --git a/spaces/chasemcdo/hf_localai/examples/flowise/README.md b/spaces/chasemcdo/hf_localai/examples/flowise/README.md deleted file mode 100644 index 9dbac9108b838c77b423e1927b7c96e5e8cf1b49..0000000000000000000000000000000000000000 --- a/spaces/chasemcdo/hf_localai/examples/flowise/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# flowise - -Example of integration with [FlowiseAI/Flowise](https://github.com/FlowiseAI/Flowise). - -![Screenshot from 2023-05-30 18-01-03](https://github.com/go-skynet/LocalAI/assets/2420543/02458782-0549-4131-971c-95ee56ec1af8) - -You can check a demo video in the Flowise PR: https://github.com/FlowiseAI/Flowise/pull/123 - -## Run - -In this example LocalAI will download the gpt4all model and set it up as "gpt-3.5-turbo". See the `docker-compose.yaml` -```bash -# Clone LocalAI -git clone https://github.com/go-skynet/LocalAI - -cd LocalAI/examples/flowise - -# start with docker-compose -docker-compose up --pull always - -``` - -## Accessing flowise - -Open http://localhost:3000. - -## Using LocalAI - -Search for LocalAI in the integration, and use the `http://api:8080/` as URL. - diff --git a/spaces/chenxx/ChuanhuChatGPT/llama_func.py b/spaces/chenxx/ChuanhuChatGPT/llama_func.py deleted file mode 100644 index c71027dd4e6f99c0c12626cbbf276f407877be04..0000000000000000000000000000000000000000 --- a/spaces/chenxx/ChuanhuChatGPT/llama_func.py +++ /dev/null @@ -1,192 +0,0 @@ -import os -import logging - -from llama_index import GPTSimpleVectorIndex -from llama_index import download_loader -from llama_index import ( - Document, - LLMPredictor, - PromptHelper, - QuestionAnswerPrompt, - RefinePrompt, -) -from langchain.llms import OpenAI -import colorama - - -from presets import * -from utils import * - - -def get_documents(file_src): - documents = [] - index_name = "" - logging.debug("Loading documents...") - logging.debug(f"file_src: {file_src}") - for file in file_src: - logging.debug(f"file: {file.name}") - index_name += file.name - if os.path.splitext(file.name)[1] == ".pdf": - logging.debug("Loading PDF...") - CJKPDFReader = download_loader("CJKPDFReader") - loader = CJKPDFReader() - documents += loader.load_data(file=file.name) - elif os.path.splitext(file.name)[1] == ".docx": - logging.debug("Loading DOCX...") - DocxReader = download_loader("DocxReader") - loader = DocxReader() - documents += loader.load_data(file=file.name) - elif os.path.splitext(file.name)[1] == ".epub": - logging.debug("Loading EPUB...") - EpubReader = download_loader("EpubReader") - loader = EpubReader() - documents += loader.load_data(file=file.name) - else: - logging.debug("Loading text file...") - with open(file.name, "r", encoding="utf-8") as f: - text = add_space(f.read()) - documents += [Document(text)] - index_name = sha1sum(index_name) - return documents, index_name - - -def construct_index( - api_key, - file_src, - max_input_size=4096, - num_outputs=1, - max_chunk_overlap=20, - chunk_size_limit=600, - embedding_limit=None, - separator=" ", - num_children=10, - max_keywords_per_chunk=10, -): - os.environ["OPENAI_API_KEY"] = api_key - chunk_size_limit = None if chunk_size_limit == 0 else chunk_size_limit - embedding_limit = None if embedding_limit == 0 else embedding_limit - separator = " " if separator == "" else separator - - llm_predictor = LLMPredictor( - llm=OpenAI(model_name="gpt-3.5-turbo-0301", openai_api_key=api_key) - ) - prompt_helper = PromptHelper( - max_input_size, - num_outputs, - max_chunk_overlap, - embedding_limit, - chunk_size_limit, - separator=separator, - ) - documents, index_name = get_documents(file_src) - if os.path.exists(f"./index/{index_name}.json"): - logging.info("找到了缓存的索引文件,加载中……") - return GPTSimpleVectorIndex.load_from_disk(f"./index/{index_name}.json") - else: - try: - logging.debug("构建索引中……") - index = GPTSimpleVectorIndex( - documents, llm_predictor=llm_predictor, prompt_helper=prompt_helper - ) - os.makedirs("./index", exist_ok=True) - index.save_to_disk(f"./index/{index_name}.json") - return index - except Exception as e: - print(e) - return None - - -def chat_ai( - api_key, - index, - question, - context, - chatbot, -): - os.environ["OPENAI_API_KEY"] = api_key - - logging.info(f"Question: {question}") - - response, chatbot_display, status_text = ask_ai( - api_key, - index, - question, - replace_today(PROMPT_TEMPLATE), - REFINE_TEMPLATE, - SIM_K, - INDEX_QUERY_TEMPRATURE, - context, - ) - if response is None: - status_text = "查询失败,请换个问法试试" - return context, chatbot - response = response - - context.append({"role": "user", "content": question}) - context.append({"role": "assistant", "content": response}) - chatbot.append((question, chatbot_display)) - - os.environ["OPENAI_API_KEY"] = "" - return context, chatbot, status_text - - -def ask_ai( - api_key, - index, - question, - prompt_tmpl, - refine_tmpl, - sim_k=1, - temprature=0, - prefix_messages=[], -): - os.environ["OPENAI_API_KEY"] = api_key - - logging.debug("Index file found") - logging.debug("Querying index...") - llm_predictor = LLMPredictor( - llm=OpenAI( - temperature=temprature, - model_name="gpt-3.5-turbo-0301", - prefix_messages=prefix_messages, - ) - ) - - response = None # Initialize response variable to avoid UnboundLocalError - qa_prompt = QuestionAnswerPrompt(prompt_tmpl) - rf_prompt = RefinePrompt(refine_tmpl) - response = index.query( - question, - llm_predictor=llm_predictor, - similarity_top_k=sim_k, - text_qa_template=qa_prompt, - refine_template=rf_prompt, - response_mode="compact", - ) - - if response is not None: - logging.info(f"Response: {response}") - ret_text = response.response - nodes = [] - for index, node in enumerate(response.source_nodes): - brief = node.source_text[:25].replace("\n", "") - nodes.append( - f"
    [{index+1}]\t{brief}...

    {node.source_text}

    " - ) - new_response = ret_text + "\n----------\n" + "\n\n".join(nodes) - logging.info( - f"Response: {colorama.Fore.BLUE}{ret_text}{colorama.Style.RESET_ALL}" - ) - os.environ["OPENAI_API_KEY"] = "" - return ret_text, new_response, f"查询消耗了{llm_predictor.last_token_usage} tokens" - else: - logging.warning("No response found, returning None") - os.environ["OPENAI_API_KEY"] = "" - return None - - -def add_space(text): - punctuations = {",": ", ", "。": "。 ", "?": "? ", "!": "! ", ":": ": ", ";": "; "} - for cn_punc, en_punc in punctuations.items(): - text = text.replace(cn_punc, en_punc) - return text diff --git a/spaces/chronopt-research/ViTExCo/src/data/transforms.py b/spaces/chronopt-research/ViTExCo/src/data/transforms.py deleted file mode 100644 index aafd87a4cfad80c2ea0729257ce8d98fe0b9b423..0000000000000000000000000000000000000000 --- a/spaces/chronopt-research/ViTExCo/src/data/transforms.py +++ /dev/null @@ -1,348 +0,0 @@ -from __future__ import division - -import collections -import numbers -import random - -import torch -from PIL import Image -from skimage import color - -import src.data.functional as F - -__all__ = [ - "Compose", - "Concatenate", - "ToTensor", - "Normalize", - "Resize", - "Scale", - "CenterCrop", - "Pad", - "RandomCrop", - "RandomHorizontalFlip", - "RandomVerticalFlip", - "RandomResizedCrop", - "RandomSizedCrop", - "FiveCrop", - "TenCrop", - "RGB2Lab", -] - - -def CustomFunc(inputs, func, *args, **kwargs): - im_l = func(inputs[0], *args, **kwargs) - im_ab = func(inputs[1], *args, **kwargs) - warp_ba = func(inputs[2], *args, **kwargs) - warp_aba = func(inputs[3], *args, **kwargs) - im_gbl_ab = func(inputs[4], *args, **kwargs) - bgr_mc_im = func(inputs[5], *args, **kwargs) - - layer_data = [im_l, im_ab, warp_ba, warp_aba, im_gbl_ab, bgr_mc_im] - - for l in range(5): - layer = inputs[6 + l] - err_ba = func(layer[0], *args, **kwargs) - err_ab = func(layer[1], *args, **kwargs) - - layer_data.append([err_ba, err_ab]) - - return layer_data - - -class Compose(object): - """Composes several transforms together. - - Args: - transforms (list of ``Transform`` objects): list of transforms to compose. - - Example: - >>> transforms.Compose([ - >>> transforms.CenterCrop(10), - >>> transforms.ToTensor(), - >>> ]) - """ - - def __init__(self, transforms): - self.transforms = transforms - - def __call__(self, inputs): - for t in self.transforms: - inputs = t(inputs) - return inputs - - -class Concatenate(object): - """ - Input: [im_l, im_ab, inputs] - inputs = [warp_ba_l, warp_ba_ab, warp_aba, err_pm, err_aba] - - Output:[im_l, err_pm, warp_ba, warp_aba, im_ab, err_aba] - """ - - def __call__(self, inputs): - im_l = inputs[0] - im_ab = inputs[1] - warp_ba = inputs[2] - warp_aba = inputs[3] - im_glb_ab = inputs[4] - bgr_mc_im = inputs[5] - bgr_mc_im = bgr_mc_im[[2, 1, 0], ...] - - err_ba = [] - err_ab = [] - - for l in range(5): - layer = inputs[6 + l] - err_ba.append(layer[0]) - err_ab.append(layer[1]) - - cerr_ba = torch.cat(err_ba, 0) - cerr_ab = torch.cat(err_ab, 0) - - return (im_l, cerr_ba, warp_ba, warp_aba, im_glb_ab, bgr_mc_im, im_ab, cerr_ab) - - -class ToTensor(object): - """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. - - Converts a PIL Image or numpy.ndarray (H x W x C) in the range - [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]. - """ - - def __call__(self, inputs): - """ - Args: - pic (PIL Image or numpy.ndarray): Image to be converted to tensor. - - Returns: - Tensor: Converted image. - """ - return CustomFunc(inputs, F.to_mytensor) - - -class Normalize(object): - """Normalize an tensor image with mean and standard deviation. - Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform - will normalize each channel of the input ``torch.*Tensor`` i.e. - ``input[channel] = (input[channel] - mean[channel]) / std[channel]`` - - Args: - mean (sequence): Sequence of means for each channel. - std (sequence): Sequence of standard deviations for each channel. - """ - - def __call__(self, inputs): - """ - Args: - tensor (Tensor): Tensor image of size (C, H, W) to be normalized. - - Returns: - Tensor: Normalized Tensor image. - """ - - im_l = F.normalize(inputs[0], 50, 1) # [0, 100] - im_ab = F.normalize(inputs[1], (0, 0), (1, 1)) # [-100, 100] - - inputs[2][0:1, :, :] = F.normalize(inputs[2][0:1, :, :], 50, 1) - inputs[2][1:3, :, :] = F.normalize(inputs[2][1:3, :, :], (0, 0), (1, 1)) - warp_ba = inputs[2] - - inputs[3][0:1, :, :] = F.normalize(inputs[3][0:1, :, :], 50, 1) - inputs[3][1:3, :, :] = F.normalize(inputs[3][1:3, :, :], (0, 0), (1, 1)) - warp_aba = inputs[3] - - im_gbl_ab = F.normalize(inputs[4], (0, 0), (1, 1)) # [-100, 100] - - bgr_mc_im = F.normalize(inputs[5], (123.68, 116.78, 103.938), (1, 1, 1)) - - layer_data = [im_l, im_ab, warp_ba, warp_aba, im_gbl_ab, bgr_mc_im] - - for l in range(5): - layer = inputs[6 + l] - err_ba = F.normalize(layer[0], 127, 2) # [0, 255] - err_ab = F.normalize(layer[1], 127, 2) # [0, 255] - layer_data.append([err_ba, err_ab]) - - return layer_data - - -class Resize(object): - """Resize the input PIL Image to the given size. - - Args: - size (sequence or int): Desired output size. If size is a sequence like - (h, w), output size will be matched to this. If size is an int, - smaller edge of the image will be matched to this number. - i.e, if height > width, then image will be rescaled to - (size * height / width, size) - interpolation (int, optional): Desired interpolation. Default is - ``PIL.Image.BILINEAR`` - """ - - def __init__(self, size, interpolation=Image.BILINEAR): - assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2) - self.size = size - self.interpolation = interpolation - - def __call__(self, inputs): - """ - Args: - img (PIL Image): Image to be scaled. - - Returns: - PIL Image: Rescaled image. - """ - return CustomFunc(inputs, F.resize, self.size, self.interpolation) - - -class RandomCrop(object): - """Crop the given PIL Image at a random location. - - Args: - size (sequence or int): Desired output size of the crop. If size is an - int instead of sequence like (h, w), a square crop (size, size) is - made. - padding (int or sequence, optional): Optional padding on each border - of the image. Default is 0, i.e no padding. If a sequence of length - 4 is provided, it is used to pad left, top, right, bottom borders - respectively. - """ - - def __init__(self, size, padding=0): - if isinstance(size, numbers.Number): - self.size = (int(size), int(size)) - else: - self.size = size - self.padding = padding - - @staticmethod - def get_params(img, output_size): - """Get parameters for ``crop`` for a random crop. - - Args: - img (PIL Image): Image to be cropped. - output_size (tuple): Expected output size of the crop. - - Returns: - tuple: params (i, j, h, w) to be passed to ``crop`` for random crop. - """ - w, h = img.size - th, tw = output_size - if w == tw and h == th: - return 0, 0, h, w - - i = random.randint(0, h - th) - j = random.randint(0, w - tw) - return i, j, th, tw - - def __call__(self, inputs): - """ - Args: - img (PIL Image): Image to be cropped. - - Returns: - PIL Image: Cropped image. - """ - if self.padding > 0: - inputs = CustomFunc(inputs, F.pad, self.padding) - - i, j, h, w = self.get_params(inputs[0], self.size) - return CustomFunc(inputs, F.crop, i, j, h, w) - - -class CenterCrop(object): - """Crop the given PIL Image at a random location. - - Args: - size (sequence or int): Desired output size of the crop. If size is an - int instead of sequence like (h, w), a square crop (size, size) is - made. - padding (int or sequence, optional): Optional padding on each border - of the image. Default is 0, i.e no padding. If a sequence of length - 4 is provided, it is used to pad left, top, right, bottom borders - respectively. - """ - - def __init__(self, size, padding=0): - if isinstance(size, numbers.Number): - self.size = (int(size), int(size)) - else: - self.size = size - self.padding = padding - - @staticmethod - def get_params(img, output_size): - """Get parameters for ``crop`` for a random crop. - - Args: - img (PIL Image): Image to be cropped. - output_size (tuple): Expected output size of the crop. - - Returns: - tuple: params (i, j, h, w) to be passed to ``crop`` for random crop. - """ - w, h = img.size - th, tw = output_size - if w == tw and h == th: - return 0, 0, h, w - - i = (h - th) // 2 - j = (w - tw) // 2 - return i, j, th, tw - - def __call__(self, inputs): - """ - Args: - img (PIL Image): Image to be cropped. - - Returns: - PIL Image: Cropped image. - """ - if self.padding > 0: - inputs = CustomFunc(inputs, F.pad, self.padding) - - i, j, h, w = self.get_params(inputs[0], self.size) - return CustomFunc(inputs, F.crop, i, j, h, w) - - -class RandomHorizontalFlip(object): - """Horizontally flip the given PIL Image randomly with a probability of 0.5.""" - - def __call__(self, inputs): - """ - Args: - img (PIL Image): Image to be flipped. - - Returns: - PIL Image: Randomly flipped image. - """ - - if random.random() < 0.5: - return CustomFunc(inputs, F.hflip) - return inputs - - -class RGB2Lab(object): - def __call__(self, inputs): - """ - Args: - img (PIL Image): Image to be flipped. - - Returns: - PIL Image: Randomly flipped image. - """ - - def __call__(self, inputs): - image_lab = color.rgb2lab(inputs[0]) - warp_ba_lab = color.rgb2lab(inputs[2]) - warp_aba_lab = color.rgb2lab(inputs[3]) - im_gbl_lab = color.rgb2lab(inputs[4]) - - inputs[0] = image_lab[:, :, :1] # l channel - inputs[1] = image_lab[:, :, 1:] # ab channel - inputs[2] = warp_ba_lab # lab channel - inputs[3] = warp_aba_lab # lab channel - inputs[4] = im_gbl_lab[:, :, 1:] # ab channel - - return inputs diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cryptography/hazmat/backends/openssl/decode_asn1.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cryptography/hazmat/backends/openssl/decode_asn1.py deleted file mode 100644 index bf123b6285b64a5ac5a64c00c47975ea2285b9dc..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/cryptography/hazmat/backends/openssl/decode_asn1.py +++ /dev/null @@ -1,32 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - -from __future__ import annotations - -from cryptography import x509 - -# CRLReason ::= ENUMERATED { -# unspecified (0), -# keyCompromise (1), -# cACompromise (2), -# affiliationChanged (3), -# superseded (4), -# cessationOfOperation (5), -# certificateHold (6), -# -- value 7 is not used -# removeFromCRL (8), -# privilegeWithdrawn (9), -# aACompromise (10) } -_CRL_ENTRY_REASON_ENUM_TO_CODE = { - x509.ReasonFlags.unspecified: 0, - x509.ReasonFlags.key_compromise: 1, - x509.ReasonFlags.ca_compromise: 2, - x509.ReasonFlags.affiliation_changed: 3, - x509.ReasonFlags.superseded: 4, - x509.ReasonFlags.cessation_of_operation: 5, - x509.ReasonFlags.certificate_hold: 6, - x509.ReasonFlags.remove_from_crl: 8, - x509.ReasonFlags.privilege_withdrawn: 9, - x509.ReasonFlags.aa_compromise: 10, -} diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/filetype/types/isobmff.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/filetype/types/isobmff.py deleted file mode 100644 index 2ac0ffe87aa062319862cacf28e382ae838bbc17..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/filetype/types/isobmff.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import -import codecs - -from .base import Type - - -class IsoBmff(Type): - """ - Implements the ISO-BMFF base type. - """ - def __init__(self, mime, extension): - super(IsoBmff, self).__init__( - mime=mime, - extension=extension - ) - - def _is_isobmff(self, buf): - if len(buf) < 16 or buf[4:8] != b'ftyp': - return False - if len(buf) < int(codecs.encode(buf[0:4], 'hex'), 16): - return False - return True - - def _get_ftyp(self, buf): - ftyp_len = int(codecs.encode(buf[0:4], 'hex'), 16) - major_brand = buf[8:12].decode(errors='ignore') - minor_version = int(codecs.encode(buf[12:16], 'hex'), 16) - compatible_brands = [] - for i in range(16, ftyp_len, 4): - compatible_brands.append(buf[i:i+4].decode(errors='ignore')) - - return major_brand, minor_version, compatible_brands diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/PIL/ImageOps.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/PIL/ImageOps.py deleted file mode 100644 index 17702778c134abcb51d7632367fbbf1a2f3048fa..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/PIL/ImageOps.py +++ /dev/null @@ -1,628 +0,0 @@ -# -# The Python Imaging Library. -# $Id$ -# -# standard image operations -# -# History: -# 2001-10-20 fl Created -# 2001-10-23 fl Added autocontrast operator -# 2001-12-18 fl Added Kevin's fit operator -# 2004-03-14 fl Fixed potential division by zero in equalize -# 2005-05-05 fl Fixed equalize for low number of values -# -# Copyright (c) 2001-2004 by Secret Labs AB -# Copyright (c) 2001-2004 by Fredrik Lundh -# -# See the README file for information on usage and redistribution. -# - -import functools -import operator -import re - -from . import ExifTags, Image, ImagePalette - -# -# helpers - - -def _border(border): - if isinstance(border, tuple): - if len(border) == 2: - left, top = right, bottom = border - elif len(border) == 4: - left, top, right, bottom = border - else: - left = top = right = bottom = border - return left, top, right, bottom - - -def _color(color, mode): - if isinstance(color, str): - from . import ImageColor - - color = ImageColor.getcolor(color, mode) - return color - - -def _lut(image, lut): - if image.mode == "P": - # FIXME: apply to lookup table, not image data - msg = "mode P support coming soon" - raise NotImplementedError(msg) - elif image.mode in ("L", "RGB"): - if image.mode == "RGB" and len(lut) == 256: - lut = lut + lut + lut - return image.point(lut) - else: - msg = "not supported for this image mode" - raise OSError(msg) - - -# -# actions - - -def autocontrast(image, cutoff=0, ignore=None, mask=None, preserve_tone=False): - """ - Maximize (normalize) image contrast. This function calculates a - histogram of the input image (or mask region), removes ``cutoff`` percent of the - lightest and darkest pixels from the histogram, and remaps the image - so that the darkest pixel becomes black (0), and the lightest - becomes white (255). - - :param image: The image to process. - :param cutoff: The percent to cut off from the histogram on the low and - high ends. Either a tuple of (low, high), or a single - number for both. - :param ignore: The background pixel value (use None for no background). - :param mask: Histogram used in contrast operation is computed using pixels - within the mask. If no mask is given the entire image is used - for histogram computation. - :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast. - - .. versionadded:: 8.2.0 - - :return: An image. - """ - if preserve_tone: - histogram = image.convert("L").histogram(mask) - else: - histogram = image.histogram(mask) - - lut = [] - for layer in range(0, len(histogram), 256): - h = histogram[layer : layer + 256] - if ignore is not None: - # get rid of outliers - try: - h[ignore] = 0 - except TypeError: - # assume sequence - for ix in ignore: - h[ix] = 0 - if cutoff: - # cut off pixels from both ends of the histogram - if not isinstance(cutoff, tuple): - cutoff = (cutoff, cutoff) - # get number of pixels - n = 0 - for ix in range(256): - n = n + h[ix] - # remove cutoff% pixels from the low end - cut = n * cutoff[0] // 100 - for lo in range(256): - if cut > h[lo]: - cut = cut - h[lo] - h[lo] = 0 - else: - h[lo] -= cut - cut = 0 - if cut <= 0: - break - # remove cutoff% samples from the high end - cut = n * cutoff[1] // 100 - for hi in range(255, -1, -1): - if cut > h[hi]: - cut = cut - h[hi] - h[hi] = 0 - else: - h[hi] -= cut - cut = 0 - if cut <= 0: - break - # find lowest/highest samples after preprocessing - for lo in range(256): - if h[lo]: - break - for hi in range(255, -1, -1): - if h[hi]: - break - if hi <= lo: - # don't bother - lut.extend(list(range(256))) - else: - scale = 255.0 / (hi - lo) - offset = -lo * scale - for ix in range(256): - ix = int(ix * scale + offset) - if ix < 0: - ix = 0 - elif ix > 255: - ix = 255 - lut.append(ix) - return _lut(image, lut) - - -def colorize(image, black, white, mid=None, blackpoint=0, whitepoint=255, midpoint=127): - """ - Colorize grayscale image. - This function calculates a color wedge which maps all black pixels in - the source image to the first color and all white pixels to the - second color. If ``mid`` is specified, it uses three-color mapping. - The ``black`` and ``white`` arguments should be RGB tuples or color names; - optionally you can use three-color mapping by also specifying ``mid``. - Mapping positions for any of the colors can be specified - (e.g. ``blackpoint``), where these parameters are the integer - value corresponding to where the corresponding color should be mapped. - These parameters must have logical order, such that - ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified). - - :param image: The image to colorize. - :param black: The color to use for black input pixels. - :param white: The color to use for white input pixels. - :param mid: The color to use for midtone input pixels. - :param blackpoint: an int value [0, 255] for the black mapping. - :param whitepoint: an int value [0, 255] for the white mapping. - :param midpoint: an int value [0, 255] for the midtone mapping. - :return: An image. - """ - - # Initial asserts - assert image.mode == "L" - if mid is None: - assert 0 <= blackpoint <= whitepoint <= 255 - else: - assert 0 <= blackpoint <= midpoint <= whitepoint <= 255 - - # Define colors from arguments - black = _color(black, "RGB") - white = _color(white, "RGB") - if mid is not None: - mid = _color(mid, "RGB") - - # Empty lists for the mapping - red = [] - green = [] - blue = [] - - # Create the low-end values - for i in range(0, blackpoint): - red.append(black[0]) - green.append(black[1]) - blue.append(black[2]) - - # Create the mapping (2-color) - if mid is None: - range_map = range(0, whitepoint - blackpoint) - - for i in range_map: - red.append(black[0] + i * (white[0] - black[0]) // len(range_map)) - green.append(black[1] + i * (white[1] - black[1]) // len(range_map)) - blue.append(black[2] + i * (white[2] - black[2]) // len(range_map)) - - # Create the mapping (3-color) - else: - range_map1 = range(0, midpoint - blackpoint) - range_map2 = range(0, whitepoint - midpoint) - - for i in range_map1: - red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1)) - green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1)) - blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1)) - for i in range_map2: - red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2)) - green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2)) - blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2)) - - # Create the high-end values - for i in range(0, 256 - whitepoint): - red.append(white[0]) - green.append(white[1]) - blue.append(white[2]) - - # Return converted image - image = image.convert("RGB") - return _lut(image, red + green + blue) - - -def contain(image, size, method=Image.Resampling.BICUBIC): - """ - Returns a resized version of the image, set to the maximum width and height - within the requested size, while maintaining the original aspect ratio. - - :param image: The image to resize and crop. - :param size: The requested output size in pixels, given as a - (width, height) tuple. - :param method: Resampling method to use. Default is - :py:attr:`~PIL.Image.Resampling.BICUBIC`. - See :ref:`concept-filters`. - :return: An image. - """ - - im_ratio = image.width / image.height - dest_ratio = size[0] / size[1] - - if im_ratio != dest_ratio: - if im_ratio > dest_ratio: - new_height = round(image.height / image.width * size[0]) - if new_height != size[1]: - size = (size[0], new_height) - else: - new_width = round(image.width / image.height * size[1]) - if new_width != size[0]: - size = (new_width, size[1]) - return image.resize(size, resample=method) - - -def pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5)): - """ - Returns a resized and padded version of the image, expanded to fill the - requested aspect ratio and size. - - :param image: The image to resize and crop. - :param size: The requested output size in pixels, given as a - (width, height) tuple. - :param method: Resampling method to use. Default is - :py:attr:`~PIL.Image.Resampling.BICUBIC`. - See :ref:`concept-filters`. - :param color: The background color of the padded image. - :param centering: Control the position of the original image within the - padded version. - - (0.5, 0.5) will keep the image centered - (0, 0) will keep the image aligned to the top left - (1, 1) will keep the image aligned to the bottom - right - :return: An image. - """ - - resized = contain(image, size, method) - if resized.size == size: - out = resized - else: - out = Image.new(image.mode, size, color) - if resized.palette: - out.putpalette(resized.getpalette()) - if resized.width != size[0]: - x = round((size[0] - resized.width) * max(0, min(centering[0], 1))) - out.paste(resized, (x, 0)) - else: - y = round((size[1] - resized.height) * max(0, min(centering[1], 1))) - out.paste(resized, (0, y)) - return out - - -def crop(image, border=0): - """ - Remove border from image. The same amount of pixels are removed - from all four sides. This function works on all image modes. - - .. seealso:: :py:meth:`~PIL.Image.Image.crop` - - :param image: The image to crop. - :param border: The number of pixels to remove. - :return: An image. - """ - left, top, right, bottom = _border(border) - return image.crop((left, top, image.size[0] - right, image.size[1] - bottom)) - - -def scale(image, factor, resample=Image.Resampling.BICUBIC): - """ - Returns a rescaled image by a specific factor given in parameter. - A factor greater than 1 expands the image, between 0 and 1 contracts the - image. - - :param image: The image to rescale. - :param factor: The expansion factor, as a float. - :param resample: Resampling method to use. Default is - :py:attr:`~PIL.Image.Resampling.BICUBIC`. - See :ref:`concept-filters`. - :returns: An :py:class:`~PIL.Image.Image` object. - """ - if factor == 1: - return image.copy() - elif factor <= 0: - msg = "the factor must be greater than 0" - raise ValueError(msg) - else: - size = (round(factor * image.width), round(factor * image.height)) - return image.resize(size, resample) - - -def deform(image, deformer, resample=Image.Resampling.BILINEAR): - """ - Deform the image. - - :param image: The image to deform. - :param deformer: A deformer object. Any object that implements a - ``getmesh`` method can be used. - :param resample: An optional resampling filter. Same values possible as - in the PIL.Image.transform function. - :return: An image. - """ - return image.transform( - image.size, Image.Transform.MESH, deformer.getmesh(image), resample - ) - - -def equalize(image, mask=None): - """ - Equalize the image histogram. This function applies a non-linear - mapping to the input image, in order to create a uniform - distribution of grayscale values in the output image. - - :param image: The image to equalize. - :param mask: An optional mask. If given, only the pixels selected by - the mask are included in the analysis. - :return: An image. - """ - if image.mode == "P": - image = image.convert("RGB") - h = image.histogram(mask) - lut = [] - for b in range(0, len(h), 256): - histo = [_f for _f in h[b : b + 256] if _f] - if len(histo) <= 1: - lut.extend(list(range(256))) - else: - step = (functools.reduce(operator.add, histo) - histo[-1]) // 255 - if not step: - lut.extend(list(range(256))) - else: - n = step // 2 - for i in range(256): - lut.append(n // step) - n = n + h[i + b] - return _lut(image, lut) - - -def expand(image, border=0, fill=0): - """ - Add border to the image - - :param image: The image to expand. - :param border: Border width, in pixels. - :param fill: Pixel fill value (a color value). Default is 0 (black). - :return: An image. - """ - left, top, right, bottom = _border(border) - width = left + image.size[0] + right - height = top + image.size[1] + bottom - color = _color(fill, image.mode) - if image.palette: - palette = ImagePalette.ImagePalette(palette=image.getpalette()) - if isinstance(color, tuple): - color = palette.getcolor(color) - else: - palette = None - out = Image.new(image.mode, (width, height), color) - if palette: - out.putpalette(palette.palette) - out.paste(image, (left, top)) - return out - - -def fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5)): - """ - Returns a resized and cropped version of the image, cropped to the - requested aspect ratio and size. - - This function was contributed by Kevin Cazabon. - - :param image: The image to resize and crop. - :param size: The requested output size in pixels, given as a - (width, height) tuple. - :param method: Resampling method to use. Default is - :py:attr:`~PIL.Image.Resampling.BICUBIC`. - See :ref:`concept-filters`. - :param bleed: Remove a border around the outside of the image from all - four edges. The value is a decimal percentage (use 0.01 for - one percent). The default value is 0 (no border). - Cannot be greater than or equal to 0.5. - :param centering: Control the cropping position. Use (0.5, 0.5) for - center cropping (e.g. if cropping the width, take 50% off - of the left side, and therefore 50% off the right side). - (0.0, 0.0) will crop from the top left corner (i.e. if - cropping the width, take all of the crop off of the right - side, and if cropping the height, take all of it off the - bottom). (1.0, 0.0) will crop from the bottom left - corner, etc. (i.e. if cropping the width, take all of the - crop off the left side, and if cropping the height take - none from the top, and therefore all off the bottom). - :return: An image. - """ - - # by Kevin Cazabon, Feb 17/2000 - # kevin@cazabon.com - # https://www.cazabon.com - - # ensure centering is mutable - centering = list(centering) - - if not 0.0 <= centering[0] <= 1.0: - centering[0] = 0.5 - if not 0.0 <= centering[1] <= 1.0: - centering[1] = 0.5 - - if not 0.0 <= bleed < 0.5: - bleed = 0.0 - - # calculate the area to use for resizing and cropping, subtracting - # the 'bleed' around the edges - - # number of pixels to trim off on Top and Bottom, Left and Right - bleed_pixels = (bleed * image.size[0], bleed * image.size[1]) - - live_size = ( - image.size[0] - bleed_pixels[0] * 2, - image.size[1] - bleed_pixels[1] * 2, - ) - - # calculate the aspect ratio of the live_size - live_size_ratio = live_size[0] / live_size[1] - - # calculate the aspect ratio of the output image - output_ratio = size[0] / size[1] - - # figure out if the sides or top/bottom will be cropped off - if live_size_ratio == output_ratio: - # live_size is already the needed ratio - crop_width = live_size[0] - crop_height = live_size[1] - elif live_size_ratio >= output_ratio: - # live_size is wider than what's needed, crop the sides - crop_width = output_ratio * live_size[1] - crop_height = live_size[1] - else: - # live_size is taller than what's needed, crop the top and bottom - crop_width = live_size[0] - crop_height = live_size[0] / output_ratio - - # make the crop - crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering[0] - crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering[1] - - crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height) - - # resize the image and return it - return image.resize(size, method, box=crop) - - -def flip(image): - """ - Flip the image vertically (top to bottom). - - :param image: The image to flip. - :return: An image. - """ - return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) - - -def grayscale(image): - """ - Convert the image to grayscale. - - :param image: The image to convert. - :return: An image. - """ - return image.convert("L") - - -def invert(image): - """ - Invert (negate) the image. - - :param image: The image to invert. - :return: An image. - """ - lut = [] - for i in range(256): - lut.append(255 - i) - return image.point(lut) if image.mode == "1" else _lut(image, lut) - - -def mirror(image): - """ - Flip image horizontally (left to right). - - :param image: The image to mirror. - :return: An image. - """ - return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) - - -def posterize(image, bits): - """ - Reduce the number of bits for each color channel. - - :param image: The image to posterize. - :param bits: The number of bits to keep for each channel (1-8). - :return: An image. - """ - lut = [] - mask = ~(2 ** (8 - bits) - 1) - for i in range(256): - lut.append(i & mask) - return _lut(image, lut) - - -def solarize(image, threshold=128): - """ - Invert all pixel values above a threshold. - - :param image: The image to solarize. - :param threshold: All pixels above this greyscale level are inverted. - :return: An image. - """ - lut = [] - for i in range(256): - if i < threshold: - lut.append(i) - else: - lut.append(255 - i) - return _lut(image, lut) - - -def exif_transpose(image, *, in_place=False): - """ - If an image has an EXIF Orientation tag, other than 1, transpose the image - accordingly, and remove the orientation data. - - :param image: The image to transpose. - :param in_place: Boolean. Keyword-only argument. - If ``True``, the original image is modified in-place, and ``None`` is returned. - If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned - with the transposition applied. If there is no transposition, a copy of the - image will be returned. - """ - image_exif = image.getexif() - orientation = image_exif.get(ExifTags.Base.Orientation) - method = { - 2: Image.Transpose.FLIP_LEFT_RIGHT, - 3: Image.Transpose.ROTATE_180, - 4: Image.Transpose.FLIP_TOP_BOTTOM, - 5: Image.Transpose.TRANSPOSE, - 6: Image.Transpose.ROTATE_270, - 7: Image.Transpose.TRANSVERSE, - 8: Image.Transpose.ROTATE_90, - }.get(orientation) - if method is not None: - transposed_image = image.transpose(method) - if in_place: - image.im = transposed_image.im - image.pyaccess = None - image._size = transposed_image._size - exif_image = image if in_place else transposed_image - - exif = exif_image.getexif() - if ExifTags.Base.Orientation in exif: - del exif[ExifTags.Base.Orientation] - if "exif" in exif_image.info: - exif_image.info["exif"] = exif.tobytes() - elif "Raw profile type exif" in exif_image.info: - exif_image.info["Raw profile type exif"] = exif.tobytes().hex() - elif "XML:com.adobe.xmp" in exif_image.info: - for pattern in ( - r'tiff:Orientation="([0-9])"', - r"([0-9])", - ): - exif_image.info["XML:com.adobe.xmp"] = re.sub( - pattern, "", exif_image.info["XML:com.adobe.xmp"] - ) - if not in_place: - return transposed_image - elif not in_place: - return image.copy() diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/click/_textwrap.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/click/_textwrap.py deleted file mode 100644 index b47dcbd4264e86715adfae1c5124c288b67a983e..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/click/_textwrap.py +++ /dev/null @@ -1,49 +0,0 @@ -import textwrap -import typing as t -from contextlib import contextmanager - - -class TextWrapper(textwrap.TextWrapper): - def _handle_long_word( - self, - reversed_chunks: t.List[str], - cur_line: t.List[str], - cur_len: int, - width: int, - ) -> None: - space_left = max(width - cur_len, 1) - - if self.break_long_words: - last = reversed_chunks[-1] - cut = last[:space_left] - res = last[space_left:] - cur_line.append(cut) - reversed_chunks[-1] = res - elif not cur_line: - cur_line.append(reversed_chunks.pop()) - - @contextmanager - def extra_indent(self, indent: str) -> t.Iterator[None]: - old_initial_indent = self.initial_indent - old_subsequent_indent = self.subsequent_indent - self.initial_indent += indent - self.subsequent_indent += indent - - try: - yield - finally: - self.initial_indent = old_initial_indent - self.subsequent_indent = old_subsequent_indent - - def indent_only(self, text: str) -> str: - rv = [] - - for idx, line in enumerate(text.splitlines()): - indent = self.initial_indent - - if idx > 0: - indent = self.subsequent_indent - - rv.append(f"{indent}{line}") - - return "\n".join(rv) diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/macUtils.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/macUtils.py deleted file mode 100644 index 468a75ad6d2da59bf00bbb07063ba4819aff64dd..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/ttLib/macUtils.py +++ /dev/null @@ -1,54 +0,0 @@ -"""ttLib.macUtils.py -- Various Mac-specific stuff.""" -from io import BytesIO -from fontTools.misc.macRes import ResourceReader, ResourceError - - -def getSFNTResIndices(path): - """Determine whether a file has a 'sfnt' resource fork or not.""" - try: - reader = ResourceReader(path) - indices = reader.getIndices("sfnt") - reader.close() - return indices - except ResourceError: - return [] - - -def openTTFonts(path): - """Given a pathname, return a list of TTFont objects. In the case - of a flat TTF/OTF file, the list will contain just one font object; - but in the case of a Mac font suitcase it will contain as many - font objects as there are sfnt resources in the file. - """ - from fontTools import ttLib - - fonts = [] - sfnts = getSFNTResIndices(path) - if not sfnts: - fonts.append(ttLib.TTFont(path)) - else: - for index in sfnts: - fonts.append(ttLib.TTFont(path, index)) - if not fonts: - raise ttLib.TTLibError("no fonts found in file '%s'" % path) - return fonts - - -class SFNTResourceReader(BytesIO): - - """Simple read-only file wrapper for 'sfnt' resources.""" - - def __init__(self, path, res_name_or_index): - from fontTools import ttLib - - reader = ResourceReader(path) - if isinstance(res_name_or_index, str): - rsrc = reader.getNamedResource("sfnt", res_name_or_index) - else: - rsrc = reader.getIndResource("sfnt", res_name_or_index) - if rsrc is None: - raise ttLib.TTLibError("sfnt resource not found: %s" % res_name_or_index) - reader.close() - self.rsrc = rsrc - super(SFNTResourceReader, self).__init__(rsrc.data) - self.name = path diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/arm/audiodsp_init_neon.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/arm/audiodsp_init_neon.c deleted file mode 100644 index 6902db86b4ce997edf4da6fa7d8ecfd1e413dfd2..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/arm/audiodsp_init_neon.c +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ARM NEON optimised audio functions - * Copyright (c) 2008 Mans Rullgard - * - * 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 - -#include "libavutil/attributes.h" -#include "libavcodec/audiodsp.h" -#include "audiodsp_arm.h" - -void ff_vector_clipf_neon(float *dst, const float *src, int len, float min, float max); -void ff_vector_clip_int32_neon(int32_t *dst, const int32_t *src, int32_t min, - int32_t max, unsigned int len); - -int32_t ff_scalarproduct_int16_neon(const int16_t *v1, const int16_t *v2, int len); - -av_cold void ff_audiodsp_init_neon(AudioDSPContext *c) -{ - c->vector_clip_int32 = ff_vector_clip_int32_neon; - c->vector_clipf = ff_vector_clipf_neon; - - c->scalarproduct_int16 = ff_scalarproduct_int16_neon; -} diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/atrac1data.h b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/atrac1data.h deleted file mode 100644 index 62c218b7906d59c9b0aa131cdc22763c959482b2..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/atrac1data.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ATRAC 1 compatible decoder data - * Copyright (c) 2009 Maxim Poliakovski - * Copyright (c) 2009 Benjamin Larsson - * - * 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 - * ATRAC1 compatible decoder data - */ - -#ifndef AVCODEC_ATRAC1DATA_H -#define AVCODEC_ATRAC1DATA_H - -#include - -static const uint8_t bfu_amount_tab1[8] = {20, 28, 32, 36, 40, 44, 48, 52}; -static const uint8_t bfu_amount_tab2[4] = { 0, 112, 176, 208}; -static const uint8_t bfu_amount_tab3[8] = { 0, 24, 36, 48, 72, 108, 132, 156}; - -/** number of BFUs in each QMF band */ -static const uint8_t bfu_bands_t[4] = {0, 20, 36, 52}; - -/** number of spectral lines in each BFU - * block floating unit = group of spectral frequencies having the - * same quantization parameters like word length and scale factor - */ -static const uint8_t specs_per_bfu[52] = { - 8, 8, 8, 8, 4, 4, 4, 4, 8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6, // low band - 6, 6, 6, 6, 7, 7, 7, 7, 9, 9, 9, 9, 10, 10, 10, 10, // middle band - 12, 12, 12, 12, 12, 12, 12, 12, 20, 20, 20, 20, 20, 20, 20, 20 // high band -}; - -/** start position of each BFU in the MDCT spectrum for the long mode */ -static const uint16_t bfu_start_long[52] = { - 0, 8, 16, 24, 32, 36, 40, 44, 48, 56, 64, 72, 80, 86, 92, 98, 104, 110, 116, 122, - 128, 134, 140, 146, 152, 159, 166, 173, 180, 189, 198, 207, 216, 226, 236, 246, - 256, 268, 280, 292, 304, 316, 328, 340, 352, 372, 392, 412, 432, 452, 472, 492, -}; - -/** start position of each BFU in the MDCT spectrum for the short mode */ -static const uint16_t bfu_start_short[52] = { - 0, 32, 64, 96, 8, 40, 72, 104, 12, 44, 76, 108, 20, 52, 84, 116, 26, 58, 90, 122, - 128, 160, 192, 224, 134, 166, 198, 230, 141, 173, 205, 237, 150, 182, 214, 246, - 256, 288, 320, 352, 384, 416, 448, 480, 268, 300, 332, 364, 396, 428, 460, 492 -}; - -#endif /* AVCODEC_ATRAC1DATA_H */ diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/flicvideo.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/flicvideo.c deleted file mode 100644 index 228f65277528e626cc2daafc8c92362deb14c7ad..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/flicvideo.c +++ /dev/null @@ -1,1115 +0,0 @@ -/* - * FLI/FLC Animation Video Decoder - * Copyright (C) 2003, 2004 The FFmpeg project - * - * 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 - * Autodesk Animator FLI/FLC Video Decoder - * by Mike Melanson (melanson@pcisys.net) - * for more information on the .fli/.flc file format and all of its many - * variations, visit: - * http://www.compuphase.com/flic.htm - * - * This decoder outputs PAL8/RGB555/RGB565/BGR24. To use this decoder, be - * sure that your demuxer sends the FLI file header to the decoder via - * the extradata chunk in AVCodecContext. The chunk should be 128 bytes - * large. The only exception is for FLI files from the game "Magic Carpet", - * in which the header is only 12 bytes. - */ - -#include - -#include "libavutil/intreadwrite.h" -#include "avcodec.h" -#include "bytestream.h" -#include "codec_internal.h" -#include "decode.h" -#include "mathops.h" - -#define FLI_256_COLOR 4 -#define FLI_DELTA 7 -#define FLI_COLOR 11 -#define FLI_LC 12 -#define FLI_BLACK 13 -#define FLI_BRUN 15 -#define FLI_COPY 16 -#define FLI_MINI 18 -#define FLI_DTA_BRUN 25 -#define FLI_DTA_COPY 26 -#define FLI_DTA_LC 27 - -#define FLI_TYPE_CODE (0xAF11) -#define FLC_FLX_TYPE_CODE (0xAF12) -#define FLC_DTA_TYPE_CODE (0xAF44) /* Marks an "Extended FLC" comes from Dave's Targa Animator (DTA) */ -#define FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE (0xAF13) - -#define CHECK_PIXEL_PTR(n) \ - if (pixel_ptr + n > pixel_limit) { \ - av_log (s->avctx, AV_LOG_ERROR, "Invalid pixel_ptr = %d > pixel_limit = %d\n", \ - pixel_ptr + n, pixel_limit); \ - return AVERROR_INVALIDDATA; \ - } \ - -typedef struct FlicDecodeContext { - AVCodecContext *avctx; - AVFrame *frame; - - unsigned int palette[256]; - int new_palette; - int fli_type; /* either 0xAF11 or 0xAF12, affects palette resolution */ -} FlicDecodeContext; - -static av_cold int flic_decode_init(AVCodecContext *avctx) -{ - FlicDecodeContext *s = avctx->priv_data; - unsigned char *fli_header = (unsigned char *)avctx->extradata; - int depth; - - if (avctx->extradata_size != 0 && - avctx->extradata_size != 12 && - avctx->extradata_size != 128 && - avctx->extradata_size != 256 && - avctx->extradata_size != 904 && - avctx->extradata_size != 1024) { - av_log(avctx, AV_LOG_ERROR, "Unexpected extradata size %d\n", avctx->extradata_size); - return AVERROR_INVALIDDATA; - } - - s->avctx = avctx; - - if (s->avctx->extradata_size == 12) { - /* special case for magic carpet FLIs */ - s->fli_type = FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE; - depth = 8; - } else if (avctx->extradata_size == 1024) { - uint8_t *ptr = avctx->extradata; - int i; - - for (i = 0; i < 256; i++) { - s->palette[i] = AV_RL32(ptr); - ptr += 4; - } - depth = 8; - /* FLI in MOV, see e.g. FFmpeg trac issue #626 */ - } else if (avctx->extradata_size == 0 || - avctx->extradata_size == 256 || - /* see FFmpeg ticket #1234 */ - avctx->extradata_size == 904) { - s->fli_type = FLI_TYPE_CODE; - depth = 8; - } else { - s->fli_type = AV_RL16(&fli_header[4]); - depth = AV_RL16(&fli_header[12]); - } - - if (depth == 0) { - depth = 8; /* Some FLC generators set depth to zero, when they mean 8Bpp. Fix up here */ - } - - if ((s->fli_type == FLC_FLX_TYPE_CODE) && (depth == 16)) { - depth = 15; /* Original Autodesk FLX's say the depth is 16Bpp when it is really 15Bpp */ - } - - switch (depth) { - case 8 : avctx->pix_fmt = AV_PIX_FMT_PAL8; break; - case 15 : avctx->pix_fmt = AV_PIX_FMT_RGB555; break; - case 16 : avctx->pix_fmt = AV_PIX_FMT_RGB565; break; - case 24 : avctx->pix_fmt = AV_PIX_FMT_BGR24; break; - default : - av_log(avctx, AV_LOG_ERROR, "Unknown FLC/FLX depth of %d Bpp is unsupported.\n",depth); - return AVERROR_INVALIDDATA; - } - - s->frame = av_frame_alloc(); - if (!s->frame) - return AVERROR(ENOMEM); - - s->new_palette = 0; - - return 0; -} - -static int flic_decode_frame_8BPP(AVCodecContext *avctx, - AVFrame *rframe, int *got_frame, - const uint8_t *buf, int buf_size) -{ - FlicDecodeContext *s = avctx->priv_data; - - GetByteContext g2; - int pixel_ptr; - int palette_ptr; - unsigned char palette_idx1; - unsigned char palette_idx2; - - unsigned int frame_size; - int num_chunks; - - unsigned int chunk_size; - int chunk_type; - - int i, j, ret; - - int color_packets; - int color_changes; - int color_shift; - unsigned char r, g, b; - - int lines; - int compressed_lines; - int starting_line; - int line_packets; - int y_ptr; - int byte_run; - int pixel_skip; - int pixel_countdown; - unsigned char *pixels; - unsigned int pixel_limit; - - bytestream2_init(&g2, buf, buf_size); - - if ((ret = ff_reget_buffer(avctx, s->frame, 0)) < 0) - return ret; - - pixels = s->frame->data[0]; - pixel_limit = s->avctx->height * s->frame->linesize[0]; - if (buf_size < 16 || buf_size > INT_MAX - (3 * 256 + AV_INPUT_BUFFER_PADDING_SIZE)) - return AVERROR_INVALIDDATA; - frame_size = bytestream2_get_le32(&g2); - if (frame_size > buf_size) - frame_size = buf_size; - bytestream2_skip(&g2, 2); /* skip the magic number */ - num_chunks = bytestream2_get_le16(&g2); - bytestream2_skip(&g2, 8); /* skip padding */ - - if (frame_size < 16) - return AVERROR_INVALIDDATA; - - frame_size -= 16; - - /* iterate through the chunks */ - while ((frame_size >= 6) && (num_chunks > 0) && - bytestream2_get_bytes_left(&g2) >= 4) { - int stream_ptr_after_chunk; - chunk_size = bytestream2_get_le32(&g2); - if (chunk_size > frame_size) { - av_log(avctx, AV_LOG_WARNING, - "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size); - chunk_size = frame_size; - } - stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size; - - chunk_type = bytestream2_get_le16(&g2); - - switch (chunk_type) { - case FLI_256_COLOR: - case FLI_COLOR: - /* check special case: If this file is from the Magic Carpet - * game and uses 6-bit colors even though it reports 256-color - * chunks in a 0xAF12-type file (fli_type is set to 0xAF13 during - * initialization) */ - if ((chunk_type == FLI_256_COLOR) && (s->fli_type != FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE)) - color_shift = 0; - else - color_shift = 2; - /* set up the palette */ - color_packets = bytestream2_get_le16(&g2); - palette_ptr = 0; - for (i = 0; i < color_packets; i++) { - /* first byte is how many colors to skip */ - palette_ptr += bytestream2_get_byte(&g2); - - /* next byte indicates how many entries to change */ - color_changes = bytestream2_get_byte(&g2); - - /* if there are 0 color changes, there are actually 256 */ - if (color_changes == 0) - color_changes = 256; - - if (bytestream2_tell(&g2) + color_changes * 3 > stream_ptr_after_chunk) - break; - - for (j = 0; j < color_changes; j++) { - unsigned int entry; - - /* wrap around, for good measure */ - if ((unsigned)palette_ptr >= 256) - palette_ptr = 0; - - r = bytestream2_get_byte(&g2) << color_shift; - g = bytestream2_get_byte(&g2) << color_shift; - b = bytestream2_get_byte(&g2) << color_shift; - entry = 0xFFU << 24 | r << 16 | g << 8 | b; - if (color_shift == 2) - entry |= entry >> 6 & 0x30303; - if (s->palette[palette_ptr] != entry) - s->new_palette = 1; - s->palette[palette_ptr++] = entry; - } - } - break; - - case FLI_DELTA: - y_ptr = 0; - compressed_lines = bytestream2_get_le16(&g2); - while (compressed_lines > 0) { - if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) - break; - if (y_ptr > pixel_limit) - return AVERROR_INVALIDDATA; - line_packets = sign_extend(bytestream2_get_le16(&g2), 16); - if ((line_packets & 0xC000) == 0xC000) { - // line skip opcode - line_packets = -line_packets; - if (line_packets > s->avctx->height) - return AVERROR_INVALIDDATA; - y_ptr += line_packets * s->frame->linesize[0]; - } else if ((line_packets & 0xC000) == 0x4000) { - av_log(avctx, AV_LOG_ERROR, "Undefined opcode (%x) in DELTA_FLI\n", line_packets); - } else if ((line_packets & 0xC000) == 0x8000) { - // "last byte" opcode - pixel_ptr= y_ptr + s->frame->linesize[0] - 1; - CHECK_PIXEL_PTR(0); - pixels[pixel_ptr] = line_packets & 0xff; - } else { - compressed_lines--; - pixel_ptr = y_ptr; - CHECK_PIXEL_PTR(0); - pixel_countdown = s->avctx->width; - for (i = 0; i < line_packets; i++) { - if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) - break; - /* account for the skip bytes */ - pixel_skip = bytestream2_get_byte(&g2); - pixel_ptr += pixel_skip; - pixel_countdown -= pixel_skip; - byte_run = sign_extend(bytestream2_get_byte(&g2), 8); - if (byte_run < 0) { - byte_run = -byte_run; - palette_idx1 = bytestream2_get_byte(&g2); - palette_idx2 = bytestream2_get_byte(&g2); - CHECK_PIXEL_PTR(byte_run * 2); - for (j = 0; j < byte_run; j++, pixel_countdown -= 2) { - pixels[pixel_ptr++] = palette_idx1; - pixels[pixel_ptr++] = palette_idx2; - } - } else { - CHECK_PIXEL_PTR(byte_run * 2); - if (bytestream2_tell(&g2) + byte_run * 2 > stream_ptr_after_chunk) - break; - for (j = 0; j < byte_run * 2; j++, pixel_countdown--) { - pixels[pixel_ptr++] = bytestream2_get_byte(&g2); - } - } - } - - y_ptr += s->frame->linesize[0]; - } - } - break; - - case FLI_LC: - /* line compressed */ - starting_line = bytestream2_get_le16(&g2); - if (starting_line >= s->avctx->height) - return AVERROR_INVALIDDATA; - y_ptr = 0; - y_ptr += starting_line * s->frame->linesize[0]; - - compressed_lines = bytestream2_get_le16(&g2); - while (compressed_lines > 0) { - pixel_ptr = y_ptr; - CHECK_PIXEL_PTR(0); - pixel_countdown = s->avctx->width; - if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) - break; - line_packets = bytestream2_get_byte(&g2); - if (line_packets > 0) { - for (i = 0; i < line_packets; i++) { - /* account for the skip bytes */ - if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) - break; - pixel_skip = bytestream2_get_byte(&g2); - pixel_ptr += pixel_skip; - pixel_countdown -= pixel_skip; - byte_run = sign_extend(bytestream2_get_byte(&g2),8); - if (byte_run > 0) { - CHECK_PIXEL_PTR(byte_run); - if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk) - break; - for (j = 0; j < byte_run; j++, pixel_countdown--) { - pixels[pixel_ptr++] = bytestream2_get_byte(&g2); - } - } else if (byte_run < 0) { - byte_run = -byte_run; - palette_idx1 = bytestream2_get_byte(&g2); - CHECK_PIXEL_PTR(byte_run); - for (j = 0; j < byte_run; j++, pixel_countdown--) { - pixels[pixel_ptr++] = palette_idx1; - } - } - } - } - - y_ptr += s->frame->linesize[0]; - compressed_lines--; - } - break; - - case FLI_BLACK: - /* set the whole frame to color 0 (which is usually black) */ - memset(pixels, 0, - s->frame->linesize[0] * s->avctx->height); - break; - - case FLI_BRUN: - /* Byte run compression: This chunk type only occurs in the first - * FLI frame and it will update the entire frame. */ - y_ptr = 0; - for (lines = 0; lines < s->avctx->height; lines++) { - pixel_ptr = y_ptr; - /* disregard the line packets; instead, iterate through all - * pixels on a row */ - bytestream2_skip(&g2, 1); - pixel_countdown = s->avctx->width; - while (pixel_countdown > 0) { - if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) - break; - byte_run = sign_extend(bytestream2_get_byte(&g2), 8); - if (!byte_run) { - av_log(avctx, AV_LOG_ERROR, "Invalid byte run value.\n"); - return AVERROR_INVALIDDATA; - } - - if (byte_run > 0) { - palette_idx1 = bytestream2_get_byte(&g2); - CHECK_PIXEL_PTR(byte_run); - for (j = 0; j < byte_run; j++) { - pixels[pixel_ptr++] = palette_idx1; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n", - pixel_countdown, lines); - } - } else { /* copy bytes if byte_run < 0 */ - byte_run = -byte_run; - CHECK_PIXEL_PTR(byte_run); - if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk) - break; - for (j = 0; j < byte_run; j++) { - pixels[pixel_ptr++] = bytestream2_get_byte(&g2); - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n", - pixel_countdown, lines); - } - } - } - - y_ptr += s->frame->linesize[0]; - } - break; - - case FLI_COPY: - /* copy the chunk (uncompressed frame) */ - if (chunk_size - 6 != FFALIGN(s->avctx->width, 4) * s->avctx->height) { - av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \ - "has incorrect size, skipping chunk\n", chunk_size - 6); - bytestream2_skip(&g2, chunk_size - 6); - } else { - for (y_ptr = 0; y_ptr < s->frame->linesize[0] * s->avctx->height; - y_ptr += s->frame->linesize[0]) { - bytestream2_get_buffer(&g2, &pixels[y_ptr], - s->avctx->width); - if (s->avctx->width & 3) - bytestream2_skip(&g2, 4 - (s->avctx->width & 3)); - } - } - break; - - case FLI_MINI: - /* some sort of a thumbnail? disregard this chunk... */ - break; - - default: - av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type); - break; - } - - if (stream_ptr_after_chunk - bytestream2_tell(&g2) >= 0) { - bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2)); - } else { - av_log(avctx, AV_LOG_ERROR, "Chunk overread\n"); - break; - } - - frame_size -= chunk_size; - num_chunks--; - } - - /* by the end of the chunk, the stream ptr should equal the frame - * size (minus 1 or 2, possibly); if it doesn't, issue a warning */ - if (bytestream2_get_bytes_left(&g2) > 2) - av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \ - "and final chunk ptr = %d\n", buf_size, - buf_size - bytestream2_get_bytes_left(&g2)); - - /* make the palette available on the way out */ - memcpy(s->frame->data[1], s->palette, AVPALETTE_SIZE); - if (s->new_palette) { - s->frame->palette_has_changed = 1; - s->new_palette = 0; - } - - if ((ret = av_frame_ref(rframe, s->frame)) < 0) - return ret; - - *got_frame = 1; - - return buf_size; -} - -static int flic_decode_frame_15_16BPP(AVCodecContext *avctx, - AVFrame *rframe, int *got_frame, - const uint8_t *buf, int buf_size) -{ - /* Note, the only difference between the 15Bpp and 16Bpp */ - /* Format is the pixel format, the packets are processed the same. */ - FlicDecodeContext *s = avctx->priv_data; - - GetByteContext g2; - int pixel_ptr; - unsigned char palette_idx1; - - unsigned int frame_size; - int num_chunks; - - unsigned int chunk_size; - int chunk_type; - - int i, j, ret; - - int lines; - int compressed_lines; - int line_packets; - int y_ptr; - int byte_run; - int pixel_skip; - int pixel_countdown; - unsigned char *pixels; - int pixel; - unsigned int pixel_limit; - - bytestream2_init(&g2, buf, buf_size); - - if ((ret = ff_reget_buffer(avctx, s->frame, 0)) < 0) - return ret; - - pixels = s->frame->data[0]; - pixel_limit = s->avctx->height * s->frame->linesize[0]; - - frame_size = bytestream2_get_le32(&g2); - bytestream2_skip(&g2, 2); /* skip the magic number */ - num_chunks = bytestream2_get_le16(&g2); - bytestream2_skip(&g2, 8); /* skip padding */ - if (frame_size > buf_size) - frame_size = buf_size; - - if (frame_size < 16) - return AVERROR_INVALIDDATA; - frame_size -= 16; - - /* iterate through the chunks */ - while ((frame_size > 0) && (num_chunks > 0) && - bytestream2_get_bytes_left(&g2) >= 4) { - int stream_ptr_after_chunk; - chunk_size = bytestream2_get_le32(&g2); - if (chunk_size > frame_size) { - av_log(avctx, AV_LOG_WARNING, - "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size); - chunk_size = frame_size; - } - stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size; - - chunk_type = bytestream2_get_le16(&g2); - - - switch (chunk_type) { - case FLI_256_COLOR: - case FLI_COLOR: - /* For some reason, it seems that non-palettized flics do - * include one of these chunks in their first frame. - * Why I do not know, it seems rather extraneous. */ - ff_dlog(avctx, - "Unexpected Palette chunk %d in non-palettized FLC\n", - chunk_type); - bytestream2_skip(&g2, chunk_size - 6); - break; - - case FLI_DELTA: - case FLI_DTA_LC: - y_ptr = 0; - compressed_lines = bytestream2_get_le16(&g2); - while (compressed_lines > 0) { - if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) - break; - if (y_ptr > pixel_limit) - return AVERROR_INVALIDDATA; - line_packets = sign_extend(bytestream2_get_le16(&g2), 16); - if (line_packets < 0) { - line_packets = -line_packets; - if (line_packets > s->avctx->height) - return AVERROR_INVALIDDATA; - y_ptr += line_packets * s->frame->linesize[0]; - } else { - compressed_lines--; - pixel_ptr = y_ptr; - CHECK_PIXEL_PTR(0); - pixel_countdown = s->avctx->width; - for (i = 0; i < line_packets; i++) { - /* account for the skip bytes */ - if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) - break; - pixel_skip = bytestream2_get_byte(&g2); - pixel_ptr += (pixel_skip*2); /* Pixel is 2 bytes wide */ - pixel_countdown -= pixel_skip; - byte_run = sign_extend(bytestream2_get_byte(&g2), 8); - if (byte_run < 0) { - byte_run = -byte_run; - pixel = bytestream2_get_le16(&g2); - CHECK_PIXEL_PTR(2 * byte_run); - for (j = 0; j < byte_run; j++, pixel_countdown -= 2) { - *((signed short*)(&pixels[pixel_ptr])) = pixel; - pixel_ptr += 2; - } - } else { - if (bytestream2_tell(&g2) + 2*byte_run > stream_ptr_after_chunk) - break; - CHECK_PIXEL_PTR(2 * byte_run); - for (j = 0; j < byte_run; j++, pixel_countdown--) { - *((signed short*)(&pixels[pixel_ptr])) = bytestream2_get_le16(&g2); - pixel_ptr += 2; - } - } - } - - y_ptr += s->frame->linesize[0]; - } - } - break; - - case FLI_LC: - av_log(avctx, AV_LOG_ERROR, "Unexpected FLI_LC chunk in non-palettized FLC\n"); - bytestream2_skip(&g2, chunk_size - 6); - break; - - case FLI_BLACK: - /* set the whole frame to 0x0000 which is black in both 15Bpp and 16Bpp modes. */ - memset(pixels, 0x0000, - s->frame->linesize[0] * s->avctx->height); - break; - - case FLI_BRUN: - y_ptr = 0; - for (lines = 0; lines < s->avctx->height; lines++) { - pixel_ptr = y_ptr; - /* disregard the line packets; instead, iterate through all - * pixels on a row */ - bytestream2_skip(&g2, 1); - pixel_countdown = (s->avctx->width * 2); - - while (pixel_countdown > 0) { - if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) - break; - byte_run = sign_extend(bytestream2_get_byte(&g2), 8); - if (byte_run > 0) { - palette_idx1 = bytestream2_get_byte(&g2); - CHECK_PIXEL_PTR(byte_run); - for (j = 0; j < byte_run; j++) { - pixels[pixel_ptr++] = palette_idx1; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) (linea%d)\n", - pixel_countdown, lines); - } - } else { /* copy bytes if byte_run < 0 */ - byte_run = -byte_run; - if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk) - break; - CHECK_PIXEL_PTR(byte_run); - for (j = 0; j < byte_run; j++) { - palette_idx1 = bytestream2_get_byte(&g2); - pixels[pixel_ptr++] = palette_idx1; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n", - pixel_countdown, lines); - } - } - } - - /* Now FLX is strange, in that it is "byte" as opposed to "pixel" run length compressed. - * This does not give us any good opportunity to perform word endian conversion - * during decompression. So if it is required (i.e., this is not a LE target, we do - * a second pass over the line here, swapping the bytes. - */ -#if HAVE_BIGENDIAN - pixel_ptr = y_ptr; - pixel_countdown = s->avctx->width; - while (pixel_countdown > 0) { - *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[pixel_ptr]); - pixel_ptr += 2; - } -#endif - y_ptr += s->frame->linesize[0]; - } - break; - - case FLI_DTA_BRUN: - y_ptr = 0; - for (lines = 0; lines < s->avctx->height; lines++) { - pixel_ptr = y_ptr; - /* disregard the line packets; instead, iterate through all - * pixels on a row */ - bytestream2_skip(&g2, 1); - pixel_countdown = s->avctx->width; /* Width is in pixels, not bytes */ - - while (pixel_countdown > 0) { - if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) - break; - byte_run = sign_extend(bytestream2_get_byte(&g2), 8); - if (byte_run > 0) { - pixel = bytestream2_get_le16(&g2); - CHECK_PIXEL_PTR(2 * byte_run); - for (j = 0; j < byte_run; j++) { - *((signed short*)(&pixels[pixel_ptr])) = pixel; - pixel_ptr += 2; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n", - pixel_countdown); - } - } else { /* copy pixels if byte_run < 0 */ - byte_run = -byte_run; - if (bytestream2_tell(&g2) + 2 * byte_run > stream_ptr_after_chunk) - break; - CHECK_PIXEL_PTR(2 * byte_run); - for (j = 0; j < byte_run; j++) { - *((signed short*)(&pixels[pixel_ptr])) = bytestream2_get_le16(&g2); - pixel_ptr += 2; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n", - pixel_countdown); - } - } - } - - y_ptr += s->frame->linesize[0]; - } - break; - - case FLI_COPY: - case FLI_DTA_COPY: - /* copy the chunk (uncompressed frame) */ - if (chunk_size - 6 > (unsigned int)(FFALIGN(s->avctx->width, 2) * s->avctx->height)*2) { - av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \ - "bigger than image, skipping chunk\n", chunk_size - 6); - bytestream2_skip(&g2, chunk_size - 6); - } else { - - if (bytestream2_get_bytes_left(&g2) < 2 * s->avctx->width * s->avctx->height ) - return AVERROR_INVALIDDATA; - for (y_ptr = 0; y_ptr < s->frame->linesize[0] * s->avctx->height; - y_ptr += s->frame->linesize[0]) { - - pixel_countdown = s->avctx->width; - pixel_ptr = 0; - while (pixel_countdown > 0) { - *((signed short*)(&pixels[y_ptr + pixel_ptr])) = bytestream2_get_le16(&g2); - pixel_ptr += 2; - pixel_countdown--; - } - if (s->avctx->width & 1) - bytestream2_skip(&g2, 2); - } - } - break; - - case FLI_MINI: - /* some sort of a thumbnail? disregard this chunk... */ - bytestream2_skip(&g2, chunk_size - 6); - break; - - default: - av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type); - break; - } - - if (stream_ptr_after_chunk - bytestream2_tell(&g2) >= 0) { - bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2)); - } else { - av_log(avctx, AV_LOG_ERROR, "Chunk overread\n"); - break; - } - - frame_size -= chunk_size; - num_chunks--; - } - - /* by the end of the chunk, the stream ptr should equal the frame - * size (minus 1, possibly); if it doesn't, issue a warning */ - if ((bytestream2_get_bytes_left(&g2) != 0) && (bytestream2_get_bytes_left(&g2) != 1)) - av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \ - "and final chunk ptr = %d\n", buf_size, bytestream2_tell(&g2)); - - if ((ret = av_frame_ref(rframe, s->frame)) < 0) - return ret; - - *got_frame = 1; - - return buf_size; -} - -static int flic_decode_frame_24BPP(AVCodecContext *avctx, - AVFrame *rframe, int *got_frame, - const uint8_t *buf, int buf_size) -{ - FlicDecodeContext *s = avctx->priv_data; - - GetByteContext g2; - int pixel_ptr; - unsigned char palette_idx1; - - unsigned int frame_size; - int num_chunks; - - unsigned int chunk_size; - int chunk_type; - - int i, j, ret; - - int lines; - int compressed_lines; - int line_packets; - int y_ptr; - int byte_run; - int pixel_skip; - int pixel_countdown; - unsigned char *pixels; - int pixel; - unsigned int pixel_limit; - - bytestream2_init(&g2, buf, buf_size); - - if ((ret = ff_reget_buffer(avctx, s->frame, 0)) < 0) - return ret; - - pixels = s->frame->data[0]; - pixel_limit = s->avctx->height * s->frame->linesize[0]; - - frame_size = bytestream2_get_le32(&g2); - bytestream2_skip(&g2, 2); /* skip the magic number */ - num_chunks = bytestream2_get_le16(&g2); - bytestream2_skip(&g2, 8); /* skip padding */ - if (frame_size > buf_size) - frame_size = buf_size; - - if (frame_size < 16) - return AVERROR_INVALIDDATA; - frame_size -= 16; - - /* iterate through the chunks */ - while ((frame_size > 0) && (num_chunks > 0) && - bytestream2_get_bytes_left(&g2) >= 4) { - int stream_ptr_after_chunk; - chunk_size = bytestream2_get_le32(&g2); - if (chunk_size > frame_size) { - av_log(avctx, AV_LOG_WARNING, - "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size); - chunk_size = frame_size; - } - stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size; - - chunk_type = bytestream2_get_le16(&g2); - - - switch (chunk_type) { - case FLI_256_COLOR: - case FLI_COLOR: - /* For some reason, it seems that non-palettized flics do - * include one of these chunks in their first frame. - * Why I do not know, it seems rather extraneous. */ - ff_dlog(avctx, - "Unexpected Palette chunk %d in non-palettized FLC\n", - chunk_type); - bytestream2_skip(&g2, chunk_size - 6); - break; - - case FLI_DELTA: - case FLI_DTA_LC: - y_ptr = 0; - compressed_lines = bytestream2_get_le16(&g2); - while (compressed_lines > 0) { - if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) - break; - if (y_ptr > pixel_limit) - return AVERROR_INVALIDDATA; - line_packets = sign_extend(bytestream2_get_le16(&g2), 16); - if (line_packets < 0) { - line_packets = -line_packets; - if (line_packets > s->avctx->height) - return AVERROR_INVALIDDATA; - y_ptr += line_packets * s->frame->linesize[0]; - } else { - compressed_lines--; - pixel_ptr = y_ptr; - CHECK_PIXEL_PTR(0); - pixel_countdown = s->avctx->width; - for (i = 0; i < line_packets; i++) { - /* account for the skip bytes */ - if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) - break; - pixel_skip = bytestream2_get_byte(&g2); - pixel_ptr += (pixel_skip*3); /* Pixel is 3 bytes wide */ - pixel_countdown -= pixel_skip; - byte_run = sign_extend(bytestream2_get_byte(&g2), 8); - if (byte_run < 0) { - byte_run = -byte_run; - pixel = bytestream2_get_le24(&g2); - CHECK_PIXEL_PTR(3 * byte_run); - for (j = 0; j < byte_run; j++, pixel_countdown -= 1) { - AV_WL24(&pixels[pixel_ptr], pixel); - pixel_ptr += 3; - } - } else { - if (bytestream2_tell(&g2) + 2*byte_run > stream_ptr_after_chunk) - break; - CHECK_PIXEL_PTR(3 * byte_run); - for (j = 0; j < byte_run; j++, pixel_countdown--) { - pixel = bytestream2_get_le24(&g2); - AV_WL24(&pixels[pixel_ptr], pixel); - pixel_ptr += 3; - } - } - } - - y_ptr += s->frame->linesize[0]; - } - } - break; - - case FLI_LC: - av_log(avctx, AV_LOG_ERROR, "Unexpected FLI_LC chunk in non-palettized FLC\n"); - bytestream2_skip(&g2, chunk_size - 6); - break; - - case FLI_BLACK: - /* set the whole frame to 0x00 which is black for 24 bit mode. */ - memset(pixels, 0x00, - s->frame->linesize[0] * s->avctx->height); - break; - - case FLI_BRUN: - y_ptr = 0; - for (lines = 0; lines < s->avctx->height; lines++) { - pixel_ptr = y_ptr; - /* disregard the line packets; instead, iterate through all - * pixels on a row */ - bytestream2_skip(&g2, 1); - pixel_countdown = (s->avctx->width * 3); - - while (pixel_countdown > 0) { - if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) - break; - byte_run = sign_extend(bytestream2_get_byte(&g2), 8); - if (byte_run > 0) { - palette_idx1 = bytestream2_get_byte(&g2); - CHECK_PIXEL_PTR(byte_run); - for (j = 0; j < byte_run; j++) { - pixels[pixel_ptr++] = palette_idx1; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) (linea%d)\n", - pixel_countdown, lines); - } - } else { /* copy bytes if byte_run < 0 */ - byte_run = -byte_run; - if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk) - break; - CHECK_PIXEL_PTR(byte_run); - for (j = 0; j < byte_run; j++) { - palette_idx1 = bytestream2_get_byte(&g2); - pixels[pixel_ptr++] = palette_idx1; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n", - pixel_countdown, lines); - } - } - } - - y_ptr += s->frame->linesize[0]; - } - break; - - case FLI_DTA_BRUN: - y_ptr = 0; - for (lines = 0; lines < s->avctx->height; lines++) { - pixel_ptr = y_ptr; - /* disregard the line packets; instead, iterate through all - * pixels on a row */ - bytestream2_skip(&g2, 1); - pixel_countdown = s->avctx->width; /* Width is in pixels, not bytes */ - - while (pixel_countdown > 0) { - if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk) - break; - byte_run = sign_extend(bytestream2_get_byte(&g2), 8); - if (byte_run > 0) { - pixel = bytestream2_get_le24(&g2); - CHECK_PIXEL_PTR(3 * byte_run); - for (j = 0; j < byte_run; j++) { - AV_WL24(pixels + pixel_ptr, pixel); - pixel_ptr += 3; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n", - pixel_countdown); - } - } else { /* copy pixels if byte_run < 0 */ - byte_run = -byte_run; - if (bytestream2_tell(&g2) + 3 * byte_run > stream_ptr_after_chunk) - break; - CHECK_PIXEL_PTR(3 * byte_run); - for (j = 0; j < byte_run; j++) { - pixel = bytestream2_get_le24(&g2); - AV_WL24(pixels + pixel_ptr, pixel); - pixel_ptr += 3; - pixel_countdown--; - if (pixel_countdown < 0) - av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n", - pixel_countdown); - } - } - } - - y_ptr += s->frame->linesize[0]; - } - break; - - case FLI_COPY: - case FLI_DTA_COPY: - /* copy the chunk (uncompressed frame) */ - if (chunk_size - 6 > (unsigned int)(FFALIGN(s->avctx->width, 2) * s->avctx->height)*3) { - av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \ - "bigger than image, skipping chunk\n", chunk_size - 6); - bytestream2_skip(&g2, chunk_size - 6); - } else { - for (y_ptr = 0; y_ptr < s->frame->linesize[0] * s->avctx->height; - y_ptr += s->frame->linesize[0]) { - - bytestream2_get_buffer(&g2, pixels + y_ptr, 3*s->avctx->width); - if (s->avctx->width & 1) - bytestream2_skip(&g2, 3); - } - } - break; - - case FLI_MINI: - /* some sort of a thumbnail? disregard this chunk... */ - bytestream2_skip(&g2, chunk_size - 6); - break; - - default: - av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type); - break; - } - - if (stream_ptr_after_chunk - bytestream2_tell(&g2) >= 0) { - bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2)); - } else { - av_log(avctx, AV_LOG_ERROR, "Chunk overread\n"); - break; - } - - frame_size -= chunk_size; - num_chunks--; - } - - /* by the end of the chunk, the stream ptr should equal the frame - * size (minus 1, possibly); if it doesn't, issue a warning */ - if ((bytestream2_get_bytes_left(&g2) != 0) && (bytestream2_get_bytes_left(&g2) != 1)) - av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \ - "and final chunk ptr = %d\n", buf_size, bytestream2_tell(&g2)); - - if ((ret = av_frame_ref(rframe, s->frame)) < 0) - return ret; - - *got_frame = 1; - - return buf_size; -} - -static int flic_decode_frame(AVCodecContext *avctx, AVFrame *frame, - int *got_frame, AVPacket *avpkt) -{ - const uint8_t *buf = avpkt->data; - int buf_size = avpkt->size; - if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { - return flic_decode_frame_8BPP(avctx, frame, got_frame, - buf, buf_size); - } else if ((avctx->pix_fmt == AV_PIX_FMT_RGB555) || - (avctx->pix_fmt == AV_PIX_FMT_RGB565)) { - return flic_decode_frame_15_16BPP(avctx, frame, got_frame, - buf, buf_size); - } else if (avctx->pix_fmt == AV_PIX_FMT_BGR24) { - return flic_decode_frame_24BPP(avctx, frame, got_frame, - buf, buf_size); - } - - /* Should not get here, ever as the pix_fmt is processed */ - /* in flic_decode_init and the above if should deal with */ - /* the finite set of possibilities allowable by here. */ - /* But in case we do, just error out. */ - av_log(avctx, AV_LOG_ERROR, "Unknown FLC format, my science cannot explain how this happened.\n"); - return AVERROR_BUG; -} - - -static av_cold int flic_decode_end(AVCodecContext *avctx) -{ - FlicDecodeContext *s = avctx->priv_data; - - av_frame_free(&s->frame); - - return 0; -} - -const FFCodec ff_flic_decoder = { - .p.name = "flic", - CODEC_LONG_NAME("Autodesk Animator Flic video"), - .p.type = AVMEDIA_TYPE_VIDEO, - .p.id = AV_CODEC_ID_FLIC, - .priv_data_size = sizeof(FlicDecodeContext), - .init = flic_decode_init, - .close = flic_decode_end, - FF_CODEC_DECODE_CB(flic_decode_frame), - .p.capabilities = AV_CODEC_CAP_DR1, -}; diff --git a/spaces/congsaPfin/Manga-OCR/logs/Discover the Best Apps and Games with Apps9 the Free and Fast Downloader.md b/spaces/congsaPfin/Manga-OCR/logs/Discover the Best Apps and Games with Apps9 the Free and Fast Downloader.md deleted file mode 100644 index 2b4eb2769cd22aff63f7e9485e65599543595d9b..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Discover the Best Apps and Games with Apps9 the Free and Fast Downloader.md +++ /dev/null @@ -1,142 +0,0 @@ - -

    Apps9: A Tool to Download Multimedia Content for Android

    -

    If you are looking for a way to download all kinds of multimedia content directly to your Android device, you might want to check out Apps9. Apps9 is a tool that lets you download wallpapers, ringtones, and even apps and games (although the latter must be downloaded through Google Play). In this article, we will review what Apps9 is, what features it offers, how to use it, and what are its pros and cons. We will also compare it with some alternatives that you can try if you are not satisfied with Apps9.

    -

    What is Apps9?

    -

    Apps9 is a tool that allows you to download multimedia content for your Android device. It is not an app store, but rather a platform that provides links to various sources of content. You can use Apps9 to browse and download wallpapers, ringtones, and apps and games from different categories and genres. You can also use filters and search options to find the content that you are looking for.

    -

    apps9


    DOWNLOAD ……… https://urlca.com/2uOaho



    -

    Features of Apps9

    -

    Some of the features that Apps9 offers are:

    -
      -
    • It has a large collection of wallpapers and ringtones that you can download for free.
    • -
    • It has a variety of apps and games that you can download through Google Play.
    • -
    • It has a user-friendly interface that is easy to navigate.
    • -
    • It has a fast and reliable download speed.
    • -
    • It has a recommendation system that suggests content based on your preferences.
    • -
    -

    How to use Apps9

    -

    To use Apps9, you need to follow these steps:

    -

    apps9 download
    -apps9 apk
    -apps9 app store
    -apps9 games
    -apps9 wallpaper
    -apps9 ringtones
    -apps9 video downloader
    -apps9 music player
    -apps9 photo editor
    -apps9 launcher
    -apps9 browser
    -apps9 whatsapp
    -apps9 facebook
    -apps9 instagram
    -apps9 tiktok
    -apps9 youtube
    -apps9 netflix
    -apps9 amazon
    -apps9 flipkart
    -apps9 snapchat
    -apps9 twitter
    -apps9 spotify
    -apps9 zoom
    -apps9 gmail
    -apps9 google play
    -apps9 pubg
    -apps9 free fire
    -apps9 clash of clans
    -apps9 candy crush
    -apps9 temple run
    -apps9 subway surfers
    -apps9 angry birds
    -apps9 minecraft
    -apps9 roblox
    -apps9 fortnite
    -apps9 among us
    -apps9 call of duty
    -apps9 gta
    -apps9 fifa
    -apps9 asphalt
    -apps9 pokemon go
    -apps9 zomato
    -apps9 swiggy
    -apps9 uber eats
    -apps9 ola cabs
    -apps9 uber cabs

    -
      -
    1. Download and install the APK file from [Apps9](^1^).
    2. -
    3. Open the app and grant the necessary permissions.
    4. -
    5. Browse the content by categories or use the search bar.
    6. -
    7. Select the content that you want to download and tap on the download button.
    8. -
    9. For wallpapers and ringtones, you can set them as your default or save them in your device.
    10. -
    11. For apps and games, you will be redirected to Google Play where you can install them.
    12. -
    -

    Pros and cons of Apps9

    -

    Like any other tool, Apps9 has its advantages and disadvantages. Here are some of them:

    -

    Pros of Apps9

    -
      -
    • It is free to use and does not require registration or login.
    • -
    • It has a wide range of multimedia content that you can download for your Android device.
    • -
    • It has a simple and intuitive interface that makes it easy to use.
    • -
    • It has a fast and stable download speed that does not consume much data or battery.
    • -
    • It has a smart recommendation system that helps you discover new content.
    • -
    -

    Cons of Apps9

    -
      -
    • It is not an official app store, so it may not be safe or secure to use.
    • -
    • It may contain ads or malware that can harm your device or compromise your privacy.
    • -
    • It may not have the latest or updated versions of apps and games.
    • -
    • It may not have some apps and games that are available on other platforms.
    • -
    • It may not work on some devices or regions due to compatibility or legal issues.
    • -
    -

    Alternatives to Apps9

    -

    If you are not happy with Apps9 or want to try something else, here are some alternatives that you can consider:

    -

    Google Play Store

    -

    The Google Play Store is the official app store for Android devices. It has millions of apps and games that you can download and install on your device. Some of the features that the Google Play Store offers are:

    -
      -
    • It is safe and secure to use, as it has strict policies and guidelines for app developers and users.
    • -
    • It has a huge variety of apps and games that cater to different needs and preferences.
    • -
    • It has regular updates and improvements that enhance the performance and functionality of apps and games.
    • -
    • It has a user-friendly interface that allows you to browse, search, and download apps and games easily.
    • -
    • It has a rating and review system that helps you to find the best and most reliable apps and games.
    • -
    -

    Aptoide

    -

    Aptoide is an alternative app store for Android devices. It allows you to download and install apps and games that are not available on the Google Play Store. It also lets you create your own app store and share it with other users.

    - Some of the features that Aptoide offers are:

    -
      -
    • It is free to use and does not require registration or login.
    • -
    • It has a large collection of apps and games that you can download from different sources.
    • -
    • It has a flexible and customizable interface that allows you to create your own app store.
    • -
    • It has a social network feature that allows you to follow other users and discover new content.
    • -
    • It has a rollback feature that allows you to restore previous versions of apps and games.
    • -
    -

    APKPure

    -

    APKPure is another alternative app store for Android devices. It allows you to download and install APK files of apps and games that are not available on the Google Play Store. It also provides updates and patches for apps and games.

    - Some of the features that APKPure offers are:

    -
      -
    • It is free to use and does not require registration or login.
    • -
    • It has a large collection of APK files of apps and games that you can download from different sources.
    • -
    • It has a simple and elegant interface that allows you to browse, search, and download APK files easily.
    • -
    • It has an update feature that allows you to keep your apps and games up to date.
    • -
    • It has a lightweight design that does not consume much storage space or battery power.
    • -
    -

    Conclusion

    -

    In conclusion, Apps9 is a tool that allows you to download multimedia content for your Android device. It has a variety of wallpapers, ringtones, apps, and games that you can download for free. However, it also has some drawbacks, such as security risks, ads, outdated versions, limited availability, and compatibility issues. Therefore, you should be careful when using Apps9 and always check the source and quality of the content before downloading it. Alternatively, you can try other platforms such as Google Play Store, Aptoide, or APKPure, which offer similar or better features than Apps9.

    -

    Call to action

    -

    If you want to try Apps9 for yourself, you can download it from [Apps9]. However, if you are looking for more reliable and trustworthy platforms, we recommend you to check out Google Play Store, Aptoide, or APKPure. You can find them on their official websites or download their APK files from [APKMirror]. We hope this article was helpful for you. If you have any questions or feedback, please leave them in the comments section below. Thank you for reading!

    -

    Frequently Asked Questions

    -

    Here are some of the most common questions that people ask about Apps9:

    -
      -
    1. Is Apps9 safe to use?
    2. -

      Apps9 is not an official app store, so it may not be safe or secure to use. It may contain ads or malware that can harm your device or compromise your privacy. It may also violate some laws or regulations in some regions. Therefore, you should always scan the APK file before installing it and use a VPN or proxy service if necessary.

      -
    3. Is Apps9 legal to use?
    4. -

      Apps9 may not be legal to use in some regions or countries, as it may infringe the intellectual property rights of some app developers or publishers. It may also violate some terms of service or policies of Google Play Store or other platforms. Therefore, you should always check the legality of the content before downloading it and respect the rights of the original creators.

      -
    5. How do I update Apps9?
    6. -

      To update Apps9, you need to download the latest version of the APK file from [Apps9] or other sources. Then, you need to uninstall the previous version of Apps9 from your device and install the new version. Alternatively, you can enable the auto-update feature in the app settings, which will automatically download and install the updates when they are available.

      -
    7. How do I uninstall Apps9?
    8. -

      To uninstall Apps9, you need to go to your device settings and select the Apps or Applications option. Then, you need to find Apps9 in the list of installed apps and tap on it. Then, you need to tap on the Uninstall button and confirm your action. You can also use a third-party app uninstaller tool to remove Apps9 from your device.

      -
    9. What are some similar tools to Apps9?
    10. -

      Some similar tools to Apps9 are Google Play Store, Aptoide, APKPure, APKMirror, Uptodown, Mobogenie, 9Apps, and more. These tools allow you to download and install apps and games for your Android device from different sources. However, they may have different features, advantages, and disadvantages than Apps9. Therefore, you should compare them carefully before choosing the best one for you.

      -
    11. How do I contact Apps9 support?
    12. -

      If you have any issues or problems with Apps9, you can contact their support team by sending an email to [support@apps9.com]. You can also visit their website [Apps9] or their Facebook page [Apps9] for more information and updates. You can also check their FAQ section or their blog for some tips and tricks on how to use Apps9.

      -

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Hill Climb Racing 2 The Ultimate Online Multiplayer Racing Game for Windows 7.md b/spaces/congsaPfin/Manga-OCR/logs/Hill Climb Racing 2 The Ultimate Online Multiplayer Racing Game for Windows 7.md deleted file mode 100644 index a10fa248a783d7c46ba23c14856ae82e966b69af..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Hill Climb Racing 2 The Ultimate Online Multiplayer Racing Game for Windows 7.md +++ /dev/null @@ -1,118 +0,0 @@ - -
    - H2: How to Download Hill Climb Racing 2 from the Microsoft Store
    - H2: How to Play Hill Climb Racing 2 on PC with BlueStacks Emulator
    - H2: How to Play Hill Climb Racing 2 on Windows PC without Downloading
    - Conclusion: Summarize the main points and invite the reader to try the game
    - FAQs: Answer some common questions about the game and its compatibility with Windows 7 | Table 2: Article with HTML formatting

    Hill Climb Racing 2 Download Windows 7: How to Play the Popular Racing Game on Your PC

    -

    If you love racing games, you might have heard of Hill Climb Racing 2, one of the most popular and addictive games in the genre. Hill Climb Racing 2 is a 2D online multiplayer racing game that lets you customize your character and vehicle, race on dozens of tracks, perform cool stunts, and compete with players from around the world. The game is available for Android and iOS devices, but did you know that you can also play it on your Windows 7 PC? In this article, we will show you how to download and play Hill Climb Racing 2 on your computer using three different methods. Whether you want to use the Microsoft Store, an emulator, or a browser, we have you covered. Read on to find out more!

    -

    hill climb racing 2 download windows 7


    DOWNLOAD ⇒⇒⇒ https://urlca.com/2uO4Vj



    -

    How to Download Hill Climb Racing 2 from the Microsoft Store

    -

    One of the easiest ways to play Hill Climb Racing 2 on your Windows 7 PC is to download it from the Microsoft Store. The Microsoft Store is an online platform that offers various apps and games for Windows devices. To download Hill Climb Racing 2 from the Microsoft Store, follow these steps:

    -
      -
    1. Open your web browser and go to [Hill Climb Racing 2](^1^).
    2. -
    3. Click on the "Get" button and sign in with your Microsoft account.
    4. -
    5. Click on the "Install" button and wait for the download to finish.
    6. -
    7. Once the game is installed, you can launch it from the Start menu or the desktop shortcut.
    8. -
    -

    Congratulations, you can now enjoy Hill Climb Racing 2 on your Windows 7 PC!

    -

    How to Play Hill Climb Racing 2 on PC with BlueStacks Emulator

    -

    Another way to play Hill Climb Racing 2 on your Windows 7 PC is to use an emulator. An emulator is a software that mimics the functionality of another device, such as an Android phone or tablet. By using an emulator, you can run Android apps and games on your computer. One of the best emulators for playing Hill Climb Racing 2 is BlueStacks, which offers a smooth and seamless gaming experience. To play Hill Climb Racing 2 on PC with BlueStacks emulator, follow these steps:

    -
      -
    1. Open your web browser and go to [BlueStacks](^2^).
    2. -
    3. Click on the "Download BlueStacks" button and follow the instructions to install the emulator.
    4. -
    5. Once BlueStacks is installed, launch it and sign in with your Google account.
    6. -
    7. Go to the Google Play Store and search for Hill Climb Racing 2.
    8. -
    9. Click on the "Install" button and wait for the game to download.
    10. -
    11. Once the game is installed, you can launch it from the BlueStacks home screen or app drawer.
    12. -
    -

    Congratulations, you can now enjoy Hill Climb Racing 2 on your Windows 7 PC with BlueStacks emulator!

    -

    hill climb racing 2 pc download windows 7
    -hill climb racing 2 free download for windows 7
    -hill climb racing 2 game download for windows 7
    -hill climb racing 2 download for laptop windows 7
    -hill climb racing 2 download for computer windows 7
    -hill climb racing 2 online play on windows 7
    -hill climb racing 2 install on windows 7
    -hill climb racing 2 setup for windows 7
    -hill climb racing 2 apk download for windows 7
    -hill climb racing 2 app download for windows 7
    -hill climb racing 2 emulator for windows 7
    -hill climb racing 2 bluestacks for windows 7
    -hill climb racing 2 microsoft store for windows 7
    -hill climb racing 2 fingersoft for windows 7
    -hill climb racing 2 mod apk for windows 7
    -hill climb racing 2 hack for windows 7
    -hill climb racing 2 cheats for windows 7
    -hill climb racing 2 tips and tricks for windows 7
    -hill climb racing 2 update for windows 7
    -hill climb racing 2 new version for windows 7
    -hill climb racing 2 best vehicle for windows 7
    -hill climb racing 2 multiplayer on windows 7
    -hill climb racing 2 team mode on windows 7
    -hill climb racing 2 adventure mode on windows 7
    -hill climb racing 2 cups mode on windows 7
    -hill climb racing 2 legendary rank on windows 7
    -hill climb racing 2 skins and outfits for windows 7
    -hill climb racing 2 tuning parts for windows 7
    -hill climb racing 2 coins and gems for windows 7
    -hill climb racing 2 events and challenges for windows 7
    -hill climb racing 2 seasons and rewards for windows 7
    -hill climb racing 2 leaderboards and achievements for windows 7
    -hill climb racing 2 fun and addictive for windows 7
    -hill climb racing 2 physics and graphics for windows 7
    -hill climb racing 2 stunts and flips for windows 7
    -hill climb racing 2 tracks and terrains for windows 7
    -hill climb racing vs hill climb racing [^1^] [^3^] [^4^] [^5^] [^6^] [^8^] [^9^] [^10^] [^11^] [^30^(https://www.bluestacks.com/apps/racing/hill-climb-racing-on-pc.html)]
    -how to play hill climb racing on pc with keyboard
    -how to transfer progress from android to pc in hill climb racing
    -how to get unlimited coins in hill climb racing on pc
    -how to unlock all vehicles in hill climb racing on pc
    -how to change language in hill climb racing on pc
    -how to record gameplay of hill climb racing on pc
    -how to fix lag in hill climb racing on pc
    -how to connect facebook account in hill climb racing on pc
    -how to join a team in hill climb racing on pc
    -how to chat with friends in hill climb racing on pc
    -how to create a custom track in hill climb racing on pc
    -how to use cheat engine in hill climb racing on pc
    -how to play offline in hill climb racing on pc
    -how to sync data across devices in hill climb racing on pc
    -how to get free gems in hill climb racing on pc
    -how to change vehicle color in hill climb racing on pc
    -how to get legendary chests in hill climb racing on pc
    -how to get daily rewards in hill climb racing on pc
    -how to complete achievements in hill climb racing on pc
    -how to level up fast in hill climb racing on pc

    -

    How to Play Hill Climb Racing 2 on Windows PC without Downloading

    -

    If you don't want to download anything on your Windows 7 PC, there is still a way to play Hill Climb Racing 2 online. You can use a browser that supports HTML5 games, such as Chrome or Firefox, and play Hill Climb Racing 2 in your browser without downloading. To play Hill Climb Racing 2 on Windows PC without downloading, follow these steps:

    -
      -
    1. Open your web browser and go to [Hill Climb Racing 2].
    2. -
    3. Click on the "Play" button and wait for the game to load.
    4. -
    5. Once the game is loaded, you can start playing it in your browser.
    6. -
    -

    Congratulations, you can now enjoy Hill Climb Racing 2 on your Windows 7 PC without downloading!

    -

    Conclusion

    -

    Hill Climb Racing 2 is a fun and addictive racing game that you can play on your Windows 7 PC using any of the three methods we discussed in this article. Whether you prefer to download it from the Microsoft Store, use an emulator like BlueStacks, or play it online in your browser, you can experience the thrill of racing on various tracks, customizing your character and vehicle, and competing with other players. Hill Climb Racing 2 is a game that will keep you entertained for hours, so why not give it a try today?

    -

    FAQs

    -

    Is Hill Climb Racing 2 free to play?

    -

    Yes, Hill Climb Racing 2 is free to play, but it contains in-app purchases that allow you to buy coins, gems, and other items to enhance your gameplay.

    -

    Is Hill Climb Racing 2 compatible with Windows 7?

    -

    Yes, Hill Climb Racing 2 is compatible with Windows 7, as long as you have a compatible device and a stable internet connection. You can download it from the Microsoft Store, use an emulator like BlueStacks, or play it online in your browser.

    -

    How do I control Hill Climb Racing 2 on PC?

    -

    You can control Hill Climb Racing 2 on PC using your keyboard or mouse. The default controls are as follows:

    -
      -
    • Left arrow key or A key: Brake
    • -
    • Right arrow key or D key: Accelerate
    • -
    • Up arrow key or W key: Tilt forward
    • -
    • Down arrow key or S key: Tilt backward
    • -
    • Space bar: Boost
    • -
    • Mouse: Click on buttons and menus
    • -
    -

    You can also customize the controls in the settings menu.

    -

    How do I update Hill Climb Racing 2 on PC?

    -

    If you downloaded Hill Climb Racing 2 from the Microsoft Store, you can update it by going to the Store app and clicking on the "Downloads and updates" option. If you are using an emulator like BlueStacks, you can update it by going to the Google Play Store and clicking on the "My apps & games" option. If you are playing Hill Climb Racing 2 online in your browser, you don't need to update it manually, as it will update automatically.

    -

    How do I uninstall Hill Climb Racing 2 from PC?

    -

    If you want to uninstall Hill Climb Racing 2 from your PC, you can do so by following these steps:

    -
      -
    1. If you downloaded Hill Climb Racing 2 from the Microsoft Store, go to the Start menu and right-click on the game icon. Then, click on "Uninstall" and confirm your choice.
    2. -
    3. If you are using an emulator like BlueStacks, launch the emulator and go to the app drawer. Then, drag and drop the game icon to the "Uninstall" option and confirm your choice.
    4. -
    5. If you are playing Hill Climb Racing 2 online in your browser, you don't need to uninstall it, as it is not stored on your PC.
    6. -

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Hills of Steel 2 APK Mod The Most Addictive Multiplayer Game Ever.md b/spaces/congsaPfin/Manga-OCR/logs/Hills of Steel 2 APK Mod The Most Addictive Multiplayer Game Ever.md deleted file mode 100644 index c471a5b9bca40bbc9e62ba3f6b1e096b0a2bda48..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Hills of Steel 2 APK Mod The Most Addictive Multiplayer Game Ever.md +++ /dev/null @@ -1,92 +0,0 @@ -
    -

    Hills of Steel 2 APK Mod: A Fun and Action-Packed Tank Game

    -

    If you are looking for a fun and action-packed tank game, you should check out Hills of Steel 2 APK Mod. This is a sequel to the popular Hills of Steel game, which has over 50 million downloads on Google Play Store. In this game, you can control various tanks and fight against other players in real-time multiplayer battles. You can also customize your tanks with different items and upgrades, and enjoy various game modes and maps.

    -

    In this article, we will tell you everything you need to know about Hills of Steel 2 APK Mod, including how to download and install it, what are its features, how to play it, and some tips and tricks to help you win more battles. Let's get started!

    -

    hills of steel 2 apk mod


    Download 🔗 https://urlca.com/2uO7Z7



    -

    How to Download and Install Hills of Steel 2 APK Mod

    -

    Downloading and installing Hills of Steel 2 APK Mod is very easy. Just follow these simple steps:

    -
      -
    1. Download the APK file from a trusted source. You can use the link provided in this article or search for it online.
    2. -
    3. Enable unknown sources on your device. To do this, go to Settings > Security > Unknown Sources and toggle it on.
    4. -
    5. Install the APK file by tapping on it and following the instructions.
    6. -
    7. Launch the game and enjoy

      What are the Features of Hills of Steel 2 APK Mod?

      -

      Hills of Steel 2 APK Mod is not just a regular tank game. It has many features that make it more fun and exciting than other similar games. Here are some of the features that you can enjoy with Hills of Steel 2 APK Mod:

      -

      hills of steel 2 mod apk unlimited money
      -hills of steel 2 hack apk download
      -hills of steel 2 mod apk latest version
      -hills of steel 2 mod apk android 1
      -hills of steel 2 mod apk revdl
      -hills of steel 2 mod apk rexdl
      -hills of steel 2 mod apk happymod
      -hills of steel 2 mod apk free shopping
      -hills of steel 2 mod apk no root
      -hills of steel 2 mod apk offline
      -hills of steel 2 mod apk online
      -hills of steel 2 mod apk all tanks unlocked
      -hills of steel 2 mod apk unlimited gems and coins
      -hills of steel 2 mod apk unlimited ammo and fuel
      -hills of steel 2 mod apk unlimited stars and medals
      -hills of steel 2 mod apk unlimited health and shield
      -hills of steel 2 mod apk unlimited diamonds and gold
      -hills of steel 2 mod apk unlimited everything
      -hills of steel 2 mod apk download for android
      -hills of steel 2 mod apk download for pc
      -hills of steel 2 mod apk download for ios
      -hills of steel 2 mod apk download for windows 10
      -hills of steel 2 mod apk download for laptop
      -hills of steel 2 mod apk download for mac
      -hills of steel 2 mod apk download for chromebook
      -hills of steel 2 mod apk download link
      -hills of steel 2 mod apk download uptodown
      -hills of steel 2 mod apk download apkpure
      -hills of steel 2 mod apk download mob.org
      -hills of steel 2 mod apk download android republic
      -hills of steel 2 cheats apk free download
      -hills of steel 2 hack tool apk free download
      -hills of steel 2 hack version apk free download
      -hills of steel 2 hacked game apk free download
      -hills of steel 2 premium mod apk free download
      -hills of steel 2 pro mod apk free download
      -hills of steel 2 full mod apk free download
      -hills of steel 2 mega mod apk free download
      -hills of steel 2 god mode apk free download
      -hills of steel 2 vip mod apk free download

      -
        -
      • Unlimited coins and gems: With this mod, you don't have to worry about running out of coins and gems, which are the main currencies in the game. You can use them to upgrade your tanks and buy new ones, as well as other items and boosts. You can also use them to unlock premium tanks and modes that are otherwise unavailable or require real money.
      • -
      • Access to all tanks and modes: With this mod, you can access all the tanks and modes in the game without any ads or restrictions. You can choose from over 20 tanks, each with its own unique abilities and features. You can also play in different modes, such as Team Deathmatch, Domination, Capture the Flag, Boss Battle, and more. You can also play in different maps, such as Desert, Forest, Snow, and more.
      • -
      • Real-time multiplayer battles: With this mod, you can play with other players from around the world in real-time multiplayer battles. You can join a team or create your own, and compete against other teams for glory and rewards. You can also chat with your teammates and opponents, and make new friends or rivals.
      • -
      • Various game modes and maps: With this mod, you can enjoy various game modes and maps that will keep you entertained for hours. You can play in Team Deathmatch, where you have to eliminate the enemy team before they eliminate yours. You can play in Domination, where you have to capture and hold strategic points on the map. You can play in Capture the Flag, where you have to steal the enemy flag and bring it back to your base. You can play in Boss Battle, where you have to defeat a powerful boss tank with your team. You can also play in different maps, such as Desert, Forest, Snow, and more.
      • -
      • Stunning graphics and sound effects: With this mod, you can enjoy stunning graphics and sound effects that will make you feel like you are in a real tank battle. The game has realistic physics and animations, as well as colorful and detailed graphics. The game also has immersive sound effects and music that will enhance your gaming experience.
      • -
      -

      How to Play Hills of Steel 2 APK Mod?

      -

      Playing Hills of Steel 2 APK Mod is very easy and intuitive. You just need to follow these simple steps:

      -
        -
      1. Choose your tank and mode: After launching the game, you can choose your tank from the garage. You can also upgrade your tank or buy a new one with coins and gems. Then, you can choose the mode you want to play from the lobby. You can either join an existing match or create your own.
      2. -
      3. Control your tank with simple touch controls: Once you enter a match, you can control your tank with simple touch controls. You can move your tank forward or backward by tapping on the left or right side of the screen. You can also aim and shoot by dragging on the screen. You can also use special abilities by tapping on the icons on the bottom of the screen.
      4. -
      5. Shoot and destroy enemy tanks and bases: Your main objective is to shoot and destroy enemy tanks and bases, depending on the mode you are playing. You can also collect coins and gems that drop from destroyed enemies or crates. You can use them to upgrade your tank or buy new ones.
      6. -
      7. Collect coins and gems to unlock more tanks and items: As you play the game, you will earn coins and gems that you can use to unlock more tanks and items. You can also get unlimited coins and gems by downloading the modded version of the game. You can use them to upgrade your tanks to increase their power and durability, or buy new ones with different abilities and features. You can also use them to unlock premium tanks and modes that are otherwise unavailable or require real money.
      8. -

      Tips and Tricks for Hills of Steel 2 APK Mod

      -

      Hills of Steel 2 APK Mod is a fun and action-packed tank game, but it can also be challenging and competitive. If you want to improve your skills and win more battles, you should follow these tips and tricks:

      -
        -
      • Use different tanks for different situations: Each tank has its own strengths and weaknesses, and you should use them accordingly. For example, the Titan is a heavy tank that can deal a lot of damage and withstand a lot of hits, but it is also slow and bulky. The Cobra is a fast and agile tank that can dodge and flank enemies, but it has low armor and firepower. The Reaper is a stealthy tank that can cloak and surprise enemies, but it has limited ammo and visibility. You should experiment with different tanks and see which one suits your playstyle and preference.
      • -
      • Upgrade your tanks to increase their power and durability: As you play the game, you will earn coins and gems that you can use to upgrade your tanks. You can upgrade their engine, armor, weapon, and special ability. You can also buy new tanks with different abilities and features. Upgrading your tanks will make them more powerful and durable, and give you an edge over your enemies.
      • -
      • Use the terrain to your advantage: The game has various maps with different terrains, such as hills, bridges, ramps, tunnels, and more. You should use them to your advantage, as they can affect your movement and combat. For example, you can use hills to gain momentum and jump over enemies or obstacles. You can use bridges to cross gaps or ambush enemies. You can use ramps to launch yourself into the air or land on enemies. You can use tunnels to hide or escape from enemies.
      • -
      • Team up with other players and communicate with them: The game has real-time multiplayer battles, where you can team up with other players from around the world. You can join a team or create your own, and compete against other teams for glory and rewards. You can also chat with your teammates and opponents, and make new friends or rivals. You should cooperate with your teammates and communicate with them, as teamwork is essential for winning battles. You should also be respectful and friendly to other players, as this is a game for fun and entertainment.
      • -
      -

      Conclusion

      -

      Hills of Steel 2 APK Mod is a fun and action-packed tank game that you should try if you love tank games. You can control various tanks and fight against other players in real-time multiplayer battles. You can also customize your tanks with different items and upgrades, and enjoy various game modes and maps. You can download and install Hills of Steel 2 APK Mod easily by following the steps in this article. You can also enjoy unlimited coins and gems, access to all tanks and modes, stunning graphics and sound effects, and more with this mod. You can also improve your skills and win more battles by following the tips and tricks in this article.

      -

      We hope you enjoyed this article and found it helpful. If you have any questions or feedback, please feel free to leave them in the comments section below. Thank you for reading!

      -

      FAQs

      -
        -
      • Q1: Is Hills of Steel 2 APK Mod safe to download and install?
      • -
      • A1: Yes, as long as you download it from a reliable source. However, you should always be careful when installing apps from unknown sources.
      • -
      • Q2: Can I play Hills of Steel 2 APK Mod offline?
      • -
      • A2: No, you need an internet connection to play this game. You can play solo or with other players online.
      • -
      • Q3: How can I get more coins and gems in Hills of Steel 2 APK Mod?
      • -
      • A3: You can get unlimited coins and gems by downloading the modded version of the game. You can also earn them by playing the game and completing missions.
      • -
      • Q4: What are the best tanks in Hills of Steel 2 APK Mod?
      • -
      • A4: There is no definitive answer to this question, as different tanks have different strengths and weaknesses. You should try them all and see which one suits your playstyle and preference. Some of the popular tanks are Titan, Mammoth, Cobra, Reaper, and Phoenix.
      • -
      • Q5: How can I contact the developers of Hills of Steel 2 APK Mod?
      • -
      • A5: You can contact them through their official website, Facebook page, or email address I have already written the article for you, as you requested. There is nothing more to write, unless you want me to revise or edit something. If you are satisfied with the article, please let me know. If you have any feedback or suggestions, please also let me know. Thank you for choosing me as your content writer. I hope you enjoyed my work.

        197e85843d
        -
        -
        \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/How to Install Diablo Immortal on Your Android Device - APK Download Link.md b/spaces/congsaPfin/Manga-OCR/logs/How to Install Diablo Immortal on Your Android Device - APK Download Link.md deleted file mode 100644 index b8ccf95178acff500f5911f65022764c70492a18..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/How to Install Diablo Immortal on Your Android Device - APK Download Link.md +++ /dev/null @@ -1,139 +0,0 @@ -
        -

        Diablo Immortal APK Download for Android: Everything You Need to Know

        -

        Diablo Immortal is a brand-new mobile game from Blizzard Entertainment that brings the legendary action role-playing game series to your smartphone. Set between the events of Diablo II and Diablo III, Diablo Immortal lets you explore the dark realm of Sanctuary, fight against hordes of demons, collect epic loot, and join forces with other players in a massively multiplayer online experience. Whether you are a fan of Diablo or a newcomer to the franchise, you might be wondering how to download Diablo Immortal APK for your Android device. In this article, we will show you how to do that, as well as what features and requirements you can expect from the game, and some tips and tricks to help you succeed in your quest.

        -

        diablo immortal apk download for android


        Downloadhttps://urlca.com/2uO5tU



        -

        How to Download Diablo Immortal APK for Android Devices

        -

        There are two ways to download Diablo Immortal APK for your Android device: from the official Google Play Store or from a third-party website. Here are the steps for each method:

        -

        From Google Play Store

        -

        This is the easiest and safest way to download Diablo Immortal APK for your Android device. All you need to do is follow these steps:

        -
          -
        1. Open the Google Play Store app on your device.
        2. -
        3. Search for "Diablo Immortal" in the search bar.
        4. -
        5. Tap on the game icon and then tap on "Install".
        6. -
        7. Wait for the download and installation to finish.
        8. -
        9. Launch the game and enjoy!
        10. -
        -

        From a Third-Party Website

        -

        This is an alternative way to download Diablo Immortal APK for your Android device, but it comes with some risks. You might encounter malware, viruses, or other harmful files that could damage your device or compromise your security. Therefore, we do not recommend this method unless you are absolutely sure about the source and the file. If you still want to try this method, here are the steps:

        -

        How to download diablo immortal apk for android devices
        -Diablo immortal apk latest version free download
        -Diablo immortal android game review and gameplay
        -Diablo immortal apk mod unlimited money and gems
        -Diablo immortal apk offline mode and multiplayer features
        -Diablo immortal apk download from uptodown.com[^2^]
        -Diablo immortal apk compatibility and requirements
        -Diablo immortal apk installation guide and troubleshooting
        -Diablo immortal apk update and patch notes
        -Diablo immortal apk best classes and builds
        -Diablo immortal apk tips and tricks for beginners
        -Diablo immortal apk cheats and hacks
        -Diablo immortal apk rewards and achievements
        -Diablo immortal apk dungeons and raids
        -Diablo immortal apk lore and story
        -Diablo immortal apk graphics and performance
        -Diablo immortal apk feedback and ratings
        -Diablo immortal apk bugs and issues
        -Diablo immortal apk news and events
        -Diablo immortal apk forums and community
        -Diablo immortal apk pre-registration and beta access
        -Diablo immortal apk release date and launch details
        -Diablo immortal apk comparison with diablo 3
        -Diablo immortal apk cross-platform and cross-save support
        -Diablo immortal apk blizzard account and login problems
        -Diablo immortal apk refund policy and customer service
        -Diablo immortal apk in-app purchases and microtransactions
        -Diablo immortal apk system settings and customization options
        -Diablo immortal apk soundtrack and voice acting
        -Diablo immortal apk characters and skills
        -Diablo immortal apk items and equipment
        -Diablo immortal apk enemies and bosses
        -Diablo immortal apk quests and challenges
        -Diablo immortal apk world and environment
        -Diablo immortal apk pvp and leaderboards
        -Download diablo immortal from google play store[^1^]
        -Download diablo immortal from diabloimmortal.com[^3^]
        -Download diablo immortal from apkpure.com
        -Download diablo immortal from apkmirror.com
        -Download diablo immortal from apknite.com
        -Download diablo immortal from apktada.com
        -Download diablo immortal from apkmody.io
        -Download diablo immortal from apksfull.com
        -Download diablo immortal from apktovi.com
        -Download diablo immortal from apkgk.com

        -
          -
        1. Find a reliable third-party website that offers Diablo Immortal APK file. You can use a search engine or ask other players for recommendations.
        2. -
        3. Download the APK file to your device. Make sure you have enough storage space and a stable internet connection.
        4. -
        5. Enable "Unknown Sources" on your device settings. This will allow you to install apps from sources other than Google Play Store.
        6. -
        7. Locate the APK file on your device and tap on it.
        8. -
        9. Follow the instructions on the screen to install the game.
        10. -
        11. Launch the game and enjoy!
        12. -
        -

        What are the Features and Requirements of Diablo Immortal

        -

        Diablo Immortal is a stunning and immersive game that offers a lot of features for players to enjoy. Here are some of them:

        -
          -
        • Six iconic and customizable classes: Barbarian, Demon Hunter, Necromancer, Crusader, Monk, and Wizard.
        • -
        • New abilities, set items, legendary weapons, and gems to enhance your character.
        • -
        • A rich and dynamic story that reveals new secrets about Sanctuary and its inhabitants.
        • -
        • A vast and diverse world to explore, from the war-torn surroundings of Wortham to the grand city of Westmarch and the jungles of Bilefen.
        • -
        • A variety of quests, bosses, dungeons, events, and challenges to test your skills and reward you with loot.
        • -
        • A cross-platform and cross-save feature that lets you play on PC or mobile with the same account.
        • -
        • A massively multiplayer online experience that lets you meet, socialize, and cooperate with other players from around the world.
        • -
        • A PvP mode that lets you compete against other players in arenas or battlegrounds.
        • -
        • A voice chat feature that lets you communicate with your friends or teammates in real time.
        • -
        -

        To play Diablo Immortal on your Android device, you need to meet the following requirements:

        - - - - - - - - - - - - - - - - - - - - - - - - - -
        Minimum RequirementsRecommended Requirements
        Android 5.0 or higherAndroid 8.0 or higher
        2 GB of RAM or more4 GB of RAM or more
        At least 4 GB of free storage spaceAt least 8 GB of free storage space
        A stable internet connection (Wi-Fi or cellular)A high-speed internet connection (Wi-Fi or cellular)
        A compatible device (see the list here)A high-end device (see the list here)
        -

        What are Some Tips and Tricks for Playing Diablo Immortal

        -

        Diablo Immortal is a fun and challenging game that requires some strategy and skill to master. Here are some tips and tricks that can help you improve your gameplay and enjoy the game more:

        -
          -
        • Choose a class that suits your playstyle and preferences. Each class has its own strengths, weaknesses, abilities, and equipment. Experiment with different classes and find the one that works best for you.
        • -
        • Customize your character with the Paragon system. This system lets you allocate points to different attributes, such as strength, dexterity, intelligence, vitality, and more. You can also unlock and upgrade different talents that enhance your abilities and skills.
        • -
        • Collect and equip the best gear for your character. Gear can have different rarities, stats, affixes, and set bonuses that affect your performance. You can also use gems to socket your gear and add extra effects. Look for gear that complements your class, build, and playstyle.
        • -
        • Use the crafting system to create and improve your gear. You can use materials that you find or salvage from unwanted items to craft new items or enhance existing ones. You can also use legendary materials to reforge legendary items or add legendary powers to other items.
        • -
        • Join a clan or create your own. Clans are groups of players that can chat, trade, cooperate, and compete with each other. You can also access clan-exclusive features, such as clan quests, clan dungeons, clan wars, and clan rankings.
        • -
        • Participate in events and challenges. Events are special activities that occur periodically in the game world, such as invasions, bounties, rifts, trials, and more. Challenges are tasks that you can complete to earn rewards, such as achievements, titles, badges, and more.
        • -
        • Play with other players. Diablo Immortal is a multiplayer game that lets you interact with other players in various ways. You can team up with other players to complete quests, dungeons, raids, and more. You can also chat with other players using text or voice messages.
        • -
        • Have fun! Diablo Immortal is a game that offers a lot of content and options for players to enjoy. You can explore the world at your own pace, follow the story at your own discretion, or focus on the aspects that interest you the most. The choice is yours!
        • -
        -

        Conclusion: Summary and Recommendations

        -

        In conclusion, Diablo Immortal is a fantastic mobile game that brings the Diablo franchise to your fingertips. You can download Diablo Immortal APK for your Android device from the Google Play Store or from a third-party website, but be careful of the risks involved in the latter option. You can also enjoy the many features and requirements of the game, such as the classes, the gear, the story, the world, the multiplayer mode, and more. Finally, you can use some tips and tricks to improve your gameplay and have more fun.

        -

        If you are looking for a mobile game that offers action, adventure, loot, and social interaction, then Diablo Immortal is the game for you. Download it today and join millions of players in the epic saga of Sanctuary!

        -

        FAQs: Five Common Questions and Answers about Diablo Immortal

        -

        Here are some of the most frequently asked questions about Diablo Immortal:

        -

        Q: Is Diablo Immortal free to play?

        -

        A: Yes, Diablo Immortal is free to play. You can download and play the game without paying anything. However, there are some optional in-game purchases that you can make to enhance your experience, such as cosmetic items, inventory slots, stash tabs, etc.

        -

        Q: Is Diablo Immortal online only?

        -

        A: Yes, Diablo Immortal is online only. You need a stable internet connection to play the game and access its features. You also need to create or link a Blizzard account to play the game.

        -

        Q: Is Diablo Immortal compatible with my device?

        -

        A: Diablo Immortal is compatible with most Android devices that meet the minimum requirements. You can check the list of compatible devices here. If your device is not on the list, you might still be able to play the game, but you might encounter some performance issues or bugs.

        -

        Q: How can I contact the customer support or report a problem?

        -

        A: You can contact the customer support or report a problem by using the in-game feedback system. To access it, tap on the menu icon on the top left corner of the screen, then tap on "Feedback". You can also visit the official website or the official forums for more information and assistance.

        -

        Q: When will Diablo Immortal be released?

        -

        A: Diablo Immortal is currently in development and testing stages. There is no official release date yet, but you can sign up for pre-registration on the Google Play Store or the official website to get notified when the game is available. You can also follow the official social media channels for the latest news and updates.

        401be4b1e0
        -
        -
        \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/How to Install and Enjoy Farlight 84 on PC with an Android Emulator.md b/spaces/congsaPfin/Manga-OCR/logs/How to Install and Enjoy Farlight 84 on PC with an Android Emulator.md deleted file mode 100644 index 1ad118094f5edb6fe2f08e529dae3ae5366d2e43..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/How to Install and Enjoy Farlight 84 on PC with an Android Emulator.md +++ /dev/null @@ -1,107 +0,0 @@ - -

        How to Download Farlight 84 on PC

        -

        Farlight 84 is a popular battle royale game that features a diverse roster of heroes, spectacular vehicles, funky weapons, and jetpacks. It is available for free on Android and iOS devices, but what if you want to play it on your PC? In this article, we will show you how to download Farlight 84 on PC using different methods. Whether you have Windows 11 or an older version of Windows, you can enjoy this game on a bigger screen and with better controls.

        -

        how to download farlight 84 in pc


        Download Zip ✵✵✵ https://urlca.com/2uO5E3



        -

        What is Farlight 84?

        -

        Farlight 84 is a futuristic shooter game that combines elements of battle royale, hero shooter, and sci-fi. It was developed by Farlight Games and released in April 2023. The game takes place in a post-apocalyptic world where survivors fight for resources and glory. You can choose from over a dozen characters, each with their own unique skills and abilities. You can also customize your weapons, vehicles, and jetpacks to suit your playstyle. The game offers multiple game modes, including classic battle royale, hunt, and ranked games.

        -

        Why Play Farlight 84 on PC?

        -

        While Farlight 84 is designed for mobile devices, playing it on PC has some advantages. For one thing, you can enjoy the game's graphics and animations on a larger screen, which can enhance the immersion and excitement. For another thing, you can use your mouse and keyboard or a controller to control your character, which can give you more accuracy and agility. Playing on PC can also improve your performance and reduce lag, especially if you have a powerful PC.

        -

        How to Play Farlight 84 on PC with Windows 11

        -

        If you have Windows 11, you can play Android games on your PC using the native Android emulation feature. This feature lets you run Android apps without needing to install a third-party emulator. Here are the steps to play Farlight 84 on PC with Windows 11:

        -
          -
        1. Open the Microsoft Store app on your PC and search for "Farlight 84".
        2. -
        3. Click on the game icon and then click on "Install".
        4. -
        5. Wait for the game to download and install.
        6. -
        7. Launch the game from the Microsoft Store app or from your Start menu.
        8. -
        9. Sign in with your Google account or create a new one.
        10. -
        11. Enjoy playing Farlight 84 on your PC!
        12. -
        -

        How to Play Farlight 84 on PC with Android Emulators

        -

        If you don't have Windows 11 or you prefer using an Android emulator, you can also play Farlight 84 on PC with various emulators. An Android emulator is a software that simulates an Android device on your PC. You can download and install Android games and apps on the emulator and use your PC's hardware to run them. Here are some of the best Android emulators for playing Farlight 84 on PC:

        -
          -
        • Bluestacks: Bluestacks is one of the most popular and widely used Android emulators. It has a simple and user-friendly interface, high compatibility, and fast performance. It also has features such as keyboard mapping, game mode, and multi-instance. You can download Bluestacks from its official website and follow the instructions to install and set it up. Then, you can search for Farlight 84 in the Google Play Store app and install it. You can also download the game's APK file from here and drag and drop it to the Bluestacks window to install it.
        • -
        • Nox Player: Nox Player is another popular Android emulator that offers a smooth and stable gaming experience. It has features such as keyboard and mouse control, game optimization, and screen recording. You can download Nox Player from its official website and follow the instructions to install and set it up. Then, you can search for Farlight 84 in the Google Play Store app and install it. You can also download the game's APK file from here and drag and drop it to the Nox Player window to install it.
        • -
        • Gameloop: Gameloop is an Android emulator that is specially designed for gaming. It has features such as turbo engine, anti-aliasing, smart keymapping, and exclusive game center. You can download Gameloop from its official website and follow the instructions to install and set it up. Then, you can search for Farlight 84 in the game center app and install it. You can also download the game's APK file from here and drag and drop it to the Gameloop window to install it.
        • -
        -

        How to Play Farlight 84 on PC with Parsec

        -

        If you have a PC that can run Farlight 84 but you want to play it on your Android device, you can use Parsec to stream the game from your PC to your device. Parsec is a software that lets you remotely access your PC from anywhere. You can use it to play PC games on your phone or tablet with low latency and high quality. Here are the steps to play Farlight 84 on PC with Parsec:

        -

        How to install farlight 84 on your computer
        -Farlight 84 pc download guide and tips
        -Best way to play farlight 84 on pc with bluestacks
        -How to get farlight 84 for free on pc
        -Farlight 84 steam version download and review
        -How to run farlight 84 on pc without emulator
        -Farlight 84 pc system requirements and settings
        -How to update farlight 84 on pc
        -How to fix farlight 84 pc errors and bugs
        -How to join farlight 84 pc community and discord
        -How to play farlight 84 on pc with controller
        -Farlight 84 pc gameplay and features
        -How to unlock all heroes in farlight 84 pc
        -How to win in farlight 84 pc hunt mode
        -How to customize your character in farlight 84 pc
        -How to stream farlight 84 on pc with obs
        -How to record and edit farlight 84 videos on pc
        -How to improve your skills in farlight 84 pc
        -How to rank up in farlight 84 pc leaderboard
        -How to earn and spend coins in farlight 84 pc
        -How to get more weapons and vehicles in farlight 84 pc
        -How to use cheats and hacks in farlight 84 pc
        -How to troubleshoot farlight 84 pc issues and crashes
        -How to access farlight 84 pc beta and early access
        -How to download farlight 84 on mac and linux
        -Farlight 84 pc vs mobile comparison and pros and cons
        -How to transfer your data from mobile to pc in farlight 84
        -How to play with friends in farlight 84 cross-platform
        -How to change your language and region in farlight 84 pc
        -How to enable voice chat and microphone in farlight 84 pc
        -How to adjust graphics and sound quality in farlight 84 pc
        -How to optimize your performance and fps in farlight 84 pc
        -How to use keyboard and mouse shortcuts in farlight 84 pc
        -How to redeem codes and coupons in farlight 84 pc
        -How to contact support and report bugs in farlight 84 pc
        -Farlight 84 pc news and updates
        -Farlight 84 pc strategies and guides
        -Farlight 84 pc reviews and ratings
        -Farlight 84 pc best heroes and loadouts
        -Farlight 84 pc best weapons and vehicles
        -Farlight 84 pc best maps and locations
        -Farlight 84 pc best skins and outfits
        -Farlight 84 pc best moments and highlights
        -Farlight 84 pc fan art and wallpapers
        -Farlight 84 pc memes and jokes
        -Farlight 84 pc trivia and facts
        -Farlight 84 pc competitions and tournaments
        -Farlight 84 pc modding and customization

        -
          -
        1. Download Parsec from its official website and install it on your PC.
        2. -
        3. Launch Parsec on your PC and create an account or sign in with your existing account.
        4. -
        5. Download Parsec from Google Play Store or Apple App Store and install it on your Android device.
        6. -
        7. Launch Parsec on your device and sign in with the same account as your PC.
        8. -
        9. Select your PC from the list of available devices and tap on "Connect".
        10. -
        11. Once connected, you can see your PC's screen on your device.
        12. -
        13. Launch Farlight 84 on your PC and play it on your device using touch controls or a controller.
        14. -
        -

        Conclusion

        -

        Farlight 84 is a fun and exciting game that you can play on your PC using different methods. You can use Windows 11's native Android emulation feature, an Android emulator such as Bluestacks, Nox Player, or Gameloop, or a streaming software such as Parsec. Each method has its own pros and cons, so you can choose the one that suits you best. Whichever method you choose, you can enjoy Farlight 84 on a bigger screen and with better controls.

        -

        FAQs

        -

        Is Farlight 84 free to play?

        -

        Yes, Farlight 84 is free to play on both Android and iOS devices. However, it does have in-app purchases that allow you to buy items such as skins, weapons, vehicles, jetpacks, coins, gems, and crates.

        -

        Can I play Farlight 84 with my friends on different platforms?

        -

        Yes, Farlight 84 supports cross-platform play between Android and iOS devices. However, it does not support cross-play with PC players yet.

        - What are the minimum requirements to run Farlight 84 on PC?

    -

    The minimum requirements to run Farlight 84 on PC depend on the method you use. If you use Windows 11's native Android emulation feature, you need a PC that meets the minimum requirements for Windows 11. If you use an Android emulator, you need a PC that meets the minimum requirements for the emulator. If you use Parsec, you need a PC that can run Farlight 84 smoothly and a device that can stream it without lag.

    -

    How can I earn rewards in Farlight 84?

    -

    You can earn rewards in Farlight 84 by completing various tasks and challenges. Some of the ways to earn rewards are:

    -
      -
    • Playing daily and weekly missions.
    • -
    • Participating in events and seasons.
    • -
    • Ranking up in the leaderboards.
    • -
    • Opening crates and chests.
    • -
    • Watching ads and videos.
    • -
    • Inviting and playing with friends.
    • -
    -

    Where can I find more information about Farlight 84?

    -

    You can find more information about Farlight 84 by visiting its official website, Facebook page, Twitter account, Instagram account, YouTube channel, or Discord server. You can also check out some of the reviews and guides from other players and experts.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Play FIFA Soccer on PC and Mac Experience the Authentic Soccer Action and Real-Time 11v11 Gameplay with BlueStacks.md b/spaces/congsaPfin/Manga-OCR/logs/Play FIFA Soccer on PC and Mac Experience the Authentic Soccer Action and Real-Time 11v11 Gameplay with BlueStacks.md deleted file mode 100644 index eea99bcffebb832c44a67b0ac5463522fdbff0bf..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Play FIFA Soccer on PC and Mac Experience the Authentic Soccer Action and Real-Time 11v11 Gameplay with BlueStacks.md +++ /dev/null @@ -1,152 +0,0 @@ -
    -

    FIFA apk windows: How to play the popular soccer game on your PC

    -

    If you are a fan of soccer games, you have probably heard of FIFA, the best-selling game series by EA Sports. FIFA is a realistic and immersive simulation of the world's most popular sport, featuring hundreds of teams, players, stadiums, and competitions. You can play FIFA on various platforms, such as PlayStation, Xbox, Nintendo Switch, and mobile devices. But did you know that you can also play FIFA on your PC using an apk file? In this article, we will explain what FIFA apk windows is, why you might want to play it, how to download and install it, how to play it, and what are some alternatives to it.

    -

    fifa apk windows


    Download Filehttps://urlca.com/2uO8yx



    -

    What is FIFA apk windows?

    -

    A brief introduction to FIFA, the soccer game series by EA Sports

    -

    FIFA is a long-running game series that started in 1993 with FIFA International Soccer. Since then, EA Sports has released a new edition every year, with updated rosters, graphics, gameplay features, and modes. The latest installment is FIFA 22, which was released in September 2021. FIFA is known for its authenticity and realism, as it has official licenses from various soccer organizations, such as FIFA (the international governing body of soccer), UEFA (the European soccer association), and many national leagues and clubs. FIFA also features some of the world's best soccer players as cover stars and ambassadors.

    -

    An explanation of what apk files are and how they can be used to run Android apps on PC

    -

    An apk file is a file format that is used to distribute and install applications on Android devices. Apk stands for Android Package Kit, and it contains all the necessary files and data for an app to run. Apk files can be downloaded from various sources online, such as Google Play Store or third-party websites. However, apk files are not compatible with Windows operating systems by default. To run an apk file on your PC, you need to use an Android emulator. An Android emulator is a software that mimics the Android environment on your PC. It allows you to run Android apps and games on your PC as if you were using an Android device. There are many Android emulators available for Windows 10 users. Some of the most popular ones are BlueStacks, GameLoop, NoxPlayer, etc.

    -

    Why play FIFA apk windows?

    -

    The benefits of playing FIFA on PC

    -

    There are many reasons why you might want to play FIFA on your PC, such as:

    -
      -
    • Better graphics: Playing FIFA on PC can give you a more realistic and immersive visual experience, as you can enjoy the high-quality graphics, animations, and effects of the game. You can also adjust the graphics settings to suit your preferences and PC specifications.
    • -
    • Larger screen: Playing FIFA on PC can also give you a more comfortable and enjoyable viewing experience, as you can see the game on a bigger and wider screen. You can also use a monitor or a TV to connect your PC and play FIFA on an even larger display.
    • -
    • Keyboard and mouse controls: Playing FIFA on PC can also give you more options and flexibility in terms of controls, as you can use a keyboard and mouse to play the game. You can also customize your key bindings and mouse sensitivity to suit your style and skills.
    • -
    -

    The drawbacks of playing FIFA on PC

    -

    However, playing FIFA on PC also has some drawbacks, such as:

    -

    fifa mobile pc download
    -fifa soccer emulator for windows
    -how to play fifa on pc with bluestacks
    -fifa mobile gameloop emulator
    -fifa football pc game
    -download fifa soccer on windows 10
    -fifa mobile for pc free
    -best android emulator for fifa soccer
    -fifa mobile windows version
    -play fifa soccer on pc online
    -fifa mobile pc requirements
    -fifa soccer pc controls
    -how to install fifa apk on windows
    -fifa mobile mac download
    -fifa soccer emulator for mac
    -how to play fifa on mac with bluestacks
    -fifa mobile gameloop mac
    -fifa football mac game
    -download fifa soccer on macos
    -fifa mobile for mac free
    -best android emulator for fifa football
    -fifa mobile mac version
    -play fifa football on mac online
    -fifa mobile mac requirements
    -fifa football mac controls
    -how to install fifa apk on mac
    -download fifa apk for windows 7/8/10
    -download fifa apk for mac os x
    -download latest version of fifa apk for pc
    -download updated version of fifa apk for mac
    -download cracked version of fifa apk for windows
    -download modded version of fifa apk for mac
    -download offline version of fifa apk for pc
    -download online version of fifa apk for mac
    -download full version of fifa apk for windows
    -download lite version of fifa apk for mac
    -download english version of fifa apk for pc
    -download spanish version of fifa apk for mac
    -download french version of fifa apk for windows
    -download german version of fifa apk for mac
    -download chinese version of fifa apk for pc
    -download japanese version of fifa apk for mac
    -download korean version of fifa apk for windows
    -download arabic version of fifa apk for mac
    -download portuguese version of fifa apk for pc
    -download russian version of fifa apk for mac
    -download italian version of fifa apk for windows
    -download turkish version of fifa apk for mac
    -download hindi version of fifa apk for pc

    -
      -
    • Compatibility issues: Playing FIFA on PC using an apk file and an emulator can cause some compatibility issues, as the game is not designed for Windows operating systems. You might encounter some errors, bugs, crashes, or glitches while playing the game.
    • -
    • Performance problems: Playing FIFA on PC using an apk file and an emulator can also cause some performance problems, as the game requires a lot of resources and processing power from your PC. You might experience some lag, stuttering, or freezing while playing the game.
    • -
    • Security risks: Playing FIFA on PC using an apk file and an emulator can also pose some security risks, as the apk file and the emulator might contain some malware, spyware, or viruses that can harm your PC. You should always download the apk file and the emulator from trusted sources and scan them with antivirus software before installing them.
    • -
    -

    How to download and install FIFA apk windows?

    -

    The requirements for playing FIFA apk windows

    -

    To play FIFA apk windows, you need to have the following requirements:

    -
      -
    • A PC with Windows 10 operating system.
    • -
    • An Android emulator that can run Android apps and games on your PC. As mentioned earlier, some of the most popular ones are BlueStacks, GameLoop, NoxPlayer, etc.
    • -
    • A FIFA apk file that contains the game data and files. You can download it from various sources online, such as Google Play Store or third-party websites. However, make sure that the apk file is compatible with your emulator and is free of viruses.
    • -
    -

    The steps for downloading and installing FIFA apk windows

    -

    To download and install FIFA apk windows, you need to follow these steps:

    -
      -
    1. Download and install an Android emulator of your choice on your PC. Follow the instructions on the emulator's website or app to complete the installation process.
    2. -
    3. Download a FIFA apk file of your choice on your PC. You can use a web browser or a downloader app to download the apk file from any source you trust.
    4. -
    5. Launch the Android emulator on your PC and sign in with your Google account. This will allow you to access the Google Play Store and other Google services on the emulator.
    6. -
    7. Locate the FIFA apk file on your PC and drag and drop it to the emulator's window. Alternatively, you can use the emulator's file manager or browser to find and open the apk file.
    8. -
    9. Wait for the emulator to install the FIFA apk file on your PC. This might take a few minutes depending on the size of the apk file and the speed of your PC.
    10. -
    11. Once the installation is done, you will see a FIFA icon on the emulator's home screen or app drawer. Click on it to launch the game and enjoy playing FIFA apk windows.
    12. -
    -

    How to play FIFA apk windows?

    -

    The features and modes of FIFA apk windows

    -

    FIFA apk windows has many features and modes that you can enjoy playing, such as:

    -
      -
    • Career Mode: In this mode, you can create your own soccer player or manager and lead them to glory. You can customize their appearance, skills, attributes, contracts, transfers, etc. You can also play through various seasons, tournaments, leagues, cups, etc.
    • -
    • Ultimate Team: In this mode, you can build your own dream team of soccer stars from different eras and regions. You can collect player cards, trade them with other players, create squads, play matches, and earn rewards. You can also compete with other players online or offline in various modes, such as Division Rivals, Squad Battles, FUT Champions, etc.
    • -
    • Volta Football: In this mode, you can experience the street soccer culture and style. You can create your own avatar and customize their outfits, hairstyles, tattoos, etc. You can also play in various locations, such as rooftops, cages, courts, etc. You can also play with different rules, such as 3v3, 4v4, 5v5, Futsal, etc.
    • -
    -

    The tips and tricks for playing FIFA apk windows

    -

    To play FIFA apk windows better, you can follow these tips and tricks:

    -
      -
    • Customize your controls: You can change the default controls of the game to suit your preferences and skills. You can use the emulator's settings to map the keyboard and mouse keys to the game's buttons. You can also use a gamepad or a controller to play the game if you have one.
    • -
    • Adjust your settings: You can also change the game's settings to optimize its performance and quality. You can use the emulator's settings to adjust the resolution, frame rate, graphics quality, sound volume, etc. You can also use the game's settings to adjust the difficulty level, camera angle, gameplay speed, etc.
    • -
    • Improve your skills: You can also practice and improve your skills in the game by playing different modes and matches. You can learn the basic and advanced moves, such as passing, shooting, dribbling, tackling, etc. You can also learn the strategies and tactics of different teams and players. You can also watch tutorials and guides online to get more tips and tricks.
    • -
    -

    What are some alternatives to FIFA apk windows?

    -

    A list of some other soccer games that can be played on PC

    -

    If you are looking for some other soccer games that can be played on PC, you can check out these games:

    - - - - - - - - - - - - - - - - - -
    GameDescription
    Pro Evolution Soccer (PES)A soccer game series by Konami that focuses on realistic gameplay and physics. It has official licenses from some soccer organizations, such as UEFA and AFC. It also features some legendary players and teams.
    Football Manager (FM)A soccer management simulation game series by Sports Interactive that lets you take control of any soccer club or national team. You can manage all aspects of your team, such as transfers, tactics, training, finances, etc. You can also watch the matches in 3D or 2D.
    Rocket LeagueA soccer game with a twist by Psyonix that combines soccer with rocket-powered cars. You can play with up to four players on each team and score goals by hitting a giant ball with your car. You can also customize your car with various items and decals.
    -

    A comparison of these games with FIFA apk windows

    -

    To compare these games with FIFA apk windows, you can look at these criteria:

    -
      -
    • Gameplay: FIFA apk windows has a more realistic and immersive gameplay than PES and Rocket League. It has more features and modes than FM. However, PES has a more fluid and responsive gameplay than FIFA apk windows. FM has a more strategic and complex gameplay than FIFA apk windows. Rocket League has a more fun and casual gameplay than FIFA apk windows.
    • -
    • Graphics: FIFA apk windows has better graphics than PES and FM. It has similar graphics to Rocket League. However, FIFA apk windows might have some graphical issues when played on PC using an apk file and an emulator.
    • -
    • Reviews: FIFA apk windows has mixed reviews from critics and players. Some praise its realism and variety, while others criticize its bugs and microtransactions. PES has positive reviews from critics and players. Some praise its gameplay and physics, while others criticize its lack of licenses and modes. FM has very positive reviews from critics and players. Some praise its depth and realism, while others criticize its difficulty and complexity. Rocket League has overwhelmingly positive reviews from critics and players. Some praise its fun and creativity, while others criticize its toxicity and repetitiveness.
    • -
    -

    Conclusion

    -

    A summary of the main points of the article

    -

    In conclusion, FIFA apk windows is a way to play the popular soccer game by EA Sports on your PC using an apk file and an emulator. FIFA apk windows has many benefits, such as better graphics, larger screen, and keyboard and mouse controls. However, it also has some drawbacks, such as compatibility issues, performance problems, and security risks. To play FIFA apk windows, you need to have a PC with Windows 10, an Android emulator, and a FIFA apk file. You can download and install them following the steps we provided. You can also enjoy playing various features and modes of FIFA apk windows, such as Career Mode, Ultimate Team, and Volta Football. You can also improve your skills by following the tips and tricks we shared. If you are looking for some alternatives to FIFA apk windows, you can try out other soccer games on PC, such as PES, FM, and Rocket League.

    -

    A call to action for the readers to try out FIFA apk windows or other soccer games on PC

    -

    We hope that this article has helped you understand what FIFA apk windows is, why you might want to play it, how to download and install it, how to play it, and what are some alternatives to it. If you are a soccer fan and a PC gamer, you should definitely give FIFA apk windows or other soccer games on PC a try. You will have a lot of fun and excitement playing the world's most popular sport on your PC. So what are you waiting for? Download FIFA apk windows or other soccer games on PC today and enjoy the beautiful game!

    -

    FAQs

    -

    What is the difference between FIFA apk windows and FIFA PC?

    -

    FIFA apk windows is a way to play the mobile version of FIFA on your PC using an apk file and an emulator. FIFA PC is the official version of FIFA that is designed for Windows operating systems. FIFA PC has more features and modes than FIFA apk windows, but it also requires more system requirements and costs more money.

    -

    Is FIFA apk windows legal?

    -

    FIFA apk windows is not illegal, but it is not authorized by EA Sports either. EA Sports does not support or endorse playing FIFA on PC using an apk file and an emulator. Therefore, you are playing FIFA apk windows at your own risk and responsibility.

    -

    Is FIFA apk windows safe?

    -

    FIFA apk windows is not completely safe, as it involves downloading and installing files from unknown sources that might contain malware or viruses. It also involves using an emulator that might access your personal data or harm your PC. Therefore, you should always be careful and cautious when playing FIFA apk windows.

    -

    How can I update FIFA apk windows?

    -

    To update FIFA apk windows, you need to download and install the latest version of the FIFA apk file from a reliable source. You also need to make sure that your emulator is compatible with the new version of the game. You might need to uninstall and reinstall the game if you encounter any problems.

    -

    How can I uninstall FIFA apk windows?

    -

    To uninstall FIFA apk windows, you need to delete the FIFA apk file from your PC. You also need to delete the game data and cache from your emulator. You might need to use a cleaner app or software to remove any leftover files or registry entries.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Edius Pro 7.2 Build 0437.crack.rar The Perfect Finishing Tool for Broadcast Documentary and 4K Productions.md b/spaces/contluForse/HuggingGPT/assets/Edius Pro 7.2 Build 0437.crack.rar The Perfect Finishing Tool for Broadcast Documentary and 4K Productions.md deleted file mode 100644 index 003146f2ae1348c1b831cddc059722eb22c00cd9..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Edius Pro 7.2 Build 0437.crack.rar The Perfect Finishing Tool for Broadcast Documentary and 4K Productions.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Edius Pro 7.2 Build 0437.crack.rar


    Download Filehttps://ssurll.com/2uzyRL



    -
    - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/deeplab/resnet.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/deeplab/resnet.py deleted file mode 100644 index 28455d123a12f887400c19c263d08cc2ed08522e..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/projects/deeplab/resnet.py +++ /dev/null @@ -1,158 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import fvcore.nn.weight_init as weight_init -import torch.nn.functional as F - -from annotator.oneformer.detectron2.layers import CNNBlockBase, Conv2d, get_norm -from annotator.oneformer.detectron2.modeling import BACKBONE_REGISTRY -from annotator.oneformer.detectron2.modeling.backbone.resnet import ( - BasicStem, - BottleneckBlock, - DeformBottleneckBlock, - ResNet, -) - - -class DeepLabStem(CNNBlockBase): - """ - The DeepLab ResNet stem (layers before the first residual block). - """ - - def __init__(self, in_channels=3, out_channels=128, norm="BN"): - """ - Args: - norm (str or callable): norm after the first conv layer. - See :func:`layers.get_norm` for supported format. - """ - super().__init__(in_channels, out_channels, 4) - self.in_channels = in_channels - self.conv1 = Conv2d( - in_channels, - out_channels // 2, - kernel_size=3, - stride=2, - padding=1, - bias=False, - norm=get_norm(norm, out_channels // 2), - ) - self.conv2 = Conv2d( - out_channels // 2, - out_channels // 2, - kernel_size=3, - stride=1, - padding=1, - bias=False, - norm=get_norm(norm, out_channels // 2), - ) - self.conv3 = Conv2d( - out_channels // 2, - out_channels, - kernel_size=3, - stride=1, - padding=1, - bias=False, - norm=get_norm(norm, out_channels), - ) - weight_init.c2_msra_fill(self.conv1) - weight_init.c2_msra_fill(self.conv2) - weight_init.c2_msra_fill(self.conv3) - - def forward(self, x): - x = self.conv1(x) - x = F.relu_(x) - x = self.conv2(x) - x = F.relu_(x) - x = self.conv3(x) - x = F.relu_(x) - x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1) - return x - - -@BACKBONE_REGISTRY.register() -def build_resnet_deeplab_backbone(cfg, input_shape): - """ - Create a ResNet instance from config. - Returns: - ResNet: a :class:`ResNet` instance. - """ - # need registration of new blocks/stems? - norm = cfg.MODEL.RESNETS.NORM - if cfg.MODEL.RESNETS.STEM_TYPE == "basic": - stem = BasicStem( - in_channels=input_shape.channels, - out_channels=cfg.MODEL.RESNETS.STEM_OUT_CHANNELS, - norm=norm, - ) - elif cfg.MODEL.RESNETS.STEM_TYPE == "deeplab": - stem = DeepLabStem( - in_channels=input_shape.channels, - out_channels=cfg.MODEL.RESNETS.STEM_OUT_CHANNELS, - norm=norm, - ) - else: - raise ValueError("Unknown stem type: {}".format(cfg.MODEL.RESNETS.STEM_TYPE)) - - # fmt: off - freeze_at = cfg.MODEL.BACKBONE.FREEZE_AT - out_features = cfg.MODEL.RESNETS.OUT_FEATURES - depth = cfg.MODEL.RESNETS.DEPTH - num_groups = cfg.MODEL.RESNETS.NUM_GROUPS - width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP - bottleneck_channels = num_groups * width_per_group - in_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS - out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS - stride_in_1x1 = cfg.MODEL.RESNETS.STRIDE_IN_1X1 - res4_dilation = cfg.MODEL.RESNETS.RES4_DILATION - res5_dilation = cfg.MODEL.RESNETS.RES5_DILATION - deform_on_per_stage = cfg.MODEL.RESNETS.DEFORM_ON_PER_STAGE - deform_modulated = cfg.MODEL.RESNETS.DEFORM_MODULATED - deform_num_groups = cfg.MODEL.RESNETS.DEFORM_NUM_GROUPS - res5_multi_grid = cfg.MODEL.RESNETS.RES5_MULTI_GRID - # fmt: on - assert res4_dilation in {1, 2}, "res4_dilation cannot be {}.".format(res4_dilation) - assert res5_dilation in {1, 2, 4}, "res5_dilation cannot be {}.".format(res5_dilation) - if res4_dilation == 2: - # Always dilate res5 if res4 is dilated. - assert res5_dilation == 4 - - num_blocks_per_stage = {50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3]}[depth] - - stages = [] - - # Avoid creating variables without gradients - # It consumes extra memory and may cause allreduce to fail - out_stage_idx = [{"res2": 2, "res3": 3, "res4": 4, "res5": 5}[f] for f in out_features] - max_stage_idx = max(out_stage_idx) - for idx, stage_idx in enumerate(range(2, max_stage_idx + 1)): - if stage_idx == 4: - dilation = res4_dilation - elif stage_idx == 5: - dilation = res5_dilation - else: - dilation = 1 - first_stride = 1 if idx == 0 or dilation > 1 else 2 - stage_kargs = { - "num_blocks": num_blocks_per_stage[idx], - "stride_per_block": [first_stride] + [1] * (num_blocks_per_stage[idx] - 1), - "in_channels": in_channels, - "out_channels": out_channels, - "norm": norm, - } - stage_kargs["bottleneck_channels"] = bottleneck_channels - stage_kargs["stride_in_1x1"] = stride_in_1x1 - stage_kargs["dilation"] = dilation - stage_kargs["num_groups"] = num_groups - if deform_on_per_stage[idx]: - stage_kargs["block_class"] = DeformBottleneckBlock - stage_kargs["deform_modulated"] = deform_modulated - stage_kargs["deform_num_groups"] = deform_num_groups - else: - stage_kargs["block_class"] = BottleneckBlock - if stage_idx == 5: - stage_kargs.pop("dilation") - stage_kargs["dilation_per_block"] = [dilation * mg for mg in res5_multi_grid] - blocks = ResNet.make_stage(**stage_kargs) - in_channels = out_channels - out_channels *= 2 - bottleneck_channels *= 2 - stages.append(blocks) - return ResNet(stem, stages, out_features=out_features).freeze(freeze_at) diff --git a/spaces/cvlab/zero123-live/taming-transformers/taming/util.py b/spaces/cvlab/zero123-live/taming-transformers/taming/util.py deleted file mode 100644 index 06053e5defb87977f9ab07e69bf4da12201de9b7..0000000000000000000000000000000000000000 --- a/spaces/cvlab/zero123-live/taming-transformers/taming/util.py +++ /dev/null @@ -1,157 +0,0 @@ -import os, hashlib -import requests -from tqdm import tqdm - -URL_MAP = { - "vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1" -} - -CKPT_MAP = { - "vgg_lpips": "vgg.pth" -} - -MD5_MAP = { - "vgg_lpips": "d507d7349b931f0638a25a48a722f98a" -} - - -def download(url, local_path, chunk_size=1024): - os.makedirs(os.path.split(local_path)[0], exist_ok=True) - with requests.get(url, stream=True) as r: - total_size = int(r.headers.get("content-length", 0)) - with tqdm(total=total_size, unit="B", unit_scale=True) as pbar: - with open(local_path, "wb") as f: - for data in r.iter_content(chunk_size=chunk_size): - if data: - f.write(data) - pbar.update(chunk_size) - - -def md5_hash(path): - with open(path, "rb") as f: - content = f.read() - return hashlib.md5(content).hexdigest() - - -def get_ckpt_path(name, root, check=False): - assert name in URL_MAP - path = os.path.join(root, CKPT_MAP[name]) - if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]): - print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path)) - download(URL_MAP[name], path) - md5 = md5_hash(path) - assert md5 == MD5_MAP[name], md5 - return path - - -class KeyNotFoundError(Exception): - def __init__(self, cause, keys=None, visited=None): - self.cause = cause - self.keys = keys - self.visited = visited - messages = list() - if keys is not None: - messages.append("Key not found: {}".format(keys)) - if visited is not None: - messages.append("Visited: {}".format(visited)) - messages.append("Cause:\n{}".format(cause)) - message = "\n".join(messages) - super().__init__(message) - - -def retrieve( - list_or_dict, key, splitval="/", default=None, expand=True, pass_success=False -): - """Given a nested list or dict return the desired value at key expanding - callable nodes if necessary and :attr:`expand` is ``True``. The expansion - is done in-place. - - Parameters - ---------- - list_or_dict : list or dict - Possibly nested list or dictionary. - key : str - key/to/value, path like string describing all keys necessary to - consider to get to the desired value. List indices can also be - passed here. - splitval : str - String that defines the delimiter between keys of the - different depth levels in `key`. - default : obj - Value returned if :attr:`key` is not found. - expand : bool - Whether to expand callable nodes on the path or not. - - Returns - ------- - The desired value or if :attr:`default` is not ``None`` and the - :attr:`key` is not found returns ``default``. - - Raises - ------ - Exception if ``key`` not in ``list_or_dict`` and :attr:`default` is - ``None``. - """ - - keys = key.split(splitval) - - success = True - try: - visited = [] - parent = None - last_key = None - for key in keys: - if callable(list_or_dict): - if not expand: - raise KeyNotFoundError( - ValueError( - "Trying to get past callable node with expand=False." - ), - keys=keys, - visited=visited, - ) - list_or_dict = list_or_dict() - parent[last_key] = list_or_dict - - last_key = key - parent = list_or_dict - - try: - if isinstance(list_or_dict, dict): - list_or_dict = list_or_dict[key] - else: - list_or_dict = list_or_dict[int(key)] - except (KeyError, IndexError, ValueError) as e: - raise KeyNotFoundError(e, keys=keys, visited=visited) - - visited += [key] - # final expansion of retrieved value - if expand and callable(list_or_dict): - list_or_dict = list_or_dict() - parent[last_key] = list_or_dict - except KeyNotFoundError as e: - if default is None: - raise e - else: - list_or_dict = default - success = False - - if not pass_success: - return list_or_dict - else: - return list_or_dict, success - - -if __name__ == "__main__": - config = {"keya": "a", - "keyb": "b", - "keyc": - {"cc1": 1, - "cc2": 2, - } - } - from omegaconf import OmegaConf - config = OmegaConf.create(config) - print(config) - retrieve(config, "keya") - diff --git a/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/utils/audio.py b/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/utils/audio.py deleted file mode 100644 index a96071106d684732f89cf92c2d9fe83e377243c1..0000000000000000000000000000000000000000 --- a/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/utils/audio.py +++ /dev/null @@ -1,136 +0,0 @@ -import librosa -import librosa.filters -import numpy as np -# import tensorflow as tf -from scipy import signal -from scipy.io import wavfile -from Demo_TFR_Pirenderer.src.utils.hparams import hparams as hp - -def load_wav(path, sr): - return librosa.core.load(path, sr=sr)[0] - -def save_wav(wav, path, sr): - wav *= 32767 / max(0.01, np.max(np.abs(wav))) - #proposed by @dsmiller - wavfile.write(path, sr, wav.astype(np.int16)) - -def save_wavenet_wav(wav, path, sr): - librosa.output.write_wav(path, wav, sr=sr) - -def preemphasis(wav, k, preemphasize=True): - if preemphasize: - return signal.lfilter([1, -k], [1], wav) - return wav - -def inv_preemphasis(wav, k, inv_preemphasize=True): - if inv_preemphasize: - return signal.lfilter([1], [1, -k], wav) - return wav - -def get_hop_size(): - hop_size = hp.hop_size - if hop_size is None: - assert hp.frame_shift_ms is not None - hop_size = int(hp.frame_shift_ms / 1000 * hp.sample_rate) - return hop_size - -def linearspectrogram(wav): - D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize)) - S = _amp_to_db(np.abs(D)) - hp.ref_level_db - - if hp.signal_normalization: - return _normalize(S) - return S - -def melspectrogram(wav): - D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize)) - S = _amp_to_db(_linear_to_mel(np.abs(D))) - hp.ref_level_db - - if hp.signal_normalization: - return _normalize(S) - return S - -def _lws_processor(): - import lws - return lws.lws(hp.n_fft, get_hop_size(), fftsize=hp.win_size, mode="speech") - -def _stft(y): - if hp.use_lws: - return _lws_processor(hp).stft(y).T - else: - return librosa.stft(y=y, n_fft=hp.n_fft, hop_length=get_hop_size(), win_length=hp.win_size) - -########################################################## -#Those are only correct when using lws!!! (This was messing with Wavenet quality for a long time!) -def num_frames(length, fsize, fshift): - """Compute number of time frames of spectrogram - """ - pad = (fsize - fshift) - if length % fshift == 0: - M = (length + pad * 2 - fsize) // fshift + 1 - else: - M = (length + pad * 2 - fsize) // fshift + 2 - return M - - -def pad_lr(x, fsize, fshift): - """Compute left and right padding - """ - M = num_frames(len(x), fsize, fshift) - pad = (fsize - fshift) - T = len(x) + 2 * pad - r = (M - 1) * fshift + fsize - T - return pad, pad + r -########################################################## -#Librosa correct padding -def librosa_pad_lr(x, fsize, fshift): - return 0, (x.shape[0] // fshift + 1) * fshift - x.shape[0] - -# Conversions -_mel_basis = None - -def _linear_to_mel(spectogram): - global _mel_basis - if _mel_basis is None: - _mel_basis = _build_mel_basis() - return np.dot(_mel_basis, spectogram) - -def _build_mel_basis(): - assert hp.fmax <= hp.sample_rate // 2 - return librosa.filters.mel(sr=hp.sample_rate, n_fft=hp.n_fft, n_mels=hp.num_mels, - fmin=hp.fmin, fmax=hp.fmax) - -def _amp_to_db(x): - min_level = np.exp(hp.min_level_db / 20 * np.log(10)) - return 20 * np.log10(np.maximum(min_level, x)) - -def _db_to_amp(x): - return np.power(10.0, (x) * 0.05) - -def _normalize(S): - if hp.allow_clipping_in_normalization: - if hp.symmetric_mels: - return np.clip((2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value, - -hp.max_abs_value, hp.max_abs_value) - else: - return np.clip(hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)), 0, hp.max_abs_value) - - assert S.max() <= 0 and S.min() - hp.min_level_db >= 0 - if hp.symmetric_mels: - return (2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value - else: - return hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)) - -def _denormalize(D): - if hp.allow_clipping_in_normalization: - if hp.symmetric_mels: - return (((np.clip(D, -hp.max_abs_value, - hp.max_abs_value) + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) - + hp.min_level_db) - else: - return ((np.clip(D, 0, hp.max_abs_value) * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db) - - if hp.symmetric_mels: - return (((D + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) + hp.min_level_db) - else: - return ((D * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db) diff --git a/spaces/datasciencedojo/AmericanSignLanguage-Detection/app.py b/spaces/datasciencedojo/AmericanSignLanguage-Detection/app.py deleted file mode 100644 index 8520dcef0dbec05641be8b98ce001de3d64a6cf8..0000000000000000000000000000000000000000 --- a/spaces/datasciencedojo/AmericanSignLanguage-Detection/app.py +++ /dev/null @@ -1,177 +0,0 @@ -import cv2 -from cvzone.HandTrackingModule import HandDetector -from cvzone.ClassificationModule import Classifier -import numpy as np -import math -import gradio as gr - -detector = HandDetector(mode=True,maxHands=1) -classifier = Classifier("ModelFull/keras_model.h5", "ModelFull/labels.txt") - -offset = 20 -imgSize = 300 - -folder = "Data/C" -counter = 0 - -labels = ["A", "B","C","D","E","F","G","H","I","J","K","L","M","N", "O","P","Q","R","S","T","U","V","W","X","Y","Z"] - -def sign(img): - #img = cv2.imread("sign.jpg") - imgOutput = cv2.flip(img.copy(),1) - hands, img = detector.findHands(cv2.flip(img[:,:,::-1],1)) - if hands: - print('hand detected') - hand = hands[0] - x, y, w, h = hand['bbox'] - imlist = hand['lmList'] - print(imlist) - if ((imlist[10][0] < imlist[4][0] < imlist[6][0]) or (imlist[6][0] < imlist[4][0] < imlist[10][0])): - if ((imlist[4][1] < imlist[8][1]) and (imlist[4][1] < imlist[12][1]) ): - print('In T') - cv2.rectangle(imgOutput, (x-offset, y-offset),(x + w+offset, y + h+offset), (255, 0, 255), 4) - imgOutput = cv2.flip(imgOutput,1) - cv2.rectangle(imgOutput, (0,30),(80,80), (255, 0, 255), cv2.FILLED) - cv2.putText(imgOutput, 'T', (20, 75), cv2.FONT_HERSHEY_COMPLEX, 1.7, (255, 255, 255), 2) - return imgOutput - else: - print('In K') - cv2.rectangle(imgOutput, (x-offset, y-offset),(x + w+offset, y + h+offset), (255, 0, 255), 4) - imgOutput = cv2.flip(imgOutput,1) - cv2.rectangle(imgOutput, (0,30),(80,80), (255, 0, 255), cv2.FILLED) - cv2.putText(imgOutput, 'K', (20, 75), cv2.FONT_HERSHEY_COMPLEX, 1.7, (255, 255, 255), 2) - return imgOutput - '''if imlist[4][0]>imlist[8][0] and imlist[4][0]>imlist[12][0] and imlist[4][0]>imlist[16][0] and imlist[4][0]>imlist[20][0]: - print('In M') - cv2.rectangle(imgOutput, (x-offset, y-offset),(x + w+offset, y + h+offset), (255, 0, 255), 4) - imgOutput = cv2.flip(imgOutput,1) - cv2.rectangle(imgOutput, (0,30),(80,80), (255, 0, 255), cv2.FILLED) - cv2.putText(imgOutput, 'M', (20, 75), cv2.FONT_HERSHEY_COMPLEX, 1.7, (255, 255, 255), 2) - return imgOutput''' - - imgWhite = np.ones((imgSize, imgSize, 3), np.uint8) * 255 - imgCrop = img[y - offset:y + h + offset, x - offset:x + w + offset] - - imgCropShape = imgCrop.shape - - aspectRatio = h / w - - if aspectRatio > 1: - k = imgSize / h - wCal = math.ceil(k * w) - imgResize = cv2.resize(imgCrop, (wCal, imgSize)) - imgResizeShape = imgResize.shape - wGap = math.ceil((imgSize - wCal) / 2) - imgWhite[:, wGap:wCal + wGap] = imgResize - prediction, index = classifier.getPrediction(imgWhite, draw=False) - print(prediction, index) - - else: - k = imgSize / w - hCal = math.ceil(k * h) - imgResize = cv2.resize(imgCrop, (imgSize, hCal)) - imgResizeShape = imgResize.shape - hGap = math.ceil((imgSize - hCal) / 2) - imgWhite[hGap:hCal + hGap, :] = imgResize - prediction, index = classifier.getPrediction(imgWhite, draw=False) - - cv2.imwrite("check.jpg",imgWhite) - cv2.rectangle(imgOutput, (x-offset, y-offset), - (x + w+offset, y + h+offset), (255, 0, 255), 4) - imgOutput = cv2.flip(imgOutput,1) - #cv2.rectangle(imgOutput, (x - offset, y - offset-50), - # (x - offset+90, y - offset-50+50), (255, 0, 255), cv2.FILLED) - #cv2.putText(imgOutput, labels[index], (x, y -26), cv2.FONT_HERSHEY_COMPLEX, 1.7, (255, 255, 255), 2) - cv2.rectangle(imgOutput, (0,30), - (80,80), (255, 0, 255), cv2.FILLED) - cv2.putText(imgOutput, labels[index], (20, 75), cv2.FONT_HERSHEY_COMPLEX, 1.7, (255, 255, 255), 2) - - - #cv2.imshow("ImageCrop", imgCrop) - #cv2.imshow("ImageWhite", imgWhite) - - #cv2.imshow("Image", imgOutput) - return imgOutput - -def set_example_image(example: list) -> dict: - return gr.inputs.Image.update(value=example[0]) - - -css = """ -.gr-button-lg { - z-index: 14; - width: 113px; - height: 30px; - left: 0px; - top: 0px; - padding: 0px; - cursor: pointer !important; - background: none rgb(17, 20, 45) !important; - border: none !important; - text-align: center !important; - font-size: 14px !important; - font-weight: 500 !important; - color: rgb(255, 255, 255) !important; - line-height: 1 !important; - border-radius: 6px !important; - transition: box-shadow 200ms ease 0s, background 200ms ease 0s !important; - box-shadow: none !important; -} -.gr-button-lg:hover{ - z-index: 14; - width: 113px; - height: 30px; - left: 0px; - top: 0px; - padding: 0px; - cursor: pointer !important; - background: none rgb(37, 56, 133) !important; - border: none !important; - text-align: center !important; - font-size: 14px !important; - font-weight: 500 !important; - color: rgb(255, 255, 255) !important; - line-height: 1 !important; - border-radius: 6px !important; - transition: box-shadow 200ms ease 0s, background 200ms ease 0s !important; - box-shadow: rgb(0 0 0 / 23%) 0px 1px 7px 0px !important; -} - -footer {display:none !important} -.output-markdown{display:none !important} -#out_image {height: 22rem !important;} -""" - -with gr.Blocks(title="American Sign Language Detection | Data Science Dojo", css=css) as demo: - - with gr.Tabs(): - with gr.TabItem('Upload'): - with gr.Row(): - with gr.Column(): - img_input = gr.Image(shape=(640,480)) - image_button = gr.Button("Submit") - - with gr.Column(): - output = gr.Image(shape=(640,480), elem_id="out_image") - with gr.Row(): - example_images = gr.Dataset(components=[img_input],samples=[["ex2.jpg"]]) - - with gr.TabItem('Webcam'): - with gr.Row(): - with gr.Column(): - img_input2 = gr.Webcam() - image_button2 = gr.Button("Submit") - - with gr.Column(): - output2 = gr.outputs.Image() - - image_button2.click(fn=sign, - inputs = img_input2, - outputs = output2) - image_button.click(fn=sign, - inputs = img_input, - outputs = output) - example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input]) - - -demo.launch(debug=True) \ No newline at end of file diff --git a/spaces/davidpiscasio/unpaired-img2img/models/template_model.py b/spaces/davidpiscasio/unpaired-img2img/models/template_model.py deleted file mode 100644 index 68cdaf6a9a2cb321ff2a01949b38adc6fa22e97c..0000000000000000000000000000000000000000 --- a/spaces/davidpiscasio/unpaired-img2img/models/template_model.py +++ /dev/null @@ -1,99 +0,0 @@ -"""Model class template - -This module provides a template for users to implement custom models. -You can specify '--model template' to use this model. -The class name should be consistent with both the filename and its model option. -The filename should be _dataset.py -The class name should be Dataset.py -It implements a simple image-to-image translation baseline based on regression loss. -Given input-output pairs (data_A, data_B), it learns a network netG that can minimize the following L1 loss: - min_ ||netG(data_A) - data_B||_1 -You need to implement the following functions: - : Add model-specific options and rewrite default values for existing options. - <__init__>: Initialize this model class. - : Unpack input data and perform data pre-processing. - : Run forward pass. This will be called by both and . - : Update network weights; it will be called in every training iteration. -""" -import torch -from .base_model import BaseModel -from . import networks - - -class TemplateModel(BaseModel): - @staticmethod - def modify_commandline_options(parser, is_train=True): - """Add new model-specific options and rewrite default values for existing options. - - Parameters: - parser -- the option parser - is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options. - - Returns: - the modified parser. - """ - parser.set_defaults(dataset_mode='aligned') # You can rewrite default values for this model. For example, this model usually uses aligned dataset as its dataset. - if is_train: - parser.add_argument('--lambda_regression', type=float, default=1.0, help='weight for the regression loss') # You can define new arguments for this model. - - return parser - - def __init__(self, opt): - """Initialize this model class. - - Parameters: - opt -- training/test options - - A few things can be done here. - - (required) call the initialization function of BaseModel - - define loss function, visualization images, model names, and optimizers - """ - BaseModel.__init__(self, opt) # call the initialization method of BaseModel - # specify the training losses you want to print out. The program will call base_model.get_current_losses to plot the losses to the console and save them to the disk. - self.loss_names = ['loss_G'] - # specify the images you want to save and display. The program will call base_model.get_current_visuals to save and display these images. - self.visual_names = ['data_A', 'data_B', 'output'] - # specify the models you want to save to the disk. The program will call base_model.save_networks and base_model.load_networks to save and load networks. - # you can use opt.isTrain to specify different behaviors for training and test. For example, some networks will not be used during test, and you don't need to load them. - self.model_names = ['G'] - # define networks; you can use opt.isTrain to specify different behaviors for training and test. - self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, gpu_ids=self.gpu_ids) - if self.isTrain: # only defined during training time - # define your loss functions. You can use losses provided by torch.nn such as torch.nn.L1Loss. - # We also provide a GANLoss class "networks.GANLoss". self.criterionGAN = networks.GANLoss().to(self.device) - self.criterionLoss = torch.nn.L1Loss() - # define and initialize optimizers. You can define one optimizer for each network. - # If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example. - self.optimizer = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) - self.optimizers = [self.optimizer] - - # Our program will automatically call to define schedulers, load networks, and print networks - - def set_input(self, input): - """Unpack input data from the dataloader and perform necessary pre-processing steps. - - Parameters: - input: a dictionary that contains the data itself and its metadata information. - """ - AtoB = self.opt.direction == 'AtoB' # use to swap data_A and data_B - self.data_A = input['A' if AtoB else 'B'].to(self.device) # get image data A - self.data_B = input['B' if AtoB else 'A'].to(self.device) # get image data B - self.image_paths = input['A_paths' if AtoB else 'B_paths'] # get image paths - - def forward(self): - """Run forward pass. This will be called by both functions and .""" - self.output = self.netG(self.data_A) # generate output image given the input data_A - - def backward(self): - """Calculate losses, gradients, and update network weights; called in every training iteration""" - # caculate the intermediate results if necessary; here self.output has been computed during function - # calculate loss given the input and intermediate results - self.loss_G = self.criterionLoss(self.output, self.data_B) * self.opt.lambda_regression - self.loss_G.backward() # calculate gradients of network G w.r.t. loss_G - - def optimize_parameters(self): - """Update network weights; it will be called in every training iteration.""" - self.forward() # first call forward to calculate intermediate results - self.optimizer.zero_grad() # clear network G's existing gradients - self.backward() # calculate gradients for network G - self.optimizer.step() # update gradients for network G diff --git a/spaces/davidrd123/WikiArt_20genre/app.py b/spaces/davidrd123/WikiArt_20genre/app.py deleted file mode 100644 index d0b2d51d6d21548d3ac145fb20bf200f4b4f970f..0000000000000000000000000000000000000000 --- a/spaces/davidrd123/WikiArt_20genre/app.py +++ /dev/null @@ -1,26 +0,0 @@ -import gradio as gr -from fastai.vision.all import * -import skimage - -learn = load_learner('rn50_256px_20genre_8epoch_err313.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))} - -examples = [f"Image{n:02d}.jpg" for n in range(12)] -interpretation='shap' -title = "Art Movement Classifier - WikiArt" -description = "What Art Movement Matches the Image Best?" -theme = 'grass' - -gr.Interface(fn=predict, - inputs=gr.inputs.Image(shape=((512,512))), - outputs=gr.outputs.Label(num_top_classes=5), - title = title, - examples = examples, - theme = theme, - interpretation = interpretation, - description = description).launch(share=True, enable_queue=True) \ No newline at end of file diff --git a/spaces/dawood/Kanye-AI/cluster/train_cluster.py b/spaces/dawood/Kanye-AI/cluster/train_cluster.py deleted file mode 100644 index 4ac025d400414226e66849407f477ae786c3d5d3..0000000000000000000000000000000000000000 --- a/spaces/dawood/Kanye-AI/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/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/vegalite/v5/schema/core.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/vegalite/v5/schema/core.py deleted file mode 100644 index ad1e5afd509cb95cd2d50bcbee8b51b5b794ecf3..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/altair/vegalite/v5/schema/core.py +++ /dev/null @@ -1,21785 +0,0 @@ -# The contents of this file are automatically written by -# tools/generate_schema_wrapper.py. Do not modify directly. - -from altair.utils.schemapi import SchemaBase, Undefined, _subclasses - -import pkgutil -import json - -def load_schema(): - """Load the json schema associated with this module's functions""" - return json.loads(pkgutil.get_data(__name__, 'vega-lite-schema.json').decode('utf-8')) - - -class VegaLiteSchema(SchemaBase): - _rootschema = load_schema() - @classmethod - def _default_wrapper_classes(cls): - return _subclasses(VegaLiteSchema) - - -class Root(VegaLiteSchema): - """Root schema wrapper - - anyOf(:class:`TopLevelUnitSpec`, :class:`TopLevelFacetSpec`, :class:`TopLevelLayerSpec`, - :class:`TopLevelRepeatSpec`, :class:`TopLevelConcatSpec`, :class:`TopLevelVConcatSpec`, - :class:`TopLevelHConcatSpec`) - A Vega-Lite top-level specification. This is the root class for all Vega-Lite - specifications. (The json schema is generated from this type.) - """ - _schema = VegaLiteSchema._rootschema - - def __init__(self, *args, **kwds): - super(Root, self).__init__(*args, **kwds) - - -class Aggregate(VegaLiteSchema): - """Aggregate schema wrapper - - anyOf(:class:`NonArgAggregateOp`, :class:`ArgmaxDef`, :class:`ArgminDef`) - """ - _schema = {'$ref': '#/definitions/Aggregate'} - - def __init__(self, *args, **kwds): - super(Aggregate, self).__init__(*args, **kwds) - - -class AggregateOp(VegaLiteSchema): - """AggregateOp schema wrapper - - enum('argmax', 'argmin', 'average', 'count', 'distinct', 'max', 'mean', 'median', 'min', - 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', - 'values', 'variance', 'variancep') - """ - _schema = {'$ref': '#/definitions/AggregateOp'} - - def __init__(self, *args): - super(AggregateOp, self).__init__(*args) - - -class AggregatedFieldDef(VegaLiteSchema): - """AggregatedFieldDef schema wrapper - - Mapping(required=[op, as]) - - Parameters - ---------- - - op : :class:`AggregateOp` - The aggregation operation to apply to the fields (e.g., ``"sum"``, ``"average"``, or - ``"count"`` ). See the `full list of supported aggregation operations - `__ for more information. - field : :class:`FieldName` - The data field for which to compute aggregate function. This is required for all - aggregation operations except ``"count"``. - as : :class:`FieldName` - The output field names to use for each aggregated field. - """ - _schema = {'$ref': '#/definitions/AggregatedFieldDef'} - - def __init__(self, op=Undefined, field=Undefined, **kwds): - super(AggregatedFieldDef, self).__init__(op=op, field=field, **kwds) - - -class Align(VegaLiteSchema): - """Align schema wrapper - - enum('left', 'center', 'right') - """ - _schema = {'$ref': '#/definitions/Align'} - - def __init__(self, *args): - super(Align, self).__init__(*args) - - -class AnyMark(VegaLiteSchema): - """AnyMark schema wrapper - - anyOf(:class:`CompositeMark`, :class:`CompositeMarkDef`, :class:`Mark`, :class:`MarkDef`) - """ - _schema = {'$ref': '#/definitions/AnyMark'} - - def __init__(self, *args, **kwds): - super(AnyMark, self).__init__(*args, **kwds) - - -class AnyMarkConfig(VegaLiteSchema): - """AnyMarkConfig schema wrapper - - anyOf(:class:`MarkConfig`, :class:`AreaConfig`, :class:`BarConfig`, :class:`RectConfig`, - :class:`LineConfig`, :class:`TickConfig`) - """ - _schema = {'$ref': '#/definitions/AnyMarkConfig'} - - def __init__(self, *args, **kwds): - super(AnyMarkConfig, self).__init__(*args, **kwds) - - -class AreaConfig(AnyMarkConfig): - """AreaConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : anyOf(:class:`Align`, :class:`ExprRef`) - The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). - One of ``"left"``, ``"right"``, ``"center"``. - - **Note:** Expression reference is *not* supported for range marks. - angle : anyOf(float, :class:`ExprRef`) - The rotation angle of the text, in degrees. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG element, removing the mark item from the ARIA accessibility tree. - ariaRole : anyOf(string, :class:`ExprRef`) - Sets the type of user interface element of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "role" attribute. Warning: this - property is experimental and may be changed in the future. - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - A human-readable, author-localized description for the role of the mark item for - `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "aria-roledescription" attribute. - Warning: this property is experimental and may be changed in the future. - aspect : anyOf(boolean, :class:`ExprRef`) - Whether to keep aspect ratio of image marks. - baseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an - expression reference that provides one of the valid values. The ``"line-top"`` and - ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are - calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. - - For range marks, the vertical alignment of the marks. One of ``"top"``, - ``"middle"``, ``"bottom"``. - - **Note:** Expression reference is *not* supported for range marks. - blend : anyOf(:class:`Blend`, :class:`ExprRef`) - The color blend mode for drawing an item on its current background. Any valid `CSS - mix-blend-mode `__ - value can be used. - - __Default value:__ ``"source-over"`` - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom left corner. - - **Default value:** ``0`` - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom right corner. - - **Default value:** ``0`` - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top right corner. - - **Default value:** ``0`` - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top left corner. - - **Default value:** ``0`` - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - The mouse cursor used over the mark. Any valid `CSS cursor type - `__ can be used. - description : anyOf(string, :class:`ExprRef`) - A text description of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the `"aria-label" attribute - `__. - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` - (right-to-left). This property determines on which side is truncated in response to - the limit parameter. - - **Default value:** ``"ltr"`` - dx : anyOf(float, :class:`ExprRef`) - The horizontal offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - dy : anyOf(float, :class:`ExprRef`) - The vertical offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - ellipsis : anyOf(string, :class:`ExprRef`) - The ellipsis string for text truncated in response to the limit parameter. - - **Default value:** ``"…"`` - endAngle : anyOf(float, :class:`ExprRef`) - The end angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - filled : boolean - Whether the mark's color should be used as fill color instead of stroke color. - - **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well - as ``geoshape`` marks for `graticule - `__ data sources; - otherwise, ``true``. - - **Note:** This property cannot be used in a `style config - `__. - font : anyOf(string, :class:`ExprRef`) - The typeface to set the text in (e.g., ``"Helvetica Neue"`` ). - fontSize : anyOf(float, :class:`ExprRef`) - The font size, in pixels. - - **Default value:** ``11`` - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style (e.g., ``"italic"`` ). - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight. This can be either a string (e.g ``"bold"``, ``"normal"`` ) or a - number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and - ``"bold"`` = ``700`` ). - height : anyOf(float, :class:`ExprRef`) - Height of the marks. - href : anyOf(:class:`URI`, :class:`ExprRef`) - A URL to load upon mouse click. If defined, the mark acts as a hyperlink. - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - - **Default value:** ``0`` - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - The line interpolation method to use for line and area marks. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : alternate between horizontal and vertical segments, as in a step - function. - * ``"step-before"`` : alternate between vertical and horizontal segments, as in a - step function. - * ``"step-after"`` : alternate between horizontal and vertical segments, as in a - step function. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - limit : anyOf(float, :class:`ExprRef`) - The maximum length of the text mark in pixels. The text value will be automatically - truncated if the rendered size exceeds the limit. - - **Default value:** ``0`` -- indicating no limit - line : anyOf(boolean, :class:`OverlayMarkDef`) - A flag for overlaying line on top of area marks, or an object defining the - properties of the overlayed lines. - - - If this value is an empty object ( ``{}`` ) or ``true``, lines with default - properties will be used. - - If this value is ``false``, no lines would be automatically added to area marks. - - **Default value:** ``false``. - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property is ignored if the text is array-valued. - lineHeight : anyOf(float, :class:`ExprRef`) - The line height in pixels (the spacing between subsequent lines of text) for - multi-line text marks. - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - order : anyOf(None, boolean) - For line and trail marks, this ``order`` property can be set to ``null`` or - ``false`` to make the lines use the original order in the data sources. - orient : :class:`Orientation` - The orientation of a non-stacked bar, tick, area, and line charts. The value is - either horizontal (default) or vertical. - - - * For bar, rule and tick, this determines whether the size of the bar and tick - should be applied to x or y dimension. - * For area, this property determines the orient property of the Vega output. - * For line and trail marks, this property determines the sort order of the points in - the line if ``config.sortLineBy`` is not specified. For stacked charts, this is - always determined by the orientation of the stack; therefore explicitly specified - value will be ignored. - outerRadius : anyOf(float, :class:`ExprRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - - **Default value:** ``0`` - padAngle : anyOf(float, :class:`ExprRef`) - The angular padding applied to sides of the arc, in radians. - point : anyOf(boolean, :class:`OverlayMarkDef`, string) - A flag for overlaying points on top of line or area marks, or an object defining the - properties of the overlayed points. - - - If this property is ``"transparent"``, transparent points will be used (for - enhancing tooltips and selections). - - If this property is an empty object ( ``{}`` ) or ``true``, filled points with - default properties will be used. - - If this property is ``false``, no points would be automatically added to line or - area marks. - - **Default value:** ``false``. - radius : anyOf(float, :class:`ExprRef`) - For arc mark, the primary (outer) radius in pixels. - - For text marks, polar coordinate radial offset, in pixels, of the text from the - origin determined by the ``x`` and ``y`` properties. - - **Default value:** ``min(plot_width, plot_height)/2`` - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - - **Default value:** ``0`` - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - Shape of the point marks. Supported values include: - - - * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, - ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or - ``"triangle-left"``. - * the line symbol ``"stroke"`` - * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - * a custom `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - **Default value:** ``"circle"`` - size : anyOf(float, :class:`ExprRef`) - Default size for marks. - - - * For ``point`` / ``circle`` / ``square``, this represents the pixel area of the - marks. Note that this value sets the area of the symbol; the side lengths will - increase with the square root of this value. - * For ``bar``, this represents the band size of the bar, in pixels. - * For ``text``, this represents the font size, in pixels. - - **Default value:** - - - * ``30`` for point, circle, square marks; width/height's ``step`` - * ``2`` for bar marks with discrete dimensions; - * ``5`` for bar marks with continuous dimensions; - * ``11`` for text marks. - smooth : anyOf(boolean, :class:`ExprRef`) - A boolean flag (default true) indicating if the image should be smoothed when - resized. If false, individual pixels should be scaled directly rather than - interpolated with smoothing. For SVG rendering, this option may not work in some - browsers due to lack of standardization. - startAngle : anyOf(float, :class:`ExprRef`) - The start angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default stroke color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove stroke. - - **Default value:** (None) - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOffset : anyOf(float, :class:`ExprRef`) - The offset in pixels at which to draw the group stroke and fill. If unspecified, the - default behavior is to dynamically offset stroked groups such that 1 pixel stroke - widths align with the pixel grid. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - tension : anyOf(float, :class:`ExprRef`) - Depending on the interpolation type, sets the tension parameter (for line and area - marks). - text : anyOf(:class:`Text`, :class:`ExprRef`) - Placeholder text if the ``text`` channel is not specified - theta : anyOf(float, :class:`ExprRef`) - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : anyOf(float, :class:`ExprRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - timeUnitBandPosition : float - Default relative band position for a time unit. If set to ``0``, the marks will be - positioned at the beginning of the time unit band step. If set to ``0.5``, the marks - will be positioned in the middle of the time unit band step. - timeUnitBandSize : float - Default relative band size for a time unit. If set to ``1``, the bandwidth of the - marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the - marks will be half of the time unit band step. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprRef`, None) - The tooltip text string to show upon mouse hover or an object defining which fields - should the tooltip be derived from. - - - * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from - ``encoding`` will be used. - * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the - highlighted data point will be used. - * If set to ``null`` or ``false``, then no tooltip will be used. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - - **Default value:** ``null`` - url : anyOf(:class:`URI`, :class:`ExprRef`) - The URL of the image file for image marks. - width : anyOf(float, :class:`ExprRef`) - Width of the marks. - x : anyOf(float, string, :class:`ExprRef`) - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : anyOf(float, string, :class:`ExprRef`) - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - y : anyOf(float, string, :class:`ExprRef`) - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : anyOf(float, string, :class:`ExprRef`) - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - """ - _schema = {'$ref': '#/definitions/AreaConfig'} - - def __init__(self, align=Undefined, angle=Undefined, aria=Undefined, ariaRole=Undefined, - ariaRoleDescription=Undefined, aspect=Undefined, baseline=Undefined, blend=Undefined, - color=Undefined, cornerRadius=Undefined, cornerRadiusBottomLeft=Undefined, - cornerRadiusBottomRight=Undefined, cornerRadiusTopLeft=Undefined, - cornerRadiusTopRight=Undefined, cursor=Undefined, description=Undefined, dir=Undefined, - dx=Undefined, dy=Undefined, ellipsis=Undefined, endAngle=Undefined, fill=Undefined, - fillOpacity=Undefined, filled=Undefined, font=Undefined, fontSize=Undefined, - fontStyle=Undefined, fontWeight=Undefined, height=Undefined, href=Undefined, - innerRadius=Undefined, interpolate=Undefined, invalid=Undefined, limit=Undefined, - line=Undefined, lineBreak=Undefined, lineHeight=Undefined, opacity=Undefined, - order=Undefined, orient=Undefined, outerRadius=Undefined, padAngle=Undefined, - point=Undefined, radius=Undefined, radius2=Undefined, shape=Undefined, size=Undefined, - smooth=Undefined, startAngle=Undefined, stroke=Undefined, strokeCap=Undefined, - strokeDash=Undefined, strokeDashOffset=Undefined, strokeJoin=Undefined, - strokeMiterLimit=Undefined, strokeOffset=Undefined, strokeOpacity=Undefined, - strokeWidth=Undefined, tension=Undefined, text=Undefined, theta=Undefined, - theta2=Undefined, timeUnitBandPosition=Undefined, timeUnitBandSize=Undefined, - tooltip=Undefined, url=Undefined, width=Undefined, x=Undefined, x2=Undefined, - y=Undefined, y2=Undefined, **kwds): - super(AreaConfig, self).__init__(align=align, angle=angle, aria=aria, ariaRole=ariaRole, - ariaRoleDescription=ariaRoleDescription, aspect=aspect, - baseline=baseline, blend=blend, color=color, - cornerRadius=cornerRadius, - cornerRadiusBottomLeft=cornerRadiusBottomLeft, - cornerRadiusBottomRight=cornerRadiusBottomRight, - cornerRadiusTopLeft=cornerRadiusTopLeft, - cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, - description=description, dir=dir, dx=dx, dy=dy, - ellipsis=ellipsis, endAngle=endAngle, fill=fill, - fillOpacity=fillOpacity, filled=filled, font=font, - fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, - height=height, href=href, innerRadius=innerRadius, - interpolate=interpolate, invalid=invalid, limit=limit, - line=line, lineBreak=lineBreak, lineHeight=lineHeight, - opacity=opacity, order=order, orient=orient, - outerRadius=outerRadius, padAngle=padAngle, point=point, - radius=radius, radius2=radius2, shape=shape, size=size, - smooth=smooth, startAngle=startAngle, stroke=stroke, - strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, strokeOffset=strokeOffset, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - tension=tension, text=text, theta=theta, theta2=theta2, - timeUnitBandPosition=timeUnitBandPosition, - timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, url=url, - width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class ArgmaxDef(Aggregate): - """ArgmaxDef schema wrapper - - Mapping(required=[argmax]) - - Parameters - ---------- - - argmax : :class:`FieldName` - - """ - _schema = {'$ref': '#/definitions/ArgmaxDef'} - - def __init__(self, argmax=Undefined, **kwds): - super(ArgmaxDef, self).__init__(argmax=argmax, **kwds) - - -class ArgminDef(Aggregate): - """ArgminDef schema wrapper - - Mapping(required=[argmin]) - - Parameters - ---------- - - argmin : :class:`FieldName` - - """ - _schema = {'$ref': '#/definitions/ArgminDef'} - - def __init__(self, argmin=Undefined, **kwds): - super(ArgminDef, self).__init__(argmin=argmin, **kwds) - - -class AutoSizeParams(VegaLiteSchema): - """AutoSizeParams schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - contains : enum('content', 'padding') - Determines how size calculation should be performed, one of ``"content"`` or - ``"padding"``. The default setting ( ``"content"`` ) interprets the width and height - settings as the data rectangle (plotting) dimensions, to which padding is then - added. In contrast, the ``"padding"`` setting includes the padding within the view - size calculations, such that the width and height settings indicate the **total** - intended size of the view. - - **Default value** : ``"content"`` - resize : boolean - A boolean flag indicating if autosize layout should be re-calculated on every view - update. - - **Default value** : ``false`` - type : :class:`AutosizeType` - The sizing format type. One of ``"pad"``, ``"fit"``, ``"fit-x"``, ``"fit-y"``, or - ``"none"``. See the `autosize type - `__ documentation for - descriptions of each. - - **Default value** : ``"pad"`` - """ - _schema = {'$ref': '#/definitions/AutoSizeParams'} - - def __init__(self, contains=Undefined, resize=Undefined, type=Undefined, **kwds): - super(AutoSizeParams, self).__init__(contains=contains, resize=resize, type=type, **kwds) - - -class AutosizeType(VegaLiteSchema): - """AutosizeType schema wrapper - - enum('pad', 'none', 'fit', 'fit-x', 'fit-y') - """ - _schema = {'$ref': '#/definitions/AutosizeType'} - - def __init__(self, *args): - super(AutosizeType, self).__init__(*args) - - -class Axis(VegaLiteSchema): - """Axis schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG group, removing the axis from the ARIA accessibility tree. - - **Default value:** ``true`` - bandPosition : anyOf(float, :class:`ExprRef`) - An interpolation fraction indicating where, for ``band`` scales, axis ticks should - be positioned. A value of ``0`` places ticks at the left edge of their bands. A - value of ``0.5`` places ticks in the middle of their bands. - - **Default value:** ``0.5`` - description : anyOf(string, :class:`ExprRef`) - A text description of this axis for `ARIA accessibility - `__ (SVG output - only). If the ``aria`` property is true, for SVG output the `"aria-label" attribute - `__ - will be set to this description. If the description is unspecified it will be - automatically generated. - domain : boolean - A boolean flag indicating if the domain (the axis baseline) should be included as - part of the axis. - - **Default value:** ``true`` - domainCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for the domain line's ending style. One of ``"butt"``, ``"round"`` or - ``"square"``. - - **Default value:** ``"butt"`` - domainColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Color of axis domain line. - - **Default value:** ``"gray"``. - domainDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating [stroke, space] lengths for dashed domain lines. - domainDashOffset : anyOf(float, :class:`ExprRef`) - The pixel offset at which to start drawing with the domain dash array. - domainOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the axis domain line. - domainWidth : anyOf(float, :class:`ExprRef`) - Stroke width of axis domain line - - **Default value:** ``1`` - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - grid : boolean - A boolean flag indicating if grid lines should be included as part of the axis - - **Default value:** ``true`` for `continuous scales - `__ that are not - binned; otherwise, ``false``. - gridCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for grid lines' ending style. One of ``"butt"``, ``"round"`` or - ``"square"``. - - **Default value:** ``"butt"`` - gridColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, :class:`ConditionalAxisColor`) - Color of gridlines. - - **Default value:** ``"lightGray"``. - gridDash : anyOf(List(float), :class:`ExprRef`, :class:`ConditionalAxisNumberArray`) - An array of alternating [stroke, space] lengths for dashed grid lines. - gridDashOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The pixel offset at which to start drawing with the grid dash array. - gridOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The stroke opacity of grid (value between [0,1]) - - **Default value:** ``1`` - gridWidth : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The grid width, in pixels. - - **Default value:** ``1`` - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`, :class:`ConditionalAxisLabelAlign`) - Horizontal text alignment of axis tick labels, overriding the default setting for - the current axis orientation. - labelAngle : anyOf(float, :class:`ExprRef`) - The rotation angle of the axis labels. - - **Default value:** ``-90`` for nominal and ordinal fields; ``0`` otherwise. - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`, :class:`ConditionalAxisLabelBaseline`) - Vertical text baseline of axis tick labels, overriding the default setting for the - current axis orientation. One of ``"alphabetic"`` (default), ``"top"``, - ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The ``"line-top"`` - and ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but - are calculated relative to the *lineHeight* rather than *fontSize* alone. - labelBound : anyOf(anyOf(float, boolean), :class:`ExprRef`) - Indicates if labels should be hidden if they exceed the axis range. If ``false`` - (the default) no bounds overlap analysis is performed. If ``true``, labels will be - hidden if they exceed the axis range by more than 1 pixel. If this property is a - number, it specifies the pixel tolerance: the maximum amount by which a label - bounding box may exceed the axis range. - - **Default value:** ``false``. - labelColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, :class:`ConditionalAxisColor`) - The color of the tick label, can be in hex color code or regular color name. - labelExpr : string - `Vega expression `__ for customizing - labels. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - labelFlush : anyOf(boolean, float) - Indicates if the first and last axis labels should be aligned flush with the scale - range. Flush alignment for a horizontal axis will left-align the first label and - right-align the last label. For vertical axes, bottom and top text baselines are - applied instead. If this property is a number, it also indicates the number of - pixels by which to offset the first and last labels; for example, a value of 2 will - flush-align the first and last labels and also push them 2 pixels outward from the - center of the axis. The additional adjustment can sometimes help the labels better - visually group with corresponding axis ticks. - - **Default value:** ``true`` for axis of a continuous x-scale. Otherwise, ``false``. - labelFlushOffset : anyOf(float, :class:`ExprRef`) - Indicates the number of pixels by which to offset flush-adjusted labels. For - example, a value of ``2`` will push flush-adjusted labels 2 pixels outward from the - center of the axis. Offsets can help the labels better visually group with - corresponding axis ticks. - - **Default value:** ``0``. - labelFont : anyOf(string, :class:`ExprRef`, :class:`ConditionalAxisString`) - The font of the tick label. - labelFontSize : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The font size of the label, in pixels. - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`, :class:`ConditionalAxisLabelFontStyle`) - Font style of the title. - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`, :class:`ConditionalAxisLabelFontWeight`) - Font weight of axis tick labels. - labelLimit : anyOf(float, :class:`ExprRef`) - Maximum allowed pixel width of axis tick labels. - - **Default value:** ``180`` - labelLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line label text or label text with ``"line-top"`` or - ``"line-bottom"`` baseline. - labelOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - Position offset in pixels to apply to labels, in addition to tickOffset. - - **Default value:** ``0`` - labelOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The opacity of the labels. - labelOverlap : anyOf(:class:`LabelOverlap`, :class:`ExprRef`) - The strategy to use for resolving overlap of axis labels. If ``false`` (the - default), no overlap reduction is attempted. If set to ``true`` or ``"parity"``, a - strategy of removing every other label is used (this works well for standard linear - axes). If set to ``"greedy"``, a linear scan of the labels is performed, removing - any labels that overlaps with the last visible label (this often works better for - log-scaled axes). - - **Default value:** ``true`` for non-nominal fields with non-log scales; ``"greedy"`` - for log scales; otherwise ``false``. - labelPadding : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The padding in pixels between labels and ticks. - - **Default value:** ``2`` - labelSeparation : anyOf(float, :class:`ExprRef`) - The minimum separation that must be between label bounding boxes for them to be - considered non-overlapping (default ``0`` ). This property is ignored if - *labelOverlap* resolution is not enabled. - labels : boolean - A boolean flag indicating if labels should be included as part of the axis. - - **Default value:** ``true``. - maxExtent : anyOf(float, :class:`ExprRef`) - The maximum extent in pixels that axis ticks and labels should use. This determines - a maximum offset value for axis titles. - - **Default value:** ``undefined``. - minExtent : anyOf(float, :class:`ExprRef`) - The minimum extent in pixels that axis ticks and labels should use. This determines - a minimum offset value for axis titles. - - **Default value:** ``30`` for y-axis; ``undefined`` for x-axis. - offset : anyOf(float, :class:`ExprRef`) - The offset, in pixels, by which to displace the axis from the edge of the enclosing - group or data rectangle. - - **Default value:** derived from the `axis config - `__ 's - ``offset`` ( ``0`` by default) - orient : anyOf(:class:`AxisOrient`, :class:`ExprRef`) - The orientation of the axis. One of ``"top"``, ``"bottom"``, ``"left"`` or - ``"right"``. The orientation can be used to further specialize the axis type (e.g., - a y-axis oriented towards the right edge of the chart). - - **Default value:** ``"bottom"`` for x-axes and ``"left"`` for y-axes. - position : anyOf(float, :class:`ExprRef`) - The anchor position of the axis in pixels. For x-axes with top or bottom - orientation, this sets the axis group x coordinate. For y-axes with left or right - orientation, this sets the axis group y coordinate. - - **Default value** : ``0`` - style : anyOf(string, List(string)) - A string or array of strings indicating the name of custom styles to apply to the - axis. A style is a named collection of axis property defined within the `style - configuration `__. If - style is an array, later styles will override earlier styles. - - **Default value:** (none) **Note:** Any specified style will augment the default - style. For example, an x-axis mark with ``"style": "foo"`` will use ``config.axisX`` - and ``config.style.foo`` (the specified style ``"foo"`` has higher precedence). - tickBand : anyOf(enum('center', 'extent'), :class:`ExprRef`) - For band scales, indicates if ticks and grid lines should be placed at the - ``"center"`` of a band (default) or at the band ``"extent"`` s to indicate intervals - tickCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for the tick lines' ending style. One of ``"butt"``, ``"round"`` or - ``"square"``. - - **Default value:** ``"butt"`` - tickColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, :class:`ConditionalAxisColor`) - The color of the axis's tick. - - **Default value:** ``"gray"`` - tickCount : anyOf(float, :class:`TimeInterval`, :class:`TimeIntervalStep`, :class:`ExprRef`) - A desired number of ticks, for axes visualizing quantitative scales. The resulting - number may be different so that values are "nice" (multiples of 2, 5, 10) and lie - within the underlying scale's range. - - For scales of type ``"time"`` or ``"utc"``, the tick count can instead be a time - interval specifier. Legal string values are ``"millisecond"``, ``"second"``, - ``"minute"``, ``"hour"``, ``"day"``, ``"week"``, ``"month"``, and ``"year"``. - Alternatively, an object-valued interval specifier of the form ``{"interval": - "month", "step": 3}`` includes a desired number of interval steps. Here, ticks are - generated for each quarter (Jan, Apr, Jul, Oct) boundary. - - **Default value** : Determine using a formula ``ceil(width/40)`` for x and - ``ceil(height/40)`` for y. - tickDash : anyOf(List(float), :class:`ExprRef`, :class:`ConditionalAxisNumberArray`) - An array of alternating [stroke, space] lengths for dashed tick mark lines. - tickDashOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The pixel offset at which to start drawing with the tick mark dash array. - tickExtra : boolean - Boolean flag indicating if an extra axis tick should be added for the initial - position of the axis. This flag is useful for styling axes for ``band`` scales such - that ticks are placed on band boundaries rather in the middle of a band. Use in - conjunction with ``"bandPosition": 1`` and an axis ``"padding"`` value of ``0``. - tickMinStep : anyOf(float, :class:`ExprRef`) - The minimum desired step between axis ticks, in terms of scale domain values. For - example, a value of ``1`` indicates that ticks should not be less than 1 unit apart. - If ``tickMinStep`` is specified, the ``tickCount`` value will be adjusted, if - necessary, to enforce the minimum step value. - tickOffset : anyOf(float, :class:`ExprRef`) - Position offset in pixels to apply to ticks, labels, and gridlines. - tickOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - Opacity of the ticks. - tickRound : boolean - Boolean flag indicating if pixel position values should be rounded to the nearest - integer. - - **Default value:** ``true`` - tickSize : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The size in pixels of axis ticks. - - **Default value:** ``5`` - tickWidth : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The width, in pixels, of ticks. - - **Default value:** ``1`` - ticks : boolean - Boolean value that determines whether the axis should include ticks. - - **Default value:** ``true`` - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - titleAlign : anyOf(:class:`Align`, :class:`ExprRef`) - Horizontal text alignment of axis titles. - titleAnchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - Text anchor position for placing axis titles. - titleAngle : anyOf(float, :class:`ExprRef`) - Angle in degrees of axis titles. - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - Vertical text baseline for axis titles. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The - ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and - ``"bottom"``, but are calculated relative to the *lineHeight* rather than *fontSize* - alone. - titleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Color of the title, can be in hex color code or regular color name. - titleFont : anyOf(string, :class:`ExprRef`) - Font of the title. (e.g., ``"Helvetica Neue"`` ). - titleFontSize : anyOf(float, :class:`ExprRef`) - Font size of the title. - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - Font style of the title. - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight of the title. This can be either a string (e.g ``"bold"``, ``"normal"`` - ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` - and ``"bold"`` = ``700`` ). - titleLimit : anyOf(float, :class:`ExprRef`) - Maximum allowed pixel width of axis titles. - titleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line title text or title text with ``"line-top"`` or - ``"line-bottom"`` baseline. - titleOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the axis title. - titlePadding : anyOf(float, :class:`ExprRef`) - The padding, in pixels, between title and axis. - titleX : anyOf(float, :class:`ExprRef`) - X-coordinate of the axis title relative to the axis group. - titleY : anyOf(float, :class:`ExprRef`) - Y-coordinate of the axis title relative to the axis group. - translate : anyOf(float, :class:`ExprRef`) - Coordinate space translation offset for axis layout. By default, axes are translated - by a 0.5 pixel offset for both the x and y coordinates in order to align stroked - lines with the pixel grid. However, for vector graphics output these pixel-specific - adjustments may be undesirable, in which case translate can be changed (for example, - to zero). - - **Default value:** ``0.5`` - values : anyOf(List(float), List(string), List(boolean), List(:class:`DateTime`), :class:`ExprRef`) - Explicitly set the visible axis tick values. - zindex : float - A non-negative integer indicating the z-index of the axis. If zindex is 0, axes - should be drawn behind all chart elements. To put them in front, set ``zindex`` to - ``1`` or more. - - **Default value:** ``0`` (behind the marks). - """ - _schema = {'$ref': '#/definitions/Axis'} - - def __init__(self, aria=Undefined, bandPosition=Undefined, description=Undefined, domain=Undefined, - domainCap=Undefined, domainColor=Undefined, domainDash=Undefined, - domainDashOffset=Undefined, domainOpacity=Undefined, domainWidth=Undefined, - format=Undefined, formatType=Undefined, grid=Undefined, gridCap=Undefined, - gridColor=Undefined, gridDash=Undefined, gridDashOffset=Undefined, - gridOpacity=Undefined, gridWidth=Undefined, labelAlign=Undefined, labelAngle=Undefined, - labelBaseline=Undefined, labelBound=Undefined, labelColor=Undefined, - labelExpr=Undefined, labelFlush=Undefined, labelFlushOffset=Undefined, - labelFont=Undefined, labelFontSize=Undefined, labelFontStyle=Undefined, - labelFontWeight=Undefined, labelLimit=Undefined, labelLineHeight=Undefined, - labelOffset=Undefined, labelOpacity=Undefined, labelOverlap=Undefined, - labelPadding=Undefined, labelSeparation=Undefined, labels=Undefined, - maxExtent=Undefined, minExtent=Undefined, offset=Undefined, orient=Undefined, - position=Undefined, style=Undefined, tickBand=Undefined, tickCap=Undefined, - tickColor=Undefined, tickCount=Undefined, tickDash=Undefined, tickDashOffset=Undefined, - tickExtra=Undefined, tickMinStep=Undefined, tickOffset=Undefined, - tickOpacity=Undefined, tickRound=Undefined, tickSize=Undefined, tickWidth=Undefined, - ticks=Undefined, title=Undefined, titleAlign=Undefined, titleAnchor=Undefined, - titleAngle=Undefined, titleBaseline=Undefined, titleColor=Undefined, - titleFont=Undefined, titleFontSize=Undefined, titleFontStyle=Undefined, - titleFontWeight=Undefined, titleLimit=Undefined, titleLineHeight=Undefined, - titleOpacity=Undefined, titlePadding=Undefined, titleX=Undefined, titleY=Undefined, - translate=Undefined, values=Undefined, zindex=Undefined, **kwds): - super(Axis, self).__init__(aria=aria, bandPosition=bandPosition, description=description, - domain=domain, domainCap=domainCap, domainColor=domainColor, - domainDash=domainDash, domainDashOffset=domainDashOffset, - domainOpacity=domainOpacity, domainWidth=domainWidth, format=format, - formatType=formatType, grid=grid, gridCap=gridCap, - gridColor=gridColor, gridDash=gridDash, - gridDashOffset=gridDashOffset, gridOpacity=gridOpacity, - gridWidth=gridWidth, labelAlign=labelAlign, labelAngle=labelAngle, - labelBaseline=labelBaseline, labelBound=labelBound, - labelColor=labelColor, labelExpr=labelExpr, labelFlush=labelFlush, - labelFlushOffset=labelFlushOffset, labelFont=labelFont, - labelFontSize=labelFontSize, labelFontStyle=labelFontStyle, - labelFontWeight=labelFontWeight, labelLimit=labelLimit, - labelLineHeight=labelLineHeight, labelOffset=labelOffset, - labelOpacity=labelOpacity, labelOverlap=labelOverlap, - labelPadding=labelPadding, labelSeparation=labelSeparation, - labels=labels, maxExtent=maxExtent, minExtent=minExtent, - offset=offset, orient=orient, position=position, style=style, - tickBand=tickBand, tickCap=tickCap, tickColor=tickColor, - tickCount=tickCount, tickDash=tickDash, - tickDashOffset=tickDashOffset, tickExtra=tickExtra, - tickMinStep=tickMinStep, tickOffset=tickOffset, - tickOpacity=tickOpacity, tickRound=tickRound, tickSize=tickSize, - tickWidth=tickWidth, ticks=ticks, title=title, titleAlign=titleAlign, - titleAnchor=titleAnchor, titleAngle=titleAngle, - titleBaseline=titleBaseline, titleColor=titleColor, - titleFont=titleFont, titleFontSize=titleFontSize, - titleFontStyle=titleFontStyle, titleFontWeight=titleFontWeight, - titleLimit=titleLimit, titleLineHeight=titleLineHeight, - titleOpacity=titleOpacity, titlePadding=titlePadding, titleX=titleX, - titleY=titleY, translate=translate, values=values, zindex=zindex, - **kwds) - - -class AxisConfig(VegaLiteSchema): - """AxisConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG group, removing the axis from the ARIA accessibility tree. - - **Default value:** ``true`` - bandPosition : anyOf(float, :class:`ExprRef`) - An interpolation fraction indicating where, for ``band`` scales, axis ticks should - be positioned. A value of ``0`` places ticks at the left edge of their bands. A - value of ``0.5`` places ticks in the middle of their bands. - - **Default value:** ``0.5`` - description : anyOf(string, :class:`ExprRef`) - A text description of this axis for `ARIA accessibility - `__ (SVG output - only). If the ``aria`` property is true, for SVG output the `"aria-label" attribute - `__ - will be set to this description. If the description is unspecified it will be - automatically generated. - disable : boolean - Disable axis by default. - domain : boolean - A boolean flag indicating if the domain (the axis baseline) should be included as - part of the axis. - - **Default value:** ``true`` - domainCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for the domain line's ending style. One of ``"butt"``, ``"round"`` or - ``"square"``. - - **Default value:** ``"butt"`` - domainColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Color of axis domain line. - - **Default value:** ``"gray"``. - domainDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating [stroke, space] lengths for dashed domain lines. - domainDashOffset : anyOf(float, :class:`ExprRef`) - The pixel offset at which to start drawing with the domain dash array. - domainOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the axis domain line. - domainWidth : anyOf(float, :class:`ExprRef`) - Stroke width of axis domain line - - **Default value:** ``1`` - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - grid : boolean - A boolean flag indicating if grid lines should be included as part of the axis - - **Default value:** ``true`` for `continuous scales - `__ that are not - binned; otherwise, ``false``. - gridCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for grid lines' ending style. One of ``"butt"``, ``"round"`` or - ``"square"``. - - **Default value:** ``"butt"`` - gridColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, :class:`ConditionalAxisColor`) - Color of gridlines. - - **Default value:** ``"lightGray"``. - gridDash : anyOf(List(float), :class:`ExprRef`, :class:`ConditionalAxisNumberArray`) - An array of alternating [stroke, space] lengths for dashed grid lines. - gridDashOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The pixel offset at which to start drawing with the grid dash array. - gridOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The stroke opacity of grid (value between [0,1]) - - **Default value:** ``1`` - gridWidth : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The grid width, in pixels. - - **Default value:** ``1`` - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`, :class:`ConditionalAxisLabelAlign`) - Horizontal text alignment of axis tick labels, overriding the default setting for - the current axis orientation. - labelAngle : anyOf(float, :class:`ExprRef`) - The rotation angle of the axis labels. - - **Default value:** ``-90`` for nominal and ordinal fields; ``0`` otherwise. - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`, :class:`ConditionalAxisLabelBaseline`) - Vertical text baseline of axis tick labels, overriding the default setting for the - current axis orientation. One of ``"alphabetic"`` (default), ``"top"``, - ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The ``"line-top"`` - and ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but - are calculated relative to the *lineHeight* rather than *fontSize* alone. - labelBound : anyOf(anyOf(float, boolean), :class:`ExprRef`) - Indicates if labels should be hidden if they exceed the axis range. If ``false`` - (the default) no bounds overlap analysis is performed. If ``true``, labels will be - hidden if they exceed the axis range by more than 1 pixel. If this property is a - number, it specifies the pixel tolerance: the maximum amount by which a label - bounding box may exceed the axis range. - - **Default value:** ``false``. - labelColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, :class:`ConditionalAxisColor`) - The color of the tick label, can be in hex color code or regular color name. - labelExpr : string - `Vega expression `__ for customizing - labels. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the axis's backing ``datum`` object. - labelFlush : anyOf(boolean, float) - Indicates if the first and last axis labels should be aligned flush with the scale - range. Flush alignment for a horizontal axis will left-align the first label and - right-align the last label. For vertical axes, bottom and top text baselines are - applied instead. If this property is a number, it also indicates the number of - pixels by which to offset the first and last labels; for example, a value of 2 will - flush-align the first and last labels and also push them 2 pixels outward from the - center of the axis. The additional adjustment can sometimes help the labels better - visually group with corresponding axis ticks. - - **Default value:** ``true`` for axis of a continuous x-scale. Otherwise, ``false``. - labelFlushOffset : anyOf(float, :class:`ExprRef`) - Indicates the number of pixels by which to offset flush-adjusted labels. For - example, a value of ``2`` will push flush-adjusted labels 2 pixels outward from the - center of the axis. Offsets can help the labels better visually group with - corresponding axis ticks. - - **Default value:** ``0``. - labelFont : anyOf(string, :class:`ExprRef`, :class:`ConditionalAxisString`) - The font of the tick label. - labelFontSize : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The font size of the label, in pixels. - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`, :class:`ConditionalAxisLabelFontStyle`) - Font style of the title. - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`, :class:`ConditionalAxisLabelFontWeight`) - Font weight of axis tick labels. - labelLimit : anyOf(float, :class:`ExprRef`) - Maximum allowed pixel width of axis tick labels. - - **Default value:** ``180`` - labelLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line label text or label text with ``"line-top"`` or - ``"line-bottom"`` baseline. - labelOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - Position offset in pixels to apply to labels, in addition to tickOffset. - - **Default value:** ``0`` - labelOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The opacity of the labels. - labelOverlap : anyOf(:class:`LabelOverlap`, :class:`ExprRef`) - The strategy to use for resolving overlap of axis labels. If ``false`` (the - default), no overlap reduction is attempted. If set to ``true`` or ``"parity"``, a - strategy of removing every other label is used (this works well for standard linear - axes). If set to ``"greedy"``, a linear scan of the labels is performed, removing - any labels that overlaps with the last visible label (this often works better for - log-scaled axes). - - **Default value:** ``true`` for non-nominal fields with non-log scales; ``"greedy"`` - for log scales; otherwise ``false``. - labelPadding : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The padding in pixels between labels and ticks. - - **Default value:** ``2`` - labelSeparation : anyOf(float, :class:`ExprRef`) - The minimum separation that must be between label bounding boxes for them to be - considered non-overlapping (default ``0`` ). This property is ignored if - *labelOverlap* resolution is not enabled. - labels : boolean - A boolean flag indicating if labels should be included as part of the axis. - - **Default value:** ``true``. - maxExtent : anyOf(float, :class:`ExprRef`) - The maximum extent in pixels that axis ticks and labels should use. This determines - a maximum offset value for axis titles. - - **Default value:** ``undefined``. - minExtent : anyOf(float, :class:`ExprRef`) - The minimum extent in pixels that axis ticks and labels should use. This determines - a minimum offset value for axis titles. - - **Default value:** ``30`` for y-axis; ``undefined`` for x-axis. - offset : anyOf(float, :class:`ExprRef`) - The offset, in pixels, by which to displace the axis from the edge of the enclosing - group or data rectangle. - - **Default value:** derived from the `axis config - `__ 's - ``offset`` ( ``0`` by default) - orient : anyOf(:class:`AxisOrient`, :class:`ExprRef`) - The orientation of the axis. One of ``"top"``, ``"bottom"``, ``"left"`` or - ``"right"``. The orientation can be used to further specialize the axis type (e.g., - a y-axis oriented towards the right edge of the chart). - - **Default value:** ``"bottom"`` for x-axes and ``"left"`` for y-axes. - position : anyOf(float, :class:`ExprRef`) - The anchor position of the axis in pixels. For x-axes with top or bottom - orientation, this sets the axis group x coordinate. For y-axes with left or right - orientation, this sets the axis group y coordinate. - - **Default value** : ``0`` - style : anyOf(string, List(string)) - A string or array of strings indicating the name of custom styles to apply to the - axis. A style is a named collection of axis property defined within the `style - configuration `__. If - style is an array, later styles will override earlier styles. - - **Default value:** (none) **Note:** Any specified style will augment the default - style. For example, an x-axis mark with ``"style": "foo"`` will use ``config.axisX`` - and ``config.style.foo`` (the specified style ``"foo"`` has higher precedence). - tickBand : anyOf(enum('center', 'extent'), :class:`ExprRef`) - For band scales, indicates if ticks and grid lines should be placed at the - ``"center"`` of a band (default) or at the band ``"extent"`` s to indicate intervals - tickCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for the tick lines' ending style. One of ``"butt"``, ``"round"`` or - ``"square"``. - - **Default value:** ``"butt"`` - tickColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`, :class:`ConditionalAxisColor`) - The color of the axis's tick. - - **Default value:** ``"gray"`` - tickCount : anyOf(float, :class:`TimeInterval`, :class:`TimeIntervalStep`, :class:`ExprRef`) - A desired number of ticks, for axes visualizing quantitative scales. The resulting - number may be different so that values are "nice" (multiples of 2, 5, 10) and lie - within the underlying scale's range. - - For scales of type ``"time"`` or ``"utc"``, the tick count can instead be a time - interval specifier. Legal string values are ``"millisecond"``, ``"second"``, - ``"minute"``, ``"hour"``, ``"day"``, ``"week"``, ``"month"``, and ``"year"``. - Alternatively, an object-valued interval specifier of the form ``{"interval": - "month", "step": 3}`` includes a desired number of interval steps. Here, ticks are - generated for each quarter (Jan, Apr, Jul, Oct) boundary. - - **Default value** : Determine using a formula ``ceil(width/40)`` for x and - ``ceil(height/40)`` for y. - tickDash : anyOf(List(float), :class:`ExprRef`, :class:`ConditionalAxisNumberArray`) - An array of alternating [stroke, space] lengths for dashed tick mark lines. - tickDashOffset : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The pixel offset at which to start drawing with the tick mark dash array. - tickExtra : boolean - Boolean flag indicating if an extra axis tick should be added for the initial - position of the axis. This flag is useful for styling axes for ``band`` scales such - that ticks are placed on band boundaries rather in the middle of a band. Use in - conjunction with ``"bandPosition": 1`` and an axis ``"padding"`` value of ``0``. - tickMinStep : anyOf(float, :class:`ExprRef`) - The minimum desired step between axis ticks, in terms of scale domain values. For - example, a value of ``1`` indicates that ticks should not be less than 1 unit apart. - If ``tickMinStep`` is specified, the ``tickCount`` value will be adjusted, if - necessary, to enforce the minimum step value. - tickOffset : anyOf(float, :class:`ExprRef`) - Position offset in pixels to apply to ticks, labels, and gridlines. - tickOpacity : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - Opacity of the ticks. - tickRound : boolean - Boolean flag indicating if pixel position values should be rounded to the nearest - integer. - - **Default value:** ``true`` - tickSize : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The size in pixels of axis ticks. - - **Default value:** ``5`` - tickWidth : anyOf(float, :class:`ExprRef`, :class:`ConditionalAxisNumber`) - The width, in pixels, of ticks. - - **Default value:** ``1`` - ticks : boolean - Boolean value that determines whether the axis should include ticks. - - **Default value:** ``true`` - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - titleAlign : anyOf(:class:`Align`, :class:`ExprRef`) - Horizontal text alignment of axis titles. - titleAnchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - Text anchor position for placing axis titles. - titleAngle : anyOf(float, :class:`ExprRef`) - Angle in degrees of axis titles. - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - Vertical text baseline for axis titles. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The - ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and - ``"bottom"``, but are calculated relative to the *lineHeight* rather than *fontSize* - alone. - titleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Color of the title, can be in hex color code or regular color name. - titleFont : anyOf(string, :class:`ExprRef`) - Font of the title. (e.g., ``"Helvetica Neue"`` ). - titleFontSize : anyOf(float, :class:`ExprRef`) - Font size of the title. - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - Font style of the title. - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight of the title. This can be either a string (e.g ``"bold"``, ``"normal"`` - ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` - and ``"bold"`` = ``700`` ). - titleLimit : anyOf(float, :class:`ExprRef`) - Maximum allowed pixel width of axis titles. - titleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line title text or title text with ``"line-top"`` or - ``"line-bottom"`` baseline. - titleOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the axis title. - titlePadding : anyOf(float, :class:`ExprRef`) - The padding, in pixels, between title and axis. - titleX : anyOf(float, :class:`ExprRef`) - X-coordinate of the axis title relative to the axis group. - titleY : anyOf(float, :class:`ExprRef`) - Y-coordinate of the axis title relative to the axis group. - translate : anyOf(float, :class:`ExprRef`) - Coordinate space translation offset for axis layout. By default, axes are translated - by a 0.5 pixel offset for both the x and y coordinates in order to align stroked - lines with the pixel grid. However, for vector graphics output these pixel-specific - adjustments may be undesirable, in which case translate can be changed (for example, - to zero). - - **Default value:** ``0.5`` - values : anyOf(List(float), List(string), List(boolean), List(:class:`DateTime`), :class:`ExprRef`) - Explicitly set the visible axis tick values. - zindex : float - A non-negative integer indicating the z-index of the axis. If zindex is 0, axes - should be drawn behind all chart elements. To put them in front, set ``zindex`` to - ``1`` or more. - - **Default value:** ``0`` (behind the marks). - """ - _schema = {'$ref': '#/definitions/AxisConfig'} - - def __init__(self, aria=Undefined, bandPosition=Undefined, description=Undefined, disable=Undefined, - domain=Undefined, domainCap=Undefined, domainColor=Undefined, domainDash=Undefined, - domainDashOffset=Undefined, domainOpacity=Undefined, domainWidth=Undefined, - format=Undefined, formatType=Undefined, grid=Undefined, gridCap=Undefined, - gridColor=Undefined, gridDash=Undefined, gridDashOffset=Undefined, - gridOpacity=Undefined, gridWidth=Undefined, labelAlign=Undefined, labelAngle=Undefined, - labelBaseline=Undefined, labelBound=Undefined, labelColor=Undefined, - labelExpr=Undefined, labelFlush=Undefined, labelFlushOffset=Undefined, - labelFont=Undefined, labelFontSize=Undefined, labelFontStyle=Undefined, - labelFontWeight=Undefined, labelLimit=Undefined, labelLineHeight=Undefined, - labelOffset=Undefined, labelOpacity=Undefined, labelOverlap=Undefined, - labelPadding=Undefined, labelSeparation=Undefined, labels=Undefined, - maxExtent=Undefined, minExtent=Undefined, offset=Undefined, orient=Undefined, - position=Undefined, style=Undefined, tickBand=Undefined, tickCap=Undefined, - tickColor=Undefined, tickCount=Undefined, tickDash=Undefined, tickDashOffset=Undefined, - tickExtra=Undefined, tickMinStep=Undefined, tickOffset=Undefined, - tickOpacity=Undefined, tickRound=Undefined, tickSize=Undefined, tickWidth=Undefined, - ticks=Undefined, title=Undefined, titleAlign=Undefined, titleAnchor=Undefined, - titleAngle=Undefined, titleBaseline=Undefined, titleColor=Undefined, - titleFont=Undefined, titleFontSize=Undefined, titleFontStyle=Undefined, - titleFontWeight=Undefined, titleLimit=Undefined, titleLineHeight=Undefined, - titleOpacity=Undefined, titlePadding=Undefined, titleX=Undefined, titleY=Undefined, - translate=Undefined, values=Undefined, zindex=Undefined, **kwds): - super(AxisConfig, self).__init__(aria=aria, bandPosition=bandPosition, description=description, - disable=disable, domain=domain, domainCap=domainCap, - domainColor=domainColor, domainDash=domainDash, - domainDashOffset=domainDashOffset, domainOpacity=domainOpacity, - domainWidth=domainWidth, format=format, formatType=formatType, - grid=grid, gridCap=gridCap, gridColor=gridColor, - gridDash=gridDash, gridDashOffset=gridDashOffset, - gridOpacity=gridOpacity, gridWidth=gridWidth, - labelAlign=labelAlign, labelAngle=labelAngle, - labelBaseline=labelBaseline, labelBound=labelBound, - labelColor=labelColor, labelExpr=labelExpr, - labelFlush=labelFlush, labelFlushOffset=labelFlushOffset, - labelFont=labelFont, labelFontSize=labelFontSize, - labelFontStyle=labelFontStyle, labelFontWeight=labelFontWeight, - labelLimit=labelLimit, labelLineHeight=labelLineHeight, - labelOffset=labelOffset, labelOpacity=labelOpacity, - labelOverlap=labelOverlap, labelPadding=labelPadding, - labelSeparation=labelSeparation, labels=labels, - maxExtent=maxExtent, minExtent=minExtent, offset=offset, - orient=orient, position=position, style=style, - tickBand=tickBand, tickCap=tickCap, tickColor=tickColor, - tickCount=tickCount, tickDash=tickDash, - tickDashOffset=tickDashOffset, tickExtra=tickExtra, - tickMinStep=tickMinStep, tickOffset=tickOffset, - tickOpacity=tickOpacity, tickRound=tickRound, - tickSize=tickSize, tickWidth=tickWidth, ticks=ticks, - title=title, titleAlign=titleAlign, titleAnchor=titleAnchor, - titleAngle=titleAngle, titleBaseline=titleBaseline, - titleColor=titleColor, titleFont=titleFont, - titleFontSize=titleFontSize, titleFontStyle=titleFontStyle, - titleFontWeight=titleFontWeight, titleLimit=titleLimit, - titleLineHeight=titleLineHeight, titleOpacity=titleOpacity, - titlePadding=titlePadding, titleX=titleX, titleY=titleY, - translate=translate, values=values, zindex=zindex, **kwds) - - -class AxisOrient(VegaLiteSchema): - """AxisOrient schema wrapper - - enum('top', 'bottom', 'left', 'right') - """ - _schema = {'$ref': '#/definitions/AxisOrient'} - - def __init__(self, *args): - super(AxisOrient, self).__init__(*args) - - -class AxisResolveMap(VegaLiteSchema): - """AxisResolveMap schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - x : :class:`ResolveMode` - - y : :class:`ResolveMode` - - """ - _schema = {'$ref': '#/definitions/AxisResolveMap'} - - def __init__(self, x=Undefined, y=Undefined, **kwds): - super(AxisResolveMap, self).__init__(x=x, y=y, **kwds) - - -class BBox(VegaLiteSchema): - """BBox schema wrapper - - anyOf(List(float), List(float)) - Bounding box https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/BBox'} - - def __init__(self, *args, **kwds): - super(BBox, self).__init__(*args, **kwds) - - -class BarConfig(AnyMarkConfig): - """BarConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : anyOf(:class:`Align`, :class:`ExprRef`) - The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). - One of ``"left"``, ``"right"``, ``"center"``. - - **Note:** Expression reference is *not* supported for range marks. - angle : anyOf(float, :class:`ExprRef`) - The rotation angle of the text, in degrees. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG element, removing the mark item from the ARIA accessibility tree. - ariaRole : anyOf(string, :class:`ExprRef`) - Sets the type of user interface element of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "role" attribute. Warning: this - property is experimental and may be changed in the future. - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - A human-readable, author-localized description for the role of the mark item for - `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "aria-roledescription" attribute. - Warning: this property is experimental and may be changed in the future. - aspect : anyOf(boolean, :class:`ExprRef`) - Whether to keep aspect ratio of image marks. - baseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an - expression reference that provides one of the valid values. The ``"line-top"`` and - ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are - calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. - - For range marks, the vertical alignment of the marks. One of ``"top"``, - ``"middle"``, ``"bottom"``. - - **Note:** Expression reference is *not* supported for range marks. - binSpacing : float - Offset between bars for binned field. The ideal value for this is either 0 - (preferred by statisticians) or 1 (Vega-Lite default, D3 example style). - - **Default value:** ``1`` - blend : anyOf(:class:`Blend`, :class:`ExprRef`) - The color blend mode for drawing an item on its current background. Any valid `CSS - mix-blend-mode `__ - value can be used. - - __Default value:__ ``"source-over"`` - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - continuousBandSize : float - The default size of the bars on continuous scales. - - **Default value:** ``5`` - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom left corner. - - **Default value:** ``0`` - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom right corner. - - **Default value:** ``0`` - cornerRadiusEnd : anyOf(float, :class:`ExprRef`) - For vertical bars, top-left and top-right corner radius. - - For horizontal bars, top-right and bottom-right corner radius. - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top right corner. - - **Default value:** ``0`` - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top left corner. - - **Default value:** ``0`` - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - The mouse cursor used over the mark. Any valid `CSS cursor type - `__ can be used. - description : anyOf(string, :class:`ExprRef`) - A text description of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the `"aria-label" attribute - `__. - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` - (right-to-left). This property determines on which side is truncated in response to - the limit parameter. - - **Default value:** ``"ltr"`` - discreteBandSize : anyOf(float, :class:`RelativeBandSize`) - The default size of the bars with discrete dimensions. If unspecified, the default - size is ``step-2``, which provides 2 pixel offset between bars. - dx : anyOf(float, :class:`ExprRef`) - The horizontal offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - dy : anyOf(float, :class:`ExprRef`) - The vertical offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - ellipsis : anyOf(string, :class:`ExprRef`) - The ellipsis string for text truncated in response to the limit parameter. - - **Default value:** ``"…"`` - endAngle : anyOf(float, :class:`ExprRef`) - The end angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - filled : boolean - Whether the mark's color should be used as fill color instead of stroke color. - - **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well - as ``geoshape`` marks for `graticule - `__ data sources; - otherwise, ``true``. - - **Note:** This property cannot be used in a `style config - `__. - font : anyOf(string, :class:`ExprRef`) - The typeface to set the text in (e.g., ``"Helvetica Neue"`` ). - fontSize : anyOf(float, :class:`ExprRef`) - The font size, in pixels. - - **Default value:** ``11`` - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style (e.g., ``"italic"`` ). - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight. This can be either a string (e.g ``"bold"``, ``"normal"`` ) or a - number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and - ``"bold"`` = ``700`` ). - height : anyOf(float, :class:`ExprRef`) - Height of the marks. - href : anyOf(:class:`URI`, :class:`ExprRef`) - A URL to load upon mouse click. If defined, the mark acts as a hyperlink. - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - - **Default value:** ``0`` - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - The line interpolation method to use for line and area marks. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : alternate between horizontal and vertical segments, as in a step - function. - * ``"step-before"`` : alternate between vertical and horizontal segments, as in a - step function. - * ``"step-after"`` : alternate between horizontal and vertical segments, as in a - step function. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - limit : anyOf(float, :class:`ExprRef`) - The maximum length of the text mark in pixels. The text value will be automatically - truncated if the rendered size exceeds the limit. - - **Default value:** ``0`` -- indicating no limit - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property is ignored if the text is array-valued. - lineHeight : anyOf(float, :class:`ExprRef`) - The line height in pixels (the spacing between subsequent lines of text) for - multi-line text marks. - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - order : anyOf(None, boolean) - For line and trail marks, this ``order`` property can be set to ``null`` or - ``false`` to make the lines use the original order in the data sources. - orient : :class:`Orientation` - The orientation of a non-stacked bar, tick, area, and line charts. The value is - either horizontal (default) or vertical. - - - * For bar, rule and tick, this determines whether the size of the bar and tick - should be applied to x or y dimension. - * For area, this property determines the orient property of the Vega output. - * For line and trail marks, this property determines the sort order of the points in - the line if ``config.sortLineBy`` is not specified. For stacked charts, this is - always determined by the orientation of the stack; therefore explicitly specified - value will be ignored. - outerRadius : anyOf(float, :class:`ExprRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - - **Default value:** ``0`` - padAngle : anyOf(float, :class:`ExprRef`) - The angular padding applied to sides of the arc, in radians. - radius : anyOf(float, :class:`ExprRef`) - For arc mark, the primary (outer) radius in pixels. - - For text marks, polar coordinate radial offset, in pixels, of the text from the - origin determined by the ``x`` and ``y`` properties. - - **Default value:** ``min(plot_width, plot_height)/2`` - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - - **Default value:** ``0`` - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - Shape of the point marks. Supported values include: - - - * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, - ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or - ``"triangle-left"``. - * the line symbol ``"stroke"`` - * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - * a custom `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - **Default value:** ``"circle"`` - size : anyOf(float, :class:`ExprRef`) - Default size for marks. - - - * For ``point`` / ``circle`` / ``square``, this represents the pixel area of the - marks. Note that this value sets the area of the symbol; the side lengths will - increase with the square root of this value. - * For ``bar``, this represents the band size of the bar, in pixels. - * For ``text``, this represents the font size, in pixels. - - **Default value:** - - - * ``30`` for point, circle, square marks; width/height's ``step`` - * ``2`` for bar marks with discrete dimensions; - * ``5`` for bar marks with continuous dimensions; - * ``11`` for text marks. - smooth : anyOf(boolean, :class:`ExprRef`) - A boolean flag (default true) indicating if the image should be smoothed when - resized. If false, individual pixels should be scaled directly rather than - interpolated with smoothing. For SVG rendering, this option may not work in some - browsers due to lack of standardization. - startAngle : anyOf(float, :class:`ExprRef`) - The start angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default stroke color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove stroke. - - **Default value:** (None) - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOffset : anyOf(float, :class:`ExprRef`) - The offset in pixels at which to draw the group stroke and fill. If unspecified, the - default behavior is to dynamically offset stroked groups such that 1 pixel stroke - widths align with the pixel grid. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - tension : anyOf(float, :class:`ExprRef`) - Depending on the interpolation type, sets the tension parameter (for line and area - marks). - text : anyOf(:class:`Text`, :class:`ExprRef`) - Placeholder text if the ``text`` channel is not specified - theta : anyOf(float, :class:`ExprRef`) - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : anyOf(float, :class:`ExprRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - timeUnitBandPosition : float - Default relative band position for a time unit. If set to ``0``, the marks will be - positioned at the beginning of the time unit band step. If set to ``0.5``, the marks - will be positioned in the middle of the time unit band step. - timeUnitBandSize : float - Default relative band size for a time unit. If set to ``1``, the bandwidth of the - marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the - marks will be half of the time unit band step. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprRef`, None) - The tooltip text string to show upon mouse hover or an object defining which fields - should the tooltip be derived from. - - - * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from - ``encoding`` will be used. - * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the - highlighted data point will be used. - * If set to ``null`` or ``false``, then no tooltip will be used. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - - **Default value:** ``null`` - url : anyOf(:class:`URI`, :class:`ExprRef`) - The URL of the image file for image marks. - width : anyOf(float, :class:`ExprRef`) - Width of the marks. - x : anyOf(float, string, :class:`ExprRef`) - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : anyOf(float, string, :class:`ExprRef`) - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - y : anyOf(float, string, :class:`ExprRef`) - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : anyOf(float, string, :class:`ExprRef`) - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - """ - _schema = {'$ref': '#/definitions/BarConfig'} - - def __init__(self, align=Undefined, angle=Undefined, aria=Undefined, ariaRole=Undefined, - ariaRoleDescription=Undefined, aspect=Undefined, baseline=Undefined, - binSpacing=Undefined, blend=Undefined, color=Undefined, continuousBandSize=Undefined, - cornerRadius=Undefined, cornerRadiusBottomLeft=Undefined, - cornerRadiusBottomRight=Undefined, cornerRadiusEnd=Undefined, - cornerRadiusTopLeft=Undefined, cornerRadiusTopRight=Undefined, cursor=Undefined, - description=Undefined, dir=Undefined, discreteBandSize=Undefined, dx=Undefined, - dy=Undefined, ellipsis=Undefined, endAngle=Undefined, fill=Undefined, - fillOpacity=Undefined, filled=Undefined, font=Undefined, fontSize=Undefined, - fontStyle=Undefined, fontWeight=Undefined, height=Undefined, href=Undefined, - innerRadius=Undefined, interpolate=Undefined, invalid=Undefined, limit=Undefined, - lineBreak=Undefined, lineHeight=Undefined, opacity=Undefined, order=Undefined, - orient=Undefined, outerRadius=Undefined, padAngle=Undefined, radius=Undefined, - radius2=Undefined, shape=Undefined, size=Undefined, smooth=Undefined, - startAngle=Undefined, stroke=Undefined, strokeCap=Undefined, strokeDash=Undefined, - strokeDashOffset=Undefined, strokeJoin=Undefined, strokeMiterLimit=Undefined, - strokeOffset=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, - tension=Undefined, text=Undefined, theta=Undefined, theta2=Undefined, - timeUnitBandPosition=Undefined, timeUnitBandSize=Undefined, tooltip=Undefined, - url=Undefined, width=Undefined, x=Undefined, x2=Undefined, y=Undefined, y2=Undefined, - **kwds): - super(BarConfig, self).__init__(align=align, angle=angle, aria=aria, ariaRole=ariaRole, - ariaRoleDescription=ariaRoleDescription, aspect=aspect, - baseline=baseline, binSpacing=binSpacing, blend=blend, - color=color, continuousBandSize=continuousBandSize, - cornerRadius=cornerRadius, - cornerRadiusBottomLeft=cornerRadiusBottomLeft, - cornerRadiusBottomRight=cornerRadiusBottomRight, - cornerRadiusEnd=cornerRadiusEnd, - cornerRadiusTopLeft=cornerRadiusTopLeft, - cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, - description=description, dir=dir, - discreteBandSize=discreteBandSize, dx=dx, dy=dy, - ellipsis=ellipsis, endAngle=endAngle, fill=fill, - fillOpacity=fillOpacity, filled=filled, font=font, - fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, - height=height, href=href, innerRadius=innerRadius, - interpolate=interpolate, invalid=invalid, limit=limit, - lineBreak=lineBreak, lineHeight=lineHeight, opacity=opacity, - order=order, orient=orient, outerRadius=outerRadius, - padAngle=padAngle, radius=radius, radius2=radius2, shape=shape, - size=size, smooth=smooth, startAngle=startAngle, stroke=stroke, - strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, strokeOffset=strokeOffset, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - tension=tension, text=text, theta=theta, theta2=theta2, - timeUnitBandPosition=timeUnitBandPosition, - timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, url=url, - width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class BaseTitleNoValueRefs(VegaLiteSchema): - """BaseTitleNoValueRefs schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : :class:`Align` - Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or - ``"right"``. - anchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - The anchor position for placing the title and subtitle text. One of ``"start"``, - ``"middle"``, or ``"end"``. For example, with an orientation of top these anchor - positions map to a left-, center-, or right-aligned title. - angle : anyOf(float, :class:`ExprRef`) - Angle in degrees of title and subtitle text. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG group, removing the title from the ARIA accessibility tree. - - **Default value:** ``true`` - baseline : :class:`TextBaseline` - Vertical text baseline for title and subtitle text. One of ``"alphabetic"`` - (default), ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or - ``"line-bottom"``. The ``"line-top"`` and ``"line-bottom"`` values operate similarly - to ``"top"`` and ``"bottom"``, but are calculated relative to the *lineHeight* - rather than *fontSize* alone. - color : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Text color for title text. - dx : anyOf(float, :class:`ExprRef`) - Delta offset for title and subtitle text x-coordinate. - dy : anyOf(float, :class:`ExprRef`) - Delta offset for title and subtitle text y-coordinate. - font : anyOf(string, :class:`ExprRef`) - Font name for title text. - fontSize : anyOf(float, :class:`ExprRef`) - Font size in pixels for title text. - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - Font style for title text. - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight for title text. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - frame : anyOf(anyOf(:class:`TitleFrame`, string), :class:`ExprRef`) - The reference frame for the anchor position, one of ``"bounds"`` (to anchor relative - to the full bounding box) or ``"group"`` (to anchor relative to the group width or - height). - limit : anyOf(float, :class:`ExprRef`) - The maximum allowed length in pixels of title and subtitle text. - lineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line title text or title text with ``"line-top"`` or - ``"line-bottom"`` baseline. - offset : anyOf(float, :class:`ExprRef`) - The orthogonal offset in pixels by which to displace the title group from its - position along the edge of the chart. - orient : anyOf(:class:`TitleOrient`, :class:`ExprRef`) - Default title orientation ( ``"top"``, ``"bottom"``, ``"left"``, or ``"right"`` ) - subtitleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Text color for subtitle text. - subtitleFont : anyOf(string, :class:`ExprRef`) - Font name for subtitle text. - subtitleFontSize : anyOf(float, :class:`ExprRef`) - Font size in pixels for subtitle text. - subtitleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - Font style for subtitle text. - subtitleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight for subtitle text. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - subtitleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line subtitle text. - subtitlePadding : anyOf(float, :class:`ExprRef`) - The padding in pixels between title and subtitle text. - zindex : anyOf(float, :class:`ExprRef`) - The integer z-index indicating the layering of the title group relative to other - axis, mark, and legend groups. - - **Default value:** ``0``. - """ - _schema = {'$ref': '#/definitions/BaseTitleNoValueRefs'} - - def __init__(self, align=Undefined, anchor=Undefined, angle=Undefined, aria=Undefined, - baseline=Undefined, color=Undefined, dx=Undefined, dy=Undefined, font=Undefined, - fontSize=Undefined, fontStyle=Undefined, fontWeight=Undefined, frame=Undefined, - limit=Undefined, lineHeight=Undefined, offset=Undefined, orient=Undefined, - subtitleColor=Undefined, subtitleFont=Undefined, subtitleFontSize=Undefined, - subtitleFontStyle=Undefined, subtitleFontWeight=Undefined, - subtitleLineHeight=Undefined, subtitlePadding=Undefined, zindex=Undefined, **kwds): - super(BaseTitleNoValueRefs, self).__init__(align=align, anchor=anchor, angle=angle, aria=aria, - baseline=baseline, color=color, dx=dx, dy=dy, - font=font, fontSize=fontSize, fontStyle=fontStyle, - fontWeight=fontWeight, frame=frame, limit=limit, - lineHeight=lineHeight, offset=offset, orient=orient, - subtitleColor=subtitleColor, - subtitleFont=subtitleFont, - subtitleFontSize=subtitleFontSize, - subtitleFontStyle=subtitleFontStyle, - subtitleFontWeight=subtitleFontWeight, - subtitleLineHeight=subtitleLineHeight, - subtitlePadding=subtitlePadding, zindex=zindex, - **kwds) - - -class BinExtent(VegaLiteSchema): - """BinExtent schema wrapper - - anyOf(List(float), :class:`ParameterExtent`) - """ - _schema = {'$ref': '#/definitions/BinExtent'} - - def __init__(self, *args, **kwds): - super(BinExtent, self).__init__(*args, **kwds) - - -class BinParams(VegaLiteSchema): - """BinParams schema wrapper - - Mapping(required=[]) - Binning properties or boolean flag for determining whether to bin data or not. - - Parameters - ---------- - - anchor : float - A value in the binned domain at which to anchor the bins, shifting the bin - boundaries if necessary to ensure that a boundary aligns with the anchor value. - - **Default value:** the minimum bin extent value - base : float - The number base to use for automatic bin determination (default is base 10). - - **Default value:** ``10`` - binned : boolean - When set to ``true``, Vega-Lite treats the input data as already binned. - divide : List(float) - Scale factors indicating allowable subdivisions. The default value is [5, 2], which - indicates that for base 10 numbers (the default base), the method may consider - dividing bin sizes by 5 and/or 2. For example, for an initial step size of 10, the - method can check if bin sizes of 2 (= 10/5), 5 (= 10/2), or 1 (= 10/(5*2)) might - also satisfy the given constraints. - - **Default value:** ``[5, 2]`` - extent : :class:`BinExtent` - A two-element ( ``[min, max]`` ) array indicating the range of desired bin values. - maxbins : float - Maximum number of bins. - - **Default value:** ``6`` for ``row``, ``column`` and ``shape`` channels; ``10`` for - other channels - minstep : float - A minimum allowable step size (particularly useful for integer values). - nice : boolean - If true, attempts to make the bin boundaries use human-friendly boundaries, such as - multiples of ten. - - **Default value:** ``true`` - step : float - An exact step size to use between bins. - - **Note:** If provided, options such as maxbins will be ignored. - steps : List(float) - An array of allowable step sizes to choose from. - """ - _schema = {'$ref': '#/definitions/BinParams'} - - def __init__(self, anchor=Undefined, base=Undefined, binned=Undefined, divide=Undefined, - extent=Undefined, maxbins=Undefined, minstep=Undefined, nice=Undefined, step=Undefined, - steps=Undefined, **kwds): - super(BinParams, self).__init__(anchor=anchor, base=base, binned=binned, divide=divide, - extent=extent, maxbins=maxbins, minstep=minstep, nice=nice, - step=step, steps=steps, **kwds) - - -class Binding(VegaLiteSchema): - """Binding schema wrapper - - anyOf(:class:`BindCheckbox`, :class:`BindRadioSelect`, :class:`BindRange`, - :class:`BindInput`, :class:`BindDirect`) - """ - _schema = {'$ref': '#/definitions/Binding'} - - def __init__(self, *args, **kwds): - super(Binding, self).__init__(*args, **kwds) - - -class BindCheckbox(Binding): - """BindCheckbox schema wrapper - - Mapping(required=[input]) - - Parameters - ---------- - - input : string - - debounce : float - If defined, delays event handling until the specified milliseconds have elapsed - since the last event was fired. - element : :class:`Element` - An optional CSS selector string indicating the parent element to which the input - element should be added. By default, all input elements are added within the parent - container of the Vega view. - name : string - By default, the signal name is used to label input elements. This ``name`` property - can be used instead to specify a custom label for the bound signal. - """ - _schema = {'$ref': '#/definitions/BindCheckbox'} - - def __init__(self, input=Undefined, debounce=Undefined, element=Undefined, name=Undefined, **kwds): - super(BindCheckbox, self).__init__(input=input, debounce=debounce, element=element, name=name, - **kwds) - - -class BindDirect(Binding): - """BindDirect schema wrapper - - Mapping(required=[element]) - - Parameters - ---------- - - element : anyOf(:class:`Element`, Mapping(required=[])) - An input element that exposes a *value* property and supports the `EventTarget - `__ interface, or a - CSS selector string to such an element. When the element updates and dispatches an - event, the *value* property will be used as the new, bound signal value. When the - signal updates independent of the element, the *value* property will be set to the - signal value and a new event will be dispatched on the element. - debounce : float - If defined, delays event handling until the specified milliseconds have elapsed - since the last event was fired. - event : string - The event (default ``"input"`` ) to listen for to track changes on the external - element. - """ - _schema = {'$ref': '#/definitions/BindDirect'} - - def __init__(self, element=Undefined, debounce=Undefined, event=Undefined, **kwds): - super(BindDirect, self).__init__(element=element, debounce=debounce, event=event, **kwds) - - -class BindInput(Binding): - """BindInput schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - autocomplete : string - A hint for form autofill. See the `HTML autocomplete attribute - `__ for - additional information. - debounce : float - If defined, delays event handling until the specified milliseconds have elapsed - since the last event was fired. - element : :class:`Element` - An optional CSS selector string indicating the parent element to which the input - element should be added. By default, all input elements are added within the parent - container of the Vega view. - input : string - The type of input element to use. The valid values are ``"checkbox"``, ``"radio"``, - ``"range"``, ``"select"``, and any other legal `HTML form input type - `__. - name : string - By default, the signal name is used to label input elements. This ``name`` property - can be used instead to specify a custom label for the bound signal. - placeholder : string - Text that appears in the form control when it has no value set. - """ - _schema = {'$ref': '#/definitions/BindInput'} - - def __init__(self, autocomplete=Undefined, debounce=Undefined, element=Undefined, input=Undefined, - name=Undefined, placeholder=Undefined, **kwds): - super(BindInput, self).__init__(autocomplete=autocomplete, debounce=debounce, element=element, - input=input, name=name, placeholder=placeholder, **kwds) - - -class BindRadioSelect(Binding): - """BindRadioSelect schema wrapper - - Mapping(required=[input, options]) - - Parameters - ---------- - - input : enum('radio', 'select') - - options : List(Any) - An array of options to select from. - debounce : float - If defined, delays event handling until the specified milliseconds have elapsed - since the last event was fired. - element : :class:`Element` - An optional CSS selector string indicating the parent element to which the input - element should be added. By default, all input elements are added within the parent - container of the Vega view. - labels : List(string) - An array of label strings to represent the ``options`` values. If unspecified, the - ``options`` value will be coerced to a string and used as the label. - name : string - By default, the signal name is used to label input elements. This ``name`` property - can be used instead to specify a custom label for the bound signal. - """ - _schema = {'$ref': '#/definitions/BindRadioSelect'} - - def __init__(self, input=Undefined, options=Undefined, debounce=Undefined, element=Undefined, - labels=Undefined, name=Undefined, **kwds): - super(BindRadioSelect, self).__init__(input=input, options=options, debounce=debounce, - element=element, labels=labels, name=name, **kwds) - - -class BindRange(Binding): - """BindRange schema wrapper - - Mapping(required=[input]) - - Parameters - ---------- - - input : string - - debounce : float - If defined, delays event handling until the specified milliseconds have elapsed - since the last event was fired. - element : :class:`Element` - An optional CSS selector string indicating the parent element to which the input - element should be added. By default, all input elements are added within the parent - container of the Vega view. - max : float - Sets the maximum slider value. Defaults to the larger of the signal value and - ``100``. - min : float - Sets the minimum slider value. Defaults to the smaller of the signal value and - ``0``. - name : string - By default, the signal name is used to label input elements. This ``name`` property - can be used instead to specify a custom label for the bound signal. - step : float - Sets the minimum slider increment. If undefined, the step size will be automatically - determined based on the ``min`` and ``max`` values. - """ - _schema = {'$ref': '#/definitions/BindRange'} - - def __init__(self, input=Undefined, debounce=Undefined, element=Undefined, max=Undefined, - min=Undefined, name=Undefined, step=Undefined, **kwds): - super(BindRange, self).__init__(input=input, debounce=debounce, element=element, max=max, - min=min, name=name, step=step, **kwds) - - -class Blend(VegaLiteSchema): - """Blend schema wrapper - - enum(None, 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', - 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', - 'color', 'luminosity') - """ - _schema = {'$ref': '#/definitions/Blend'} - - def __init__(self, *args): - super(Blend, self).__init__(*args) - - -class BoxPlotConfig(VegaLiteSchema): - """BoxPlotConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - box : anyOf(boolean, :class:`AnyMarkConfig`) - - extent : anyOf(string, float) - The extent of the whiskers. Available options include: - - - * ``"min-max"`` : min and max are the lower and upper whiskers respectively. - * A number representing multiple of the interquartile range. This number will be - multiplied by the IQR to determine whisker boundary, which spans from the smallest - data to the largest data within the range *[Q1 - k * IQR, Q3 + k * IQR]* where - *Q1* and *Q3* are the first and third quartiles while *IQR* is the interquartile - range ( *Q3-Q1* ). - - **Default value:** ``1.5``. - median : anyOf(boolean, :class:`AnyMarkConfig`) - - outliers : anyOf(boolean, :class:`AnyMarkConfig`) - - rule : anyOf(boolean, :class:`AnyMarkConfig`) - - size : float - Size of the box and median tick of a box plot - ticks : anyOf(boolean, :class:`AnyMarkConfig`) - - """ - _schema = {'$ref': '#/definitions/BoxPlotConfig'} - - def __init__(self, box=Undefined, extent=Undefined, median=Undefined, outliers=Undefined, - rule=Undefined, size=Undefined, ticks=Undefined, **kwds): - super(BoxPlotConfig, self).__init__(box=box, extent=extent, median=median, outliers=outliers, - rule=rule, size=size, ticks=ticks, **kwds) - - -class BrushConfig(VegaLiteSchema): - """BrushConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - cursor : :class:`Cursor` - The mouse cursor used over the interval mark. Any valid `CSS cursor type - `__ can be used. - fill : :class:`Color` - The fill color of the interval mark. - - **Default value:** ``"#333333"`` - fillOpacity : float - The fill opacity of the interval mark (a value between ``0`` and ``1`` ). - - **Default value:** ``0.125`` - stroke : :class:`Color` - The stroke color of the interval mark. - - **Default value:** ``"#ffffff"`` - strokeDash : List(float) - An array of alternating stroke and space lengths, for creating dashed or dotted - lines. - strokeDashOffset : float - The offset (in pixels) with which to begin drawing the stroke dash array. - strokeOpacity : float - The stroke opacity of the interval mark (a value between ``0`` and ``1`` ). - strokeWidth : float - The stroke width of the interval mark. - """ - _schema = {'$ref': '#/definitions/BrushConfig'} - - def __init__(self, cursor=Undefined, fill=Undefined, fillOpacity=Undefined, stroke=Undefined, - strokeDash=Undefined, strokeDashOffset=Undefined, strokeOpacity=Undefined, - strokeWidth=Undefined, **kwds): - super(BrushConfig, self).__init__(cursor=cursor, fill=fill, fillOpacity=fillOpacity, - stroke=stroke, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, **kwds) - - -class Color(VegaLiteSchema): - """Color schema wrapper - - anyOf(:class:`ColorName`, :class:`HexColor`, string) - """ - _schema = {'$ref': '#/definitions/Color'} - - def __init__(self, *args, **kwds): - super(Color, self).__init__(*args, **kwds) - - -class ColorDef(VegaLiteSchema): - """ColorDef schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull`, - :class:`FieldOrDatumDefWithConditionDatumDefGradientstringnull`, - :class:`ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull`) - """ - _schema = {'$ref': '#/definitions/ColorDef'} - - def __init__(self, *args, **kwds): - super(ColorDef, self).__init__(*args, **kwds) - - -class ColorName(Color): - """ColorName schema wrapper - - enum('black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', - 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', - 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', - 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', - 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', - 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', - 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', - 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', - 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', - 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', - 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', - 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', - 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', - 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', - 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', - 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', - 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', - 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', - 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', - 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', - 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', - 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', - 'whitesmoke', 'yellowgreen', 'rebeccapurple') - """ - _schema = {'$ref': '#/definitions/ColorName'} - - def __init__(self, *args): - super(ColorName, self).__init__(*args) - - -class ColorScheme(VegaLiteSchema): - """ColorScheme schema wrapper - - anyOf(:class:`Categorical`, :class:`SequentialSingleHue`, :class:`SequentialMultiHue`, - :class:`Diverging`, :class:`Cyclical`) - """ - _schema = {'$ref': '#/definitions/ColorScheme'} - - def __init__(self, *args, **kwds): - super(ColorScheme, self).__init__(*args, **kwds) - - -class Categorical(ColorScheme): - """Categorical schema wrapper - - enum('accent', 'category10', 'category20', 'category20b', 'category20c', 'dark2', 'paired', - 'pastel1', 'pastel2', 'set1', 'set2', 'set3', 'tableau10', 'tableau20') - """ - _schema = {'$ref': '#/definitions/Categorical'} - - def __init__(self, *args): - super(Categorical, self).__init__(*args) - - -class CompositeMark(AnyMark): - """CompositeMark schema wrapper - - anyOf(:class:`BoxPlot`, :class:`ErrorBar`, :class:`ErrorBand`) - """ - _schema = {'$ref': '#/definitions/CompositeMark'} - - def __init__(self, *args, **kwds): - super(CompositeMark, self).__init__(*args, **kwds) - - -class BoxPlot(CompositeMark): - """BoxPlot schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/BoxPlot'} - - def __init__(self, *args): - super(BoxPlot, self).__init__(*args) - - -class CompositeMarkDef(AnyMark): - """CompositeMarkDef schema wrapper - - anyOf(:class:`BoxPlotDef`, :class:`ErrorBarDef`, :class:`ErrorBandDef`) - """ - _schema = {'$ref': '#/definitions/CompositeMarkDef'} - - def __init__(self, *args, **kwds): - super(CompositeMarkDef, self).__init__(*args, **kwds) - - -class BoxPlotDef(CompositeMarkDef): - """BoxPlotDef schema wrapper - - Mapping(required=[type]) - - Parameters - ---------- - - type : :class:`BoxPlot` - The mark type. This could a primitive mark type (one of ``"bar"``, ``"circle"``, - ``"square"``, ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"geoshape"``, - ``"rule"``, and ``"text"`` ) or a composite mark type ( ``"boxplot"``, - ``"errorband"``, ``"errorbar"`` ). - box : anyOf(boolean, :class:`AnyMarkConfig`) - - clip : boolean - Whether a composite mark be clipped to the enclosing group’s width and height. - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - extent : anyOf(string, float) - The extent of the whiskers. Available options include: - - - * ``"min-max"`` : min and max are the lower and upper whiskers respectively. - * A number representing multiple of the interquartile range. This number will be - multiplied by the IQR to determine whisker boundary, which spans from the smallest - data to the largest data within the range *[Q1 - k * IQR, Q3 + k * IQR]* where - *Q1* and *Q3* are the first and third quartiles while *IQR* is the interquartile - range ( *Q3-Q1* ). - - **Default value:** ``1.5``. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - median : anyOf(boolean, :class:`AnyMarkConfig`) - - opacity : float - The opacity (value between [0,1]) of the mark. - orient : :class:`Orientation` - Orientation of the box plot. This is normally automatically determined based on - types of fields on x and y channels. However, an explicit ``orient`` be specified - when the orientation is ambiguous. - - **Default value:** ``"vertical"``. - outliers : anyOf(boolean, :class:`AnyMarkConfig`) - - rule : anyOf(boolean, :class:`AnyMarkConfig`) - - size : float - Size of the box and median tick of a box plot - ticks : anyOf(boolean, :class:`AnyMarkConfig`) - - """ - _schema = {'$ref': '#/definitions/BoxPlotDef'} - - def __init__(self, type=Undefined, box=Undefined, clip=Undefined, color=Undefined, extent=Undefined, - invalid=Undefined, median=Undefined, opacity=Undefined, orient=Undefined, - outliers=Undefined, rule=Undefined, size=Undefined, ticks=Undefined, **kwds): - super(BoxPlotDef, self).__init__(type=type, box=box, clip=clip, color=color, extent=extent, - invalid=invalid, median=median, opacity=opacity, orient=orient, - outliers=outliers, rule=rule, size=size, ticks=ticks, **kwds) - - -class CompositionConfig(VegaLiteSchema): - """CompositionConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - columns : float - The number of columns to include in the view composition layout. - - **Default value** : ``undefined`` -- An infinite number of columns (a single row) - will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using - the ``column`` channel (for ``facet`` and ``repeat`` ). - - **Note** : - - 1) This property is only for: - - - * the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` ) - * the ``facet`` and ``repeat`` operator with one field/repetition definition - (without row/column nesting) - - 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` ) - and to using the ``row`` channel (for ``facet`` and ``repeat`` ). - spacing : float - The default spacing in pixels between composed sub-views. - - **Default value** : ``20`` - """ - _schema = {'$ref': '#/definitions/CompositionConfig'} - - def __init__(self, columns=Undefined, spacing=Undefined, **kwds): - super(CompositionConfig, self).__init__(columns=columns, spacing=spacing, **kwds) - - -class ConditionalAxisColor(VegaLiteSchema): - """ConditionalAxisColor schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisColor'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisColor, self).__init__(*args, **kwds) - - -class ConditionalAxisLabelAlign(VegaLiteSchema): - """ConditionalAxisLabelAlign schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisLabelAlign'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisLabelAlign, self).__init__(*args, **kwds) - - -class ConditionalAxisLabelBaseline(VegaLiteSchema): - """ConditionalAxisLabelBaseline schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisLabelBaseline'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisLabelBaseline, self).__init__(*args, **kwds) - - -class ConditionalAxisLabelFontStyle(VegaLiteSchema): - """ConditionalAxisLabelFontStyle schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisLabelFontStyle'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisLabelFontStyle, self).__init__(*args, **kwds) - - -class ConditionalAxisLabelFontWeight(VegaLiteSchema): - """ConditionalAxisLabelFontWeight schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisLabelFontWeight'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisLabelFontWeight, self).__init__(*args, **kwds) - - -class ConditionalAxisNumber(VegaLiteSchema): - """ConditionalAxisNumber schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisNumber'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisNumber, self).__init__(*args, **kwds) - - -class ConditionalAxisNumberArray(VegaLiteSchema): - """ConditionalAxisNumberArray schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisNumberArray'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisNumberArray, self).__init__(*args, **kwds) - - -class ConditionalAxisPropertyAlignnull(VegaLiteSchema): - """ConditionalAxisPropertyAlignnull schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisProperty<(Align|null)>'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisPropertyAlignnull, self).__init__(*args, **kwds) - - -class ConditionalAxisPropertyColornull(VegaLiteSchema): - """ConditionalAxisPropertyColornull schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisProperty<(Color|null)>'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisPropertyColornull, self).__init__(*args, **kwds) - - -class ConditionalAxisPropertyFontStylenull(VegaLiteSchema): - """ConditionalAxisPropertyFontStylenull schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisProperty<(FontStyle|null)>'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisPropertyFontStylenull, self).__init__(*args, **kwds) - - -class ConditionalAxisPropertyFontWeightnull(VegaLiteSchema): - """ConditionalAxisPropertyFontWeightnull schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisProperty<(FontWeight|null)>'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisPropertyFontWeightnull, self).__init__(*args, **kwds) - - -class ConditionalAxisPropertyTextBaselinenull(VegaLiteSchema): - """ConditionalAxisPropertyTextBaselinenull schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisProperty<(TextBaseline|null)>'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisPropertyTextBaselinenull, self).__init__(*args, **kwds) - - -class ConditionalAxisPropertynumberArraynull(VegaLiteSchema): - """ConditionalAxisPropertynumberArraynull schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisProperty<(number[]|null)>'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisPropertynumberArraynull, self).__init__(*args, **kwds) - - -class ConditionalAxisPropertynumbernull(VegaLiteSchema): - """ConditionalAxisPropertynumbernull schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisProperty<(number|null)>'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisPropertynumbernull, self).__init__(*args, **kwds) - - -class ConditionalAxisPropertystringnull(VegaLiteSchema): - """ConditionalAxisPropertystringnull schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisProperty<(string|null)>'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisPropertystringnull, self).__init__(*args, **kwds) - - -class ConditionalAxisString(VegaLiteSchema): - """ConditionalAxisString schema wrapper - - anyOf(Mapping(required=[condition, value]), Mapping(required=[condition, expr])) - """ - _schema = {'$ref': '#/definitions/ConditionalAxisString'} - - def __init__(self, *args, **kwds): - super(ConditionalAxisString, self).__init__(*args, **kwds) - - -class ConditionalMarkPropFieldOrDatumDef(VegaLiteSchema): - """ConditionalMarkPropFieldOrDatumDef schema wrapper - - anyOf(:class:`ConditionalPredicateMarkPropFieldOrDatumDef`, - :class:`ConditionalParameterMarkPropFieldOrDatumDef`) - """ - _schema = {'$ref': '#/definitions/ConditionalMarkPropFieldOrDatumDef'} - - def __init__(self, *args, **kwds): - super(ConditionalMarkPropFieldOrDatumDef, self).__init__(*args, **kwds) - - -class ConditionalMarkPropFieldOrDatumDefTypeForShape(VegaLiteSchema): - """ConditionalMarkPropFieldOrDatumDefTypeForShape schema wrapper - - anyOf(:class:`ConditionalPredicateMarkPropFieldOrDatumDefTypeForShape`, - :class:`ConditionalParameterMarkPropFieldOrDatumDefTypeForShape`) - """ - _schema = {'$ref': '#/definitions/ConditionalMarkPropFieldOrDatumDef'} - - def __init__(self, *args, **kwds): - super(ConditionalMarkPropFieldOrDatumDefTypeForShape, self).__init__(*args, **kwds) - - -class ConditionalParameterMarkPropFieldOrDatumDef(ConditionalMarkPropFieldOrDatumDef): - """ConditionalParameterMarkPropFieldOrDatumDef schema wrapper - - anyOf(Mapping(required=[param]), Mapping(required=[param])) - """ - _schema = {'$ref': '#/definitions/ConditionalParameter'} - - def __init__(self, *args, **kwds): - super(ConditionalParameterMarkPropFieldOrDatumDef, self).__init__(*args, **kwds) - - -class ConditionalParameterMarkPropFieldOrDatumDefTypeForShape(ConditionalMarkPropFieldOrDatumDefTypeForShape): - """ConditionalParameterMarkPropFieldOrDatumDefTypeForShape schema wrapper - - anyOf(Mapping(required=[param]), Mapping(required=[param])) - """ - _schema = {'$ref': '#/definitions/ConditionalParameter>'} - - def __init__(self, *args, **kwds): - super(ConditionalParameterMarkPropFieldOrDatumDefTypeForShape, self).__init__(*args, **kwds) - - -class ConditionalPredicateMarkPropFieldOrDatumDef(ConditionalMarkPropFieldOrDatumDef): - """ConditionalPredicateMarkPropFieldOrDatumDef schema wrapper - - anyOf(Mapping(required=[test]), Mapping(required=[test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateMarkPropFieldOrDatumDef, self).__init__(*args, **kwds) - - -class ConditionalPredicateMarkPropFieldOrDatumDefTypeForShape(ConditionalMarkPropFieldOrDatumDefTypeForShape): - """ConditionalPredicateMarkPropFieldOrDatumDefTypeForShape schema wrapper - - anyOf(Mapping(required=[test]), Mapping(required=[test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate>'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateMarkPropFieldOrDatumDefTypeForShape, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefAlignnullExprRef(VegaLiteSchema): - """ConditionalPredicateValueDefAlignnullExprRef schema wrapper - - anyOf(Mapping(required=[test, value]), Mapping(required=[expr, test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate<(ValueDef<(Align|null)>|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateValueDefAlignnullExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefColornullExprRef(VegaLiteSchema): - """ConditionalPredicateValueDefColornullExprRef schema wrapper - - anyOf(Mapping(required=[test, value]), Mapping(required=[expr, test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate<(ValueDef<(Color|null)>|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateValueDefColornullExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefFontStylenullExprRef(VegaLiteSchema): - """ConditionalPredicateValueDefFontStylenullExprRef schema wrapper - - anyOf(Mapping(required=[test, value]), Mapping(required=[expr, test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate<(ValueDef<(FontStyle|null)>|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateValueDefFontStylenullExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefFontWeightnullExprRef(VegaLiteSchema): - """ConditionalPredicateValueDefFontWeightnullExprRef schema wrapper - - anyOf(Mapping(required=[test, value]), Mapping(required=[expr, test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate<(ValueDef<(FontWeight|null)>|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateValueDefFontWeightnullExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefTextBaselinenullExprRef(VegaLiteSchema): - """ConditionalPredicateValueDefTextBaselinenullExprRef schema wrapper - - anyOf(Mapping(required=[test, value]), Mapping(required=[expr, test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate<(ValueDef<(TextBaseline|null)>|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateValueDefTextBaselinenullExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefnumberArraynullExprRef(VegaLiteSchema): - """ConditionalPredicateValueDefnumberArraynullExprRef schema wrapper - - anyOf(Mapping(required=[test, value]), Mapping(required=[expr, test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate<(ValueDef<(number[]|null)>|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateValueDefnumberArraynullExprRef, self).__init__(*args, **kwds) - - -class ConditionalPredicateValueDefnumbernullExprRef(VegaLiteSchema): - """ConditionalPredicateValueDefnumbernullExprRef schema wrapper - - anyOf(Mapping(required=[test, value]), Mapping(required=[expr, test])) - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate<(ValueDef<(number|null)>|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalPredicateValueDefnumbernullExprRef, self).__init__(*args, **kwds) - - -class ConditionalStringFieldDef(VegaLiteSchema): - """ConditionalStringFieldDef schema wrapper - - anyOf(:class:`ConditionalPredicateStringFieldDef`, - :class:`ConditionalParameterStringFieldDef`) - """ - _schema = {'$ref': '#/definitions/ConditionalStringFieldDef'} - - def __init__(self, *args, **kwds): - super(ConditionalStringFieldDef, self).__init__(*args, **kwds) - - -class ConditionalParameterStringFieldDef(ConditionalStringFieldDef): - """ConditionalParameterStringFieldDef schema wrapper - - Mapping(required=[param]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/ConditionalParameter'} - - def __init__(self, param=Undefined, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, - empty=Undefined, field=Undefined, format=Undefined, formatType=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(ConditionalParameterStringFieldDef, self).__init__(param=param, aggregate=aggregate, - bandPosition=bandPosition, bin=bin, - empty=empty, field=field, - format=format, formatType=formatType, - timeUnit=timeUnit, title=title, - type=type, **kwds) - - -class ConditionalPredicateStringFieldDef(ConditionalStringFieldDef): - """ConditionalPredicateStringFieldDef schema wrapper - - Mapping(required=[test]) - - Parameters - ---------- - - test : :class:`PredicateComposition` - Predicate for triggering the condition - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate'} - - def __init__(self, test=Undefined, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(ConditionalPredicateStringFieldDef, self).__init__(test=test, aggregate=aggregate, - bandPosition=bandPosition, bin=bin, - field=field, format=format, - formatType=formatType, - timeUnit=timeUnit, title=title, - type=type, **kwds) - - -class ConditionalValueDefGradientstringnullExprRef(VegaLiteSchema): - """ConditionalValueDefGradientstringnullExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefGradientstringnullExprRef`, - :class:`ConditionalParameterValueDefGradientstringnullExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(Gradient|string|null|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefGradientstringnullExprRef, self).__init__(*args, **kwds) - - -class ConditionalParameterValueDefGradientstringnullExprRef(ConditionalValueDefGradientstringnullExprRef): - """ConditionalParameterValueDefGradientstringnullExprRef schema wrapper - - Mapping(required=[param, value]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - value : anyOf(:class:`Gradient`, string, None, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - """ - _schema = {'$ref': '#/definitions/ConditionalParameter>'} - - def __init__(self, param=Undefined, value=Undefined, empty=Undefined, **kwds): - super(ConditionalParameterValueDefGradientstringnullExprRef, self).__init__(param=param, - value=value, - empty=empty, **kwds) - - -class ConditionalPredicateValueDefGradientstringnullExprRef(ConditionalValueDefGradientstringnullExprRef): - """ConditionalPredicateValueDefGradientstringnullExprRef schema wrapper - - Mapping(required=[test, value]) - - Parameters - ---------- - - test : :class:`PredicateComposition` - Predicate for triggering the condition - value : anyOf(:class:`Gradient`, string, None, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate>'} - - def __init__(self, test=Undefined, value=Undefined, **kwds): - super(ConditionalPredicateValueDefGradientstringnullExprRef, self).__init__(test=test, - value=value, **kwds) - - -class ConditionalValueDefTextExprRef(VegaLiteSchema): - """ConditionalValueDefTextExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefTextExprRef`, - :class:`ConditionalParameterValueDefTextExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(Text|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefTextExprRef, self).__init__(*args, **kwds) - - -class ConditionalParameterValueDefTextExprRef(ConditionalValueDefTextExprRef): - """ConditionalParameterValueDefTextExprRef schema wrapper - - Mapping(required=[param, value]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - value : anyOf(:class:`Text`, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - """ - _schema = {'$ref': '#/definitions/ConditionalParameter>'} - - def __init__(self, param=Undefined, value=Undefined, empty=Undefined, **kwds): - super(ConditionalParameterValueDefTextExprRef, self).__init__(param=param, value=value, - empty=empty, **kwds) - - -class ConditionalPredicateValueDefTextExprRef(ConditionalValueDefTextExprRef): - """ConditionalPredicateValueDefTextExprRef schema wrapper - - Mapping(required=[test, value]) - - Parameters - ---------- - - test : :class:`PredicateComposition` - Predicate for triggering the condition - value : anyOf(:class:`Text`, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate>'} - - def __init__(self, test=Undefined, value=Undefined, **kwds): - super(ConditionalPredicateValueDefTextExprRef, self).__init__(test=test, value=value, **kwds) - - -class ConditionalValueDefnumber(VegaLiteSchema): - """ConditionalValueDefnumber schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefnumber`, - :class:`ConditionalParameterValueDefnumber`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefnumber, self).__init__(*args, **kwds) - - -class ConditionalParameterValueDefnumber(ConditionalValueDefnumber): - """ConditionalParameterValueDefnumber schema wrapper - - Mapping(required=[param, value]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - value : float - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - """ - _schema = {'$ref': '#/definitions/ConditionalParameter>'} - - def __init__(self, param=Undefined, value=Undefined, empty=Undefined, **kwds): - super(ConditionalParameterValueDefnumber, self).__init__(param=param, value=value, empty=empty, - **kwds) - - -class ConditionalPredicateValueDefnumber(ConditionalValueDefnumber): - """ConditionalPredicateValueDefnumber schema wrapper - - Mapping(required=[test, value]) - - Parameters - ---------- - - test : :class:`PredicateComposition` - Predicate for triggering the condition - value : float - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate>'} - - def __init__(self, test=Undefined, value=Undefined, **kwds): - super(ConditionalPredicateValueDefnumber, self).__init__(test=test, value=value, **kwds) - - -class ConditionalValueDefnumberArrayExprRef(VegaLiteSchema): - """ConditionalValueDefnumberArrayExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefnumberArrayExprRef`, - :class:`ConditionalParameterValueDefnumberArrayExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(number[]|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefnumberArrayExprRef, self).__init__(*args, **kwds) - - -class ConditionalParameterValueDefnumberArrayExprRef(ConditionalValueDefnumberArrayExprRef): - """ConditionalParameterValueDefnumberArrayExprRef schema wrapper - - Mapping(required=[param, value]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - value : anyOf(List(float), :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - """ - _schema = {'$ref': '#/definitions/ConditionalParameter>'} - - def __init__(self, param=Undefined, value=Undefined, empty=Undefined, **kwds): - super(ConditionalParameterValueDefnumberArrayExprRef, self).__init__(param=param, value=value, - empty=empty, **kwds) - - -class ConditionalPredicateValueDefnumberArrayExprRef(ConditionalValueDefnumberArrayExprRef): - """ConditionalPredicateValueDefnumberArrayExprRef schema wrapper - - Mapping(required=[test, value]) - - Parameters - ---------- - - test : :class:`PredicateComposition` - Predicate for triggering the condition - value : anyOf(List(float), :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate>'} - - def __init__(self, test=Undefined, value=Undefined, **kwds): - super(ConditionalPredicateValueDefnumberArrayExprRef, self).__init__(test=test, value=value, - **kwds) - - -class ConditionalValueDefnumberExprRef(VegaLiteSchema): - """ConditionalValueDefnumberExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefnumberExprRef`, - :class:`ConditionalParameterValueDefnumberExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(number|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefnumberExprRef, self).__init__(*args, **kwds) - - -class ConditionalParameterValueDefnumberExprRef(ConditionalValueDefnumberExprRef): - """ConditionalParameterValueDefnumberExprRef schema wrapper - - Mapping(required=[param, value]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - value : anyOf(float, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - """ - _schema = {'$ref': '#/definitions/ConditionalParameter>'} - - def __init__(self, param=Undefined, value=Undefined, empty=Undefined, **kwds): - super(ConditionalParameterValueDefnumberExprRef, self).__init__(param=param, value=value, - empty=empty, **kwds) - - -class ConditionalPredicateValueDefnumberExprRef(ConditionalValueDefnumberExprRef): - """ConditionalPredicateValueDefnumberExprRef schema wrapper - - Mapping(required=[test, value]) - - Parameters - ---------- - - test : :class:`PredicateComposition` - Predicate for triggering the condition - value : anyOf(float, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate>'} - - def __init__(self, test=Undefined, value=Undefined, **kwds): - super(ConditionalPredicateValueDefnumberExprRef, self).__init__(test=test, value=value, **kwds) - - -class ConditionalValueDefstringExprRef(VegaLiteSchema): - """ConditionalValueDefstringExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefstringExprRef`, - :class:`ConditionalParameterValueDefstringExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(string|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefstringExprRef, self).__init__(*args, **kwds) - - -class ConditionalParameterValueDefstringExprRef(ConditionalValueDefstringExprRef): - """ConditionalParameterValueDefstringExprRef schema wrapper - - Mapping(required=[param, value]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - value : anyOf(string, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - """ - _schema = {'$ref': '#/definitions/ConditionalParameter>'} - - def __init__(self, param=Undefined, value=Undefined, empty=Undefined, **kwds): - super(ConditionalParameterValueDefstringExprRef, self).__init__(param=param, value=value, - empty=empty, **kwds) - - -class ConditionalPredicateValueDefstringExprRef(ConditionalValueDefstringExprRef): - """ConditionalPredicateValueDefstringExprRef schema wrapper - - Mapping(required=[test, value]) - - Parameters - ---------- - - test : :class:`PredicateComposition` - Predicate for triggering the condition - value : anyOf(string, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate>'} - - def __init__(self, test=Undefined, value=Undefined, **kwds): - super(ConditionalPredicateValueDefstringExprRef, self).__init__(test=test, value=value, **kwds) - - -class ConditionalValueDefstringnullExprRef(VegaLiteSchema): - """ConditionalValueDefstringnullExprRef schema wrapper - - anyOf(:class:`ConditionalPredicateValueDefstringnullExprRef`, - :class:`ConditionalParameterValueDefstringnullExprRef`) - """ - _schema = {'$ref': '#/definitions/ConditionalValueDef<(string|null|ExprRef)>'} - - def __init__(self, *args, **kwds): - super(ConditionalValueDefstringnullExprRef, self).__init__(*args, **kwds) - - -class ConditionalParameterValueDefstringnullExprRef(ConditionalValueDefstringnullExprRef): - """ConditionalParameterValueDefstringnullExprRef schema wrapper - - Mapping(required=[param, value]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - value : anyOf(string, None, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - """ - _schema = {'$ref': '#/definitions/ConditionalParameter>'} - - def __init__(self, param=Undefined, value=Undefined, empty=Undefined, **kwds): - super(ConditionalParameterValueDefstringnullExprRef, self).__init__(param=param, value=value, - empty=empty, **kwds) - - -class ConditionalPredicateValueDefstringnullExprRef(ConditionalValueDefstringnullExprRef): - """ConditionalPredicateValueDefstringnullExprRef schema wrapper - - Mapping(required=[test, value]) - - Parameters - ---------- - - test : :class:`PredicateComposition` - Predicate for triggering the condition - value : anyOf(string, None, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ConditionalPredicate>'} - - def __init__(self, test=Undefined, value=Undefined, **kwds): - super(ConditionalPredicateValueDefstringnullExprRef, self).__init__(test=test, value=value, - **kwds) - - -class Config(VegaLiteSchema): - """Config schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - arc : :class:`RectConfig` - Arc-specific Config - area : :class:`AreaConfig` - Area-Specific Config - aria : boolean - A boolean flag indicating if ARIA default attributes should be included for marks - and guides (SVG output only). If false, the ``"aria-hidden"`` attribute will be set - for all guides, removing them from the ARIA accessibility tree and Vega-Lite will - not generate default descriptions for marks. - - **Default value:** ``true``. - autosize : anyOf(:class:`AutosizeType`, :class:`AutoSizeParams`) - How the visualization size should be determined. If a string, should be one of - ``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify - parameters for content sizing and automatic resizing. - - **Default value** : ``pad`` - axis : :class:`AxisConfig` - Axis configuration, which determines default properties for all ``x`` and ``y`` - `axes `__. For a full list of axis - configuration options, please see the `corresponding section of the axis - documentation `__. - axisBand : :class:`AxisConfig` - Config for axes with "band" scales. - axisBottom : :class:`AxisConfig` - Config for x-axis along the bottom edge of the chart. - axisDiscrete : :class:`AxisConfig` - Config for axes with "point" or "band" scales. - axisLeft : :class:`AxisConfig` - Config for y-axis along the left edge of the chart. - axisPoint : :class:`AxisConfig` - Config for axes with "point" scales. - axisQuantitative : :class:`AxisConfig` - Config for quantitative axes. - axisRight : :class:`AxisConfig` - Config for y-axis along the right edge of the chart. - axisTemporal : :class:`AxisConfig` - Config for temporal axes. - axisTop : :class:`AxisConfig` - Config for x-axis along the top edge of the chart. - axisX : :class:`AxisConfig` - X-axis specific config. - axisXBand : :class:`AxisConfig` - Config for x-axes with "band" scales. - axisXDiscrete : :class:`AxisConfig` - Config for x-axes with "point" or "band" scales. - axisXPoint : :class:`AxisConfig` - Config for x-axes with "point" scales. - axisXQuantitative : :class:`AxisConfig` - Config for x-quantitative axes. - axisXTemporal : :class:`AxisConfig` - Config for x-temporal axes. - axisY : :class:`AxisConfig` - Y-axis specific config. - axisYBand : :class:`AxisConfig` - Config for y-axes with "band" scales. - axisYDiscrete : :class:`AxisConfig` - Config for y-axes with "point" or "band" scales. - axisYPoint : :class:`AxisConfig` - Config for y-axes with "point" scales. - axisYQuantitative : :class:`AxisConfig` - Config for y-quantitative axes. - axisYTemporal : :class:`AxisConfig` - Config for y-temporal axes. - background : anyOf(:class:`Color`, :class:`ExprRef`) - CSS color property to use as the background of the entire view. - - **Default value:** ``"white"`` - bar : :class:`BarConfig` - Bar-Specific Config - boxplot : :class:`BoxPlotConfig` - Box Config - circle : :class:`MarkConfig` - Circle-Specific Config - concat : :class:`CompositionConfig` - Default configuration for all concatenation and repeat view composition operators ( - ``concat``, ``hconcat``, ``vconcat``, and ``repeat`` ) - countTitle : string - Default axis and legend title for count fields. - - **Default value:** ``'Count of Records``. - customFormatTypes : boolean - Allow the ``formatType`` property for text marks and guides to accept a custom - formatter function `registered as a Vega expression - `__. - errorband : :class:`ErrorBandConfig` - ErrorBand Config - errorbar : :class:`ErrorBarConfig` - ErrorBar Config - facet : :class:`CompositionConfig` - Default configuration for the ``facet`` view composition operator - fieldTitle : enum('verbal', 'functional', 'plain') - Defines how Vega-Lite generates title for fields. There are three possible styles: - - - * ``"verbal"`` (Default) - displays function in a verbal style (e.g., "Sum of - field", "Year-month of date", "field (binned)"). - * ``"function"`` - displays function using parentheses and capitalized texts (e.g., - "SUM(field)", "YEARMONTH(date)", "BIN(field)"). - * ``"plain"`` - displays only the field name without functions (e.g., "field", - "date", "field"). - font : string - Default font for all text marks, titles, and labels. - geoshape : :class:`MarkConfig` - Geoshape-Specific Config - header : :class:`HeaderConfig` - Header configuration, which determines default properties for all `headers - `__. - - For a full list of header configuration options, please see the `corresponding - section of in the header documentation - `__. - headerColumn : :class:`HeaderConfig` - Header configuration, which determines default properties for column `headers - `__. - - For a full list of header configuration options, please see the `corresponding - section of in the header documentation - `__. - headerFacet : :class:`HeaderConfig` - Header configuration, which determines default properties for non-row/column facet - `headers `__. - - For a full list of header configuration options, please see the `corresponding - section of in the header documentation - `__. - headerRow : :class:`HeaderConfig` - Header configuration, which determines default properties for row `headers - `__. - - For a full list of header configuration options, please see the `corresponding - section of in the header documentation - `__. - image : :class:`RectConfig` - Image-specific Config - legend : :class:`LegendConfig` - Legend configuration, which determines default properties for all `legends - `__. For a full list of legend - configuration options, please see the `corresponding section of in the legend - documentation `__. - line : :class:`LineConfig` - Line-Specific Config - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property provides a global default for text marks, which is - overridden by mark or style config settings, and by the lineBreak mark encoding - channel. If signal-valued, either string or regular expression (regexp) values are - valid. - locale : :class:`Locale` - Locale definitions for string parsing and formatting of number and date values. The - locale object should contain ``number`` and/or ``time`` properties with `locale - definitions `__. Locale definitions - provided in the config block may be overridden by the View constructor locale - option. - mark : :class:`MarkConfig` - Mark Config - normalizedNumberFormat : string - If normalizedNumberFormatType is not specified, D3 number format for axis labels, - text marks, and tooltips of normalized stacked fields (fields with ``stack: - "normalize"`` ). For example ``"s"`` for SI units. Use `D3's number format pattern - `__. - - If ``config.normalizedNumberFormatType`` is specified and - ``config.customFormatTypes`` is ``true``, this value will be passed as ``format`` - alongside ``datum.value`` to the ``config.numberFormatType`` function. **Default - value:** ``%`` - normalizedNumberFormatType : string - `Custom format type - `__ for - ``config.normalizedNumberFormat``. - - **Default value:** ``undefined`` -- This is equilvalent to call D3-format, which is - exposed as `format in Vega-Expression - `__. **Note:** You must also - set ``customFormatTypes`` to ``true`` to use this feature. - numberFormat : string - If numberFormatType is not specified, D3 number format for guide labels, text marks, - and tooltips of non-normalized fields (fields *without* ``stack: "normalize"`` ). - For example ``"s"`` for SI units. Use `D3's number format pattern - `__. - - If ``config.numberFormatType`` is specified and ``config.customFormatTypes`` is - ``true``, this value will be passed as ``format`` alongside ``datum.value`` to the - ``config.numberFormatType`` function. - numberFormatType : string - `Custom format type - `__ for - ``config.numberFormat``. - - **Default value:** ``undefined`` -- This is equilvalent to call D3-format, which is - exposed as `format in Vega-Expression - `__. **Note:** You must also - set ``customFormatTypes`` to ``true`` to use this feature. - padding : anyOf(:class:`Padding`, :class:`ExprRef`) - The default visualization padding, in pixels, from the edge of the visualization - canvas to the data rectangle. If a number, specifies padding for all sides. If an - object, the value should have the format ``{"left": 5, "top": 5, "right": 5, - "bottom": 5}`` to specify padding for each side of the visualization. - - **Default value** : ``5`` - params : List(:class:`TopLevelParameter`) - Dynamic variables or selections that parameterize a visualization. - point : :class:`MarkConfig` - Point-Specific Config - projection : :class:`ProjectionConfig` - Projection configuration, which determines default properties for all `projections - `__. For a full list of - projection configuration options, please see the `corresponding section of the - projection documentation - `__. - range : :class:`RangeConfig` - An object hash that defines default range arrays or schemes for using with scales. - For a full list of scale range configuration options, please see the `corresponding - section of the scale documentation - `__. - rect : :class:`RectConfig` - Rect-Specific Config - rule : :class:`MarkConfig` - Rule-Specific Config - scale : :class:`ScaleConfig` - Scale configuration determines default properties for all `scales - `__. For a full list of scale - configuration options, please see the `corresponding section of the scale - documentation `__. - selection : :class:`SelectionConfig` - An object hash for defining default properties for each type of selections. - square : :class:`MarkConfig` - Square-Specific Config - style : :class:`StyleConfigIndex` - An object hash that defines key-value mappings to determine default properties for - marks with a given `style - `__. The keys represent - styles names; the values have to be valid `mark configuration objects - `__. - text : :class:`MarkConfig` - Text-Specific Config - tick : :class:`TickConfig` - Tick-Specific Config - timeFormat : string - Default time format for raw time values (without time units) in text marks, legend - labels and header labels. - - **Default value:** ``"%b %d, %Y"`` **Note:** Axes automatically determine the format - for each label automatically so this config does not affect axes. - timeFormatType : string - `Custom format type - `__ for - ``config.timeFormat``. - - **Default value:** ``undefined`` -- This is equilvalent to call D3-time-format, - which is exposed as `timeFormat in Vega-Expression - `__. **Note:** You must - also set ``customFormatTypes`` to ``true`` and there must *not* be a ``timeUnit`` - defined to use this feature. - title : :class:`TitleConfig` - Title configuration, which determines default properties for all `titles - `__. For a full list of title - configuration options, please see the `corresponding section of the title - documentation `__. - trail : :class:`LineConfig` - Trail-Specific Config - view : :class:`ViewConfig` - Default properties for `single view plots - `__. - """ - _schema = {'$ref': '#/definitions/Config'} - - def __init__(self, arc=Undefined, area=Undefined, aria=Undefined, autosize=Undefined, - axis=Undefined, axisBand=Undefined, axisBottom=Undefined, axisDiscrete=Undefined, - axisLeft=Undefined, axisPoint=Undefined, axisQuantitative=Undefined, - axisRight=Undefined, axisTemporal=Undefined, axisTop=Undefined, axisX=Undefined, - axisXBand=Undefined, axisXDiscrete=Undefined, axisXPoint=Undefined, - axisXQuantitative=Undefined, axisXTemporal=Undefined, axisY=Undefined, - axisYBand=Undefined, axisYDiscrete=Undefined, axisYPoint=Undefined, - axisYQuantitative=Undefined, axisYTemporal=Undefined, background=Undefined, - bar=Undefined, boxplot=Undefined, circle=Undefined, concat=Undefined, - countTitle=Undefined, customFormatTypes=Undefined, errorband=Undefined, - errorbar=Undefined, facet=Undefined, fieldTitle=Undefined, font=Undefined, - geoshape=Undefined, header=Undefined, headerColumn=Undefined, headerFacet=Undefined, - headerRow=Undefined, image=Undefined, legend=Undefined, line=Undefined, - lineBreak=Undefined, locale=Undefined, mark=Undefined, - normalizedNumberFormat=Undefined, normalizedNumberFormatType=Undefined, - numberFormat=Undefined, numberFormatType=Undefined, padding=Undefined, - params=Undefined, point=Undefined, projection=Undefined, range=Undefined, - rect=Undefined, rule=Undefined, scale=Undefined, selection=Undefined, square=Undefined, - style=Undefined, text=Undefined, tick=Undefined, timeFormat=Undefined, - timeFormatType=Undefined, title=Undefined, trail=Undefined, view=Undefined, **kwds): - super(Config, self).__init__(arc=arc, area=area, aria=aria, autosize=autosize, axis=axis, - axisBand=axisBand, axisBottom=axisBottom, - axisDiscrete=axisDiscrete, axisLeft=axisLeft, axisPoint=axisPoint, - axisQuantitative=axisQuantitative, axisRight=axisRight, - axisTemporal=axisTemporal, axisTop=axisTop, axisX=axisX, - axisXBand=axisXBand, axisXDiscrete=axisXDiscrete, - axisXPoint=axisXPoint, axisXQuantitative=axisXQuantitative, - axisXTemporal=axisXTemporal, axisY=axisY, axisYBand=axisYBand, - axisYDiscrete=axisYDiscrete, axisYPoint=axisYPoint, - axisYQuantitative=axisYQuantitative, axisYTemporal=axisYTemporal, - background=background, bar=bar, boxplot=boxplot, circle=circle, - concat=concat, countTitle=countTitle, - customFormatTypes=customFormatTypes, errorband=errorband, - errorbar=errorbar, facet=facet, fieldTitle=fieldTitle, font=font, - geoshape=geoshape, header=header, headerColumn=headerColumn, - headerFacet=headerFacet, headerRow=headerRow, image=image, - legend=legend, line=line, lineBreak=lineBreak, locale=locale, - mark=mark, normalizedNumberFormat=normalizedNumberFormat, - normalizedNumberFormatType=normalizedNumberFormatType, - numberFormat=numberFormat, numberFormatType=numberFormatType, - padding=padding, params=params, point=point, projection=projection, - range=range, rect=rect, rule=rule, scale=scale, - selection=selection, square=square, style=style, text=text, - tick=tick, timeFormat=timeFormat, timeFormatType=timeFormatType, - title=title, trail=trail, view=view, **kwds) - - -class Cursor(VegaLiteSchema): - """Cursor schema wrapper - - enum('auto', 'default', 'none', 'context-menu', 'help', 'pointer', 'progress', 'wait', - 'cell', 'crosshair', 'text', 'vertical-text', 'alias', 'copy', 'move', 'no-drop', - 'not-allowed', 'e-resize', 'n-resize', 'ne-resize', 'nw-resize', 's-resize', 'se-resize', - 'sw-resize', 'w-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', - 'col-resize', 'row-resize', 'all-scroll', 'zoom-in', 'zoom-out', 'grab', 'grabbing') - """ - _schema = {'$ref': '#/definitions/Cursor'} - - def __init__(self, *args): - super(Cursor, self).__init__(*args) - - -class Cyclical(ColorScheme): - """Cyclical schema wrapper - - enum('rainbow', 'sinebow') - """ - _schema = {'$ref': '#/definitions/Cyclical'} - - def __init__(self, *args): - super(Cyclical, self).__init__(*args) - - -class Data(VegaLiteSchema): - """Data schema wrapper - - anyOf(:class:`DataSource`, :class:`Generator`) - """ - _schema = {'$ref': '#/definitions/Data'} - - def __init__(self, *args, **kwds): - super(Data, self).__init__(*args, **kwds) - - -class DataFormat(VegaLiteSchema): - """DataFormat schema wrapper - - anyOf(:class:`CsvDataFormat`, :class:`DsvDataFormat`, :class:`JsonDataFormat`, - :class:`TopoDataFormat`) - """ - _schema = {'$ref': '#/definitions/DataFormat'} - - def __init__(self, *args, **kwds): - super(DataFormat, self).__init__(*args, **kwds) - - -class CsvDataFormat(DataFormat): - """CsvDataFormat schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - parse : anyOf(:class:`Parse`, None) - If set to ``null``, disable type inference based on the spec and only use type - inference based on the data. Alternatively, a parsing directive object can be - provided for explicit data types. Each property of the object corresponds to a field - name, and the value to the desired data type (one of ``"number"``, ``"boolean"``, - ``"date"``, or null (do not parse the field)). For example, ``"parse": - {"modified_on": "date"}`` parses the ``modified_on`` field in each input record a - Date value. - - For ``"date"``, we parse data based using JavaScript's `Date.parse() - `__. - For Specific date formats can be provided (e.g., ``{foo: "date:'%m%d%Y'"}`` ), using - the `d3-time-format syntax `__. - UTC date format parsing is supported similarly (e.g., ``{foo: "utc:'%m%d%Y'"}`` ). - See more about `UTC time - `__ - type : enum('csv', 'tsv') - Type of input data: ``"json"``, ``"csv"``, ``"tsv"``, ``"dsv"``. - - **Default value:** The default format type is determined by the extension of the - file URL. If no extension is detected, ``"json"`` will be used by default. - """ - _schema = {'$ref': '#/definitions/CsvDataFormat'} - - def __init__(self, parse=Undefined, type=Undefined, **kwds): - super(CsvDataFormat, self).__init__(parse=parse, type=type, **kwds) - - -class DataSource(Data): - """DataSource schema wrapper - - anyOf(:class:`UrlData`, :class:`InlineData`, :class:`NamedData`) - """ - _schema = {'$ref': '#/definitions/DataSource'} - - def __init__(self, *args, **kwds): - super(DataSource, self).__init__(*args, **kwds) - - -class Datasets(VegaLiteSchema): - """Datasets schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/Datasets'} - - def __init__(self, **kwds): - super(Datasets, self).__init__(**kwds) - - -class Day(VegaLiteSchema): - """Day schema wrapper - - float - """ - _schema = {'$ref': '#/definitions/Day'} - - def __init__(self, *args): - super(Day, self).__init__(*args) - - -class Dict(VegaLiteSchema): - """Dict schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/Dict'} - - def __init__(self, **kwds): - super(Dict, self).__init__(**kwds) - - -class DictInlineDataset(VegaLiteSchema): - """DictInlineDataset schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/Dict'} - - def __init__(self, **kwds): - super(DictInlineDataset, self).__init__(**kwds) - - -class DictSelectionInit(VegaLiteSchema): - """DictSelectionInit schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/Dict'} - - def __init__(self, **kwds): - super(DictSelectionInit, self).__init__(**kwds) - - -class DictSelectionInitInterval(VegaLiteSchema): - """DictSelectionInitInterval schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/Dict'} - - def __init__(self, **kwds): - super(DictSelectionInitInterval, self).__init__(**kwds) - - -class Diverging(ColorScheme): - """Diverging schema wrapper - - enum('blueorange', 'blueorange-3', 'blueorange-4', 'blueorange-5', 'blueorange-6', - 'blueorange-7', 'blueorange-8', 'blueorange-9', 'blueorange-10', 'blueorange-11', - 'brownbluegreen', 'brownbluegreen-3', 'brownbluegreen-4', 'brownbluegreen-5', - 'brownbluegreen-6', 'brownbluegreen-7', 'brownbluegreen-8', 'brownbluegreen-9', - 'brownbluegreen-10', 'brownbluegreen-11', 'purplegreen', 'purplegreen-3', 'purplegreen-4', - 'purplegreen-5', 'purplegreen-6', 'purplegreen-7', 'purplegreen-8', 'purplegreen-9', - 'purplegreen-10', 'purplegreen-11', 'pinkyellowgreen', 'pinkyellowgreen-3', - 'pinkyellowgreen-4', 'pinkyellowgreen-5', 'pinkyellowgreen-6', 'pinkyellowgreen-7', - 'pinkyellowgreen-8', 'pinkyellowgreen-9', 'pinkyellowgreen-10', 'pinkyellowgreen-11', - 'purpleorange', 'purpleorange-3', 'purpleorange-4', 'purpleorange-5', 'purpleorange-6', - 'purpleorange-7', 'purpleorange-8', 'purpleorange-9', 'purpleorange-10', 'purpleorange-11', - 'redblue', 'redblue-3', 'redblue-4', 'redblue-5', 'redblue-6', 'redblue-7', 'redblue-8', - 'redblue-9', 'redblue-10', 'redblue-11', 'redgrey', 'redgrey-3', 'redgrey-4', 'redgrey-5', - 'redgrey-6', 'redgrey-7', 'redgrey-8', 'redgrey-9', 'redgrey-10', 'redgrey-11', - 'redyellowblue', 'redyellowblue-3', 'redyellowblue-4', 'redyellowblue-5', 'redyellowblue-6', - 'redyellowblue-7', 'redyellowblue-8', 'redyellowblue-9', 'redyellowblue-10', - 'redyellowblue-11', 'redyellowgreen', 'redyellowgreen-3', 'redyellowgreen-4', - 'redyellowgreen-5', 'redyellowgreen-6', 'redyellowgreen-7', 'redyellowgreen-8', - 'redyellowgreen-9', 'redyellowgreen-10', 'redyellowgreen-11', 'spectral', 'spectral-3', - 'spectral-4', 'spectral-5', 'spectral-6', 'spectral-7', 'spectral-8', 'spectral-9', - 'spectral-10', 'spectral-11') - """ - _schema = {'$ref': '#/definitions/Diverging'} - - def __init__(self, *args): - super(Diverging, self).__init__(*args) - - -class DomainUnionWith(VegaLiteSchema): - """DomainUnionWith schema wrapper - - Mapping(required=[unionWith]) - - Parameters - ---------- - - unionWith : anyOf(List(float), List(string), List(boolean), List(:class:`DateTime`)) - Customized domain values to be union with the field's values or explicitly defined - domain. Should be an array of valid scale domain values. - """ - _schema = {'$ref': '#/definitions/DomainUnionWith'} - - def __init__(self, unionWith=Undefined, **kwds): - super(DomainUnionWith, self).__init__(unionWith=unionWith, **kwds) - - -class DsvDataFormat(DataFormat): - """DsvDataFormat schema wrapper - - Mapping(required=[delimiter]) - - Parameters - ---------- - - delimiter : string - The delimiter between records. The delimiter must be a single character (i.e., a - single 16-bit code unit); so, ASCII delimiters are fine, but emoji delimiters are - not. - parse : anyOf(:class:`Parse`, None) - If set to ``null``, disable type inference based on the spec and only use type - inference based on the data. Alternatively, a parsing directive object can be - provided for explicit data types. Each property of the object corresponds to a field - name, and the value to the desired data type (one of ``"number"``, ``"boolean"``, - ``"date"``, or null (do not parse the field)). For example, ``"parse": - {"modified_on": "date"}`` parses the ``modified_on`` field in each input record a - Date value. - - For ``"date"``, we parse data based using JavaScript's `Date.parse() - `__. - For Specific date formats can be provided (e.g., ``{foo: "date:'%m%d%Y'"}`` ), using - the `d3-time-format syntax `__. - UTC date format parsing is supported similarly (e.g., ``{foo: "utc:'%m%d%Y'"}`` ). - See more about `UTC time - `__ - type : string - Type of input data: ``"json"``, ``"csv"``, ``"tsv"``, ``"dsv"``. - - **Default value:** The default format type is determined by the extension of the - file URL. If no extension is detected, ``"json"`` will be used by default. - """ - _schema = {'$ref': '#/definitions/DsvDataFormat'} - - def __init__(self, delimiter=Undefined, parse=Undefined, type=Undefined, **kwds): - super(DsvDataFormat, self).__init__(delimiter=delimiter, parse=parse, type=type, **kwds) - - -class Element(VegaLiteSchema): - """Element schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/Element'} - - def __init__(self, *args): - super(Element, self).__init__(*args) - - -class Encoding(VegaLiteSchema): - """Encoding schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - angle : :class:`NumericMarkPropDef` - Rotation angle of point and text marks. - color : :class:`ColorDef` - Color of the marks – either fill or stroke color based on the ``filled`` property - of mark definition. By default, ``color`` represents fill color for ``"area"``, - ``"bar"``, ``"tick"``, ``"text"``, ``"trail"``, ``"circle"``, and ``"square"`` / - stroke color for ``"line"`` and ``"point"``. - - **Default value:** If undefined, the default color depends on `mark config - `__ 's ``color`` - property. - - *Note:* 1) For fine-grained control over both fill and stroke colors of the marks, - please use the ``fill`` and ``stroke`` channels. The ``fill`` or ``stroke`` - encodings have higher precedence than ``color``, thus may override the ``color`` - encoding if conflicting encodings are specified. 2) See the scale documentation for - more information about customizing `color scheme - `__. - description : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`) - A text description of this mark for ARIA accessibility (SVG output only). For SVG - output the ``"aria-label"`` attribute will be set to this description. - detail : anyOf(:class:`FieldDefWithoutScale`, List(:class:`FieldDefWithoutScale`)) - Additional levels of detail for grouping data in aggregate views and in line, trail, - and area marks without mapping data to a specific visual channel. - fill : :class:`ColorDef` - Fill color of the marks. **Default value:** If undefined, the default color depends - on `mark config `__ - 's ``color`` property. - - *Note:* The ``fill`` encoding has higher precedence than ``color``, thus may - override the ``color`` encoding if conflicting encodings are specified. - fillOpacity : :class:`NumericMarkPropDef` - Fill opacity of the marks. - - **Default value:** If undefined, the default opacity depends on `mark config - `__ 's - ``fillOpacity`` property. - href : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`) - A URL to load upon mouse click. - key : :class:`FieldDefWithoutScale` - A data field to use as a unique key for data binding. When a visualization’s data is - updated, the key value will be used to match data elements to existing mark - instances. Use a key channel to enable object constancy for transitions over dynamic - data. - latitude : :class:`LatLongDef` - Latitude position of geographically projected marks. - latitude2 : :class:`Position2Def` - Latitude-2 position for geographically projected ranged ``"area"``, ``"bar"``, - ``"rect"``, and ``"rule"``. - longitude : :class:`LatLongDef` - Longitude position of geographically projected marks. - longitude2 : :class:`Position2Def` - Longitude-2 position for geographically projected ranged ``"area"``, ``"bar"``, - ``"rect"``, and ``"rule"``. - opacity : :class:`NumericMarkPropDef` - Opacity of the marks. - - **Default value:** If undefined, the default opacity depends on `mark config - `__ 's ``opacity`` - property. - order : anyOf(:class:`OrderFieldDef`, List(:class:`OrderFieldDef`), :class:`OrderValueDef`) - Order of the marks. - - - * For stacked marks, this ``order`` channel encodes `stack order - `__. - * For line and trail marks, this ``order`` channel encodes order of data points in - the lines. This can be useful for creating `a connected scatterplot - `__. Setting - ``order`` to ``{"value": null}`` makes the line marks use the original order in - the data sources. - * Otherwise, this ``order`` channel encodes layer order of the marks. - - **Note** : In aggregate plots, ``order`` field should be ``aggregate`` d to avoid - creating additional aggregation grouping. - radius : :class:`PolarDef` - The outer radius in pixels of arc marks. - radius2 : :class:`Position2Def` - The inner radius in pixels of arc marks. - shape : :class:`ShapeDef` - Shape of the mark. - - - #. - For ``point`` marks the supported values include: - plotting shapes: ``"circle"``, - ``"square"``, ``"cross"``, ``"diamond"``, ``"triangle-up"``, ``"triangle-down"``, - ``"triangle-right"``, or ``"triangle-left"``. - the line symbol ``"stroke"`` - - centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - a custom - `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - #. - For ``geoshape`` marks it should be a field definition of the geojson data - - **Default value:** If undefined, the default shape depends on `mark config - `__ 's ``shape`` - property. ( ``"circle"`` if unset.) - size : :class:`NumericMarkPropDef` - Size of the mark. - - - * For ``"point"``, ``"square"`` and ``"circle"``, – the symbol size, or pixel area - of the mark. - * For ``"bar"`` and ``"tick"`` – the bar and tick's size. - * For ``"text"`` – the text's font size. - * Size is unsupported for ``"line"``, ``"area"``, and ``"rect"``. (Use ``"trail"`` - instead of line with varying size) - stroke : :class:`ColorDef` - Stroke color of the marks. **Default value:** If undefined, the default color - depends on `mark config - `__ 's ``color`` - property. - - *Note:* The ``stroke`` encoding has higher precedence than ``color``, thus may - override the ``color`` encoding if conflicting encodings are specified. - strokeDash : :class:`NumericArrayMarkPropDef` - Stroke dash of the marks. - - **Default value:** ``[1,0]`` (No dash). - strokeOpacity : :class:`NumericMarkPropDef` - Stroke opacity of the marks. - - **Default value:** If undefined, the default opacity depends on `mark config - `__ 's - ``strokeOpacity`` property. - strokeWidth : :class:`NumericMarkPropDef` - Stroke width of the marks. - - **Default value:** If undefined, the default stroke width depends on `mark config - `__ 's - ``strokeWidth`` property. - text : :class:`TextDef` - Text of the ``text`` mark. - theta : :class:`PolarDef` - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : :class:`Position2Def` - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - tooltip : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`, List(:class:`StringFieldDef`), None) - The tooltip text to show upon mouse hover. Specifying ``tooltip`` encoding overrides - `the tooltip property in the mark definition - `__. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - url : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`) - The URL of an image mark. - x : :class:`PositionDef` - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : :class:`Position2Def` - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - xError : anyOf(:class:`SecondaryFieldDef`, :class:`ValueDefnumber`) - Error value of x coordinates for error specified ``"errorbar"`` and ``"errorband"``. - xError2 : anyOf(:class:`SecondaryFieldDef`, :class:`ValueDefnumber`) - Secondary error value of x coordinates for error specified ``"errorbar"`` and - ``"errorband"``. - xOffset : :class:`OffsetDef` - Offset of x-position of the marks - y : :class:`PositionDef` - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : :class:`Position2Def` - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - yError : anyOf(:class:`SecondaryFieldDef`, :class:`ValueDefnumber`) - Error value of y coordinates for error specified ``"errorbar"`` and ``"errorband"``. - yError2 : anyOf(:class:`SecondaryFieldDef`, :class:`ValueDefnumber`) - Secondary error value of y coordinates for error specified ``"errorbar"`` and - ``"errorband"``. - yOffset : :class:`OffsetDef` - Offset of y-position of the marks - """ - _schema = {'$ref': '#/definitions/Encoding'} - - def __init__(self, angle=Undefined, color=Undefined, description=Undefined, detail=Undefined, - fill=Undefined, fillOpacity=Undefined, href=Undefined, key=Undefined, - latitude=Undefined, latitude2=Undefined, longitude=Undefined, longitude2=Undefined, - opacity=Undefined, order=Undefined, radius=Undefined, radius2=Undefined, - shape=Undefined, size=Undefined, stroke=Undefined, strokeDash=Undefined, - strokeOpacity=Undefined, strokeWidth=Undefined, text=Undefined, theta=Undefined, - theta2=Undefined, tooltip=Undefined, url=Undefined, x=Undefined, x2=Undefined, - xError=Undefined, xError2=Undefined, xOffset=Undefined, y=Undefined, y2=Undefined, - yError=Undefined, yError2=Undefined, yOffset=Undefined, **kwds): - super(Encoding, self).__init__(angle=angle, color=color, description=description, detail=detail, - fill=fill, fillOpacity=fillOpacity, href=href, key=key, - latitude=latitude, latitude2=latitude2, longitude=longitude, - longitude2=longitude2, opacity=opacity, order=order, - radius=radius, radius2=radius2, shape=shape, size=size, - stroke=stroke, strokeDash=strokeDash, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, text=text, - theta=theta, theta2=theta2, tooltip=tooltip, url=url, x=x, x2=x2, - xError=xError, xError2=xError2, xOffset=xOffset, y=y, y2=y2, - yError=yError, yError2=yError2, yOffset=yOffset, **kwds) - - -class ErrorBand(CompositeMark): - """ErrorBand schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/ErrorBand'} - - def __init__(self, *args): - super(ErrorBand, self).__init__(*args) - - -class ErrorBandConfig(VegaLiteSchema): - """ErrorBandConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - band : anyOf(boolean, :class:`AnyMarkConfig`) - - borders : anyOf(boolean, :class:`AnyMarkConfig`) - - extent : :class:`ErrorBarExtent` - The extent of the band. Available options include: - - - * ``"ci"`` : Extend the band to the confidence interval of the mean. - * ``"stderr"`` : The size of band are set to the value of standard error, extending - from the mean. - * ``"stdev"`` : The size of band are set to the value of standard deviation, - extending from the mean. - * ``"iqr"`` : Extend the band to the q1 and q3. - - **Default value:** ``"stderr"``. - interpolate : :class:`Interpolate` - The line interpolation method for the error band. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : a piecewise constant function (a step function) consisting of - alternating horizontal and vertical lines. The y-value changes at the midpoint of - each pair of adjacent x-values. - * ``"step-before"`` : a piecewise constant function (a step function) consisting of - alternating horizontal and vertical lines. The y-value changes before the x-value. - * ``"step-after"`` : a piecewise constant function (a step function) consisting of - alternating horizontal and vertical lines. The y-value changes after the x-value. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - tension : float - The tension parameter for the interpolation type of the error band. - """ - _schema = {'$ref': '#/definitions/ErrorBandConfig'} - - def __init__(self, band=Undefined, borders=Undefined, extent=Undefined, interpolate=Undefined, - tension=Undefined, **kwds): - super(ErrorBandConfig, self).__init__(band=band, borders=borders, extent=extent, - interpolate=interpolate, tension=tension, **kwds) - - -class ErrorBandDef(CompositeMarkDef): - """ErrorBandDef schema wrapper - - Mapping(required=[type]) - - Parameters - ---------- - - type : :class:`ErrorBand` - The mark type. This could a primitive mark type (one of ``"bar"``, ``"circle"``, - ``"square"``, ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"geoshape"``, - ``"rule"``, and ``"text"`` ) or a composite mark type ( ``"boxplot"``, - ``"errorband"``, ``"errorbar"`` ). - band : anyOf(boolean, :class:`AnyMarkConfig`) - - borders : anyOf(boolean, :class:`AnyMarkConfig`) - - clip : boolean - Whether a composite mark be clipped to the enclosing group’s width and height. - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - extent : :class:`ErrorBarExtent` - The extent of the band. Available options include: - - - * ``"ci"`` : Extend the band to the confidence interval of the mean. - * ``"stderr"`` : The size of band are set to the value of standard error, extending - from the mean. - * ``"stdev"`` : The size of band are set to the value of standard deviation, - extending from the mean. - * ``"iqr"`` : Extend the band to the q1 and q3. - - **Default value:** ``"stderr"``. - interpolate : :class:`Interpolate` - The line interpolation method for the error band. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : a piecewise constant function (a step function) consisting of - alternating horizontal and vertical lines. The y-value changes at the midpoint of - each pair of adjacent x-values. - * ``"step-before"`` : a piecewise constant function (a step function) consisting of - alternating horizontal and vertical lines. The y-value changes before the x-value. - * ``"step-after"`` : a piecewise constant function (a step function) consisting of - alternating horizontal and vertical lines. The y-value changes after the x-value. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - opacity : float - The opacity (value between [0,1]) of the mark. - orient : :class:`Orientation` - Orientation of the error band. This is normally automatically determined, but can be - specified when the orientation is ambiguous and cannot be automatically determined. - tension : float - The tension parameter for the interpolation type of the error band. - """ - _schema = {'$ref': '#/definitions/ErrorBandDef'} - - def __init__(self, type=Undefined, band=Undefined, borders=Undefined, clip=Undefined, - color=Undefined, extent=Undefined, interpolate=Undefined, opacity=Undefined, - orient=Undefined, tension=Undefined, **kwds): - super(ErrorBandDef, self).__init__(type=type, band=band, borders=borders, clip=clip, - color=color, extent=extent, interpolate=interpolate, - opacity=opacity, orient=orient, tension=tension, **kwds) - - -class ErrorBar(CompositeMark): - """ErrorBar schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/ErrorBar'} - - def __init__(self, *args): - super(ErrorBar, self).__init__(*args) - - -class ErrorBarConfig(VegaLiteSchema): - """ErrorBarConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - extent : :class:`ErrorBarExtent` - The extent of the rule. Available options include: - - - * ``"ci"`` : Extend the rule to the confidence interval of the mean. - * ``"stderr"`` : The size of rule are set to the value of standard error, extending - from the mean. - * ``"stdev"`` : The size of rule are set to the value of standard deviation, - extending from the mean. - * ``"iqr"`` : Extend the rule to the q1 and q3. - - **Default value:** ``"stderr"``. - rule : anyOf(boolean, :class:`AnyMarkConfig`) - - size : float - Size of the ticks of an error bar - thickness : float - Thickness of the ticks and the bar of an error bar - ticks : anyOf(boolean, :class:`AnyMarkConfig`) - - """ - _schema = {'$ref': '#/definitions/ErrorBarConfig'} - - def __init__(self, extent=Undefined, rule=Undefined, size=Undefined, thickness=Undefined, - ticks=Undefined, **kwds): - super(ErrorBarConfig, self).__init__(extent=extent, rule=rule, size=size, thickness=thickness, - ticks=ticks, **kwds) - - -class ErrorBarDef(CompositeMarkDef): - """ErrorBarDef schema wrapper - - Mapping(required=[type]) - - Parameters - ---------- - - type : :class:`ErrorBar` - The mark type. This could a primitive mark type (one of ``"bar"``, ``"circle"``, - ``"square"``, ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"geoshape"``, - ``"rule"``, and ``"text"`` ) or a composite mark type ( ``"boxplot"``, - ``"errorband"``, ``"errorbar"`` ). - clip : boolean - Whether a composite mark be clipped to the enclosing group’s width and height. - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - extent : :class:`ErrorBarExtent` - The extent of the rule. Available options include: - - - * ``"ci"`` : Extend the rule to the confidence interval of the mean. - * ``"stderr"`` : The size of rule are set to the value of standard error, extending - from the mean. - * ``"stdev"`` : The size of rule are set to the value of standard deviation, - extending from the mean. - * ``"iqr"`` : Extend the rule to the q1 and q3. - - **Default value:** ``"stderr"``. - opacity : float - The opacity (value between [0,1]) of the mark. - orient : :class:`Orientation` - Orientation of the error bar. This is normally automatically determined, but can be - specified when the orientation is ambiguous and cannot be automatically determined. - rule : anyOf(boolean, :class:`AnyMarkConfig`) - - size : float - Size of the ticks of an error bar - thickness : float - Thickness of the ticks and the bar of an error bar - ticks : anyOf(boolean, :class:`AnyMarkConfig`) - - """ - _schema = {'$ref': '#/definitions/ErrorBarDef'} - - def __init__(self, type=Undefined, clip=Undefined, color=Undefined, extent=Undefined, - opacity=Undefined, orient=Undefined, rule=Undefined, size=Undefined, - thickness=Undefined, ticks=Undefined, **kwds): - super(ErrorBarDef, self).__init__(type=type, clip=clip, color=color, extent=extent, - opacity=opacity, orient=orient, rule=rule, size=size, - thickness=thickness, ticks=ticks, **kwds) - - -class ErrorBarExtent(VegaLiteSchema): - """ErrorBarExtent schema wrapper - - enum('ci', 'iqr', 'stderr', 'stdev') - """ - _schema = {'$ref': '#/definitions/ErrorBarExtent'} - - def __init__(self, *args): - super(ErrorBarExtent, self).__init__(*args) - - -class Expr(VegaLiteSchema): - """Expr schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/Expr'} - - def __init__(self, *args): - super(Expr, self).__init__(*args) - - -class ExprRef(VegaLiteSchema): - """ExprRef schema wrapper - - Mapping(required=[expr]) - - Parameters - ---------- - - expr : string - Vega expression (which can refer to Vega-Lite parameters). - """ - _schema = {'$ref': '#/definitions/ExprRef'} - - def __init__(self, expr=Undefined, **kwds): - super(ExprRef, self).__init__(expr=expr, **kwds) - - -class FacetEncodingFieldDef(VegaLiteSchema): - """FacetEncodingFieldDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - columns : float - The number of columns to include in the view composition layout. - - **Default value** : ``undefined`` -- An infinite number of columns (a single row) - will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using - the ``column`` channel (for ``facet`` and ``repeat`` ). - - **Note** : - - 1) This property is only for: - - - * the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` ) - * the ``facet`` and ``repeat`` operator with one field/repetition definition - (without row/column nesting) - - 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` ) - and to using the ``row`` channel (for ``facet`` and ``repeat`` ). - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - header : anyOf(:class:`Header`, None) - An object defining properties of a facet's header. - sort : anyOf(:class:`SortArray`, :class:`SortOrder`, :class:`EncodingSortField`, None) - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` is not supported for ``row`` and ``column``. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FacetEncodingFieldDef'} - - def __init__(self, aggregate=Undefined, align=Undefined, bandPosition=Undefined, bin=Undefined, - bounds=Undefined, center=Undefined, columns=Undefined, field=Undefined, - header=Undefined, sort=Undefined, spacing=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(FacetEncodingFieldDef, self).__init__(aggregate=aggregate, align=align, - bandPosition=bandPosition, bin=bin, bounds=bounds, - center=center, columns=columns, field=field, - header=header, sort=sort, spacing=spacing, - timeUnit=timeUnit, title=title, type=type, **kwds) - - -class FacetFieldDef(VegaLiteSchema): - """FacetFieldDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - header : anyOf(:class:`Header`, None) - An object defining properties of a facet's header. - sort : anyOf(:class:`SortArray`, :class:`SortOrder`, :class:`EncodingSortField`, None) - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` is not supported for ``row`` and ``column``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FacetFieldDef'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - header=Undefined, sort=Undefined, timeUnit=Undefined, title=Undefined, type=Undefined, - **kwds): - super(FacetFieldDef, self).__init__(aggregate=aggregate, bandPosition=bandPosition, bin=bin, - field=field, header=header, sort=sort, timeUnit=timeUnit, - title=title, type=type, **kwds) - - -class FacetMapping(VegaLiteSchema): - """FacetMapping schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - column : :class:`FacetFieldDef` - A field definition for the horizontal facet of trellis plots. - row : :class:`FacetFieldDef` - A field definition for the vertical facet of trellis plots. - """ - _schema = {'$ref': '#/definitions/FacetMapping'} - - def __init__(self, column=Undefined, row=Undefined, **kwds): - super(FacetMapping, self).__init__(column=column, row=row, **kwds) - - -class FacetedEncoding(VegaLiteSchema): - """FacetedEncoding schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - angle : :class:`NumericMarkPropDef` - Rotation angle of point and text marks. - color : :class:`ColorDef` - Color of the marks – either fill or stroke color based on the ``filled`` property - of mark definition. By default, ``color`` represents fill color for ``"area"``, - ``"bar"``, ``"tick"``, ``"text"``, ``"trail"``, ``"circle"``, and ``"square"`` / - stroke color for ``"line"`` and ``"point"``. - - **Default value:** If undefined, the default color depends on `mark config - `__ 's ``color`` - property. - - *Note:* 1) For fine-grained control over both fill and stroke colors of the marks, - please use the ``fill`` and ``stroke`` channels. The ``fill`` or ``stroke`` - encodings have higher precedence than ``color``, thus may override the ``color`` - encoding if conflicting encodings are specified. 2) See the scale documentation for - more information about customizing `color scheme - `__. - column : :class:`RowColumnEncodingFieldDef` - A field definition for the horizontal facet of trellis plots. - description : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`) - A text description of this mark for ARIA accessibility (SVG output only). For SVG - output the ``"aria-label"`` attribute will be set to this description. - detail : anyOf(:class:`FieldDefWithoutScale`, List(:class:`FieldDefWithoutScale`)) - Additional levels of detail for grouping data in aggregate views and in line, trail, - and area marks without mapping data to a specific visual channel. - facet : :class:`FacetEncodingFieldDef` - A field definition for the (flexible) facet of trellis plots. - - If either ``row`` or ``column`` is specified, this channel will be ignored. - fill : :class:`ColorDef` - Fill color of the marks. **Default value:** If undefined, the default color depends - on `mark config `__ - 's ``color`` property. - - *Note:* The ``fill`` encoding has higher precedence than ``color``, thus may - override the ``color`` encoding if conflicting encodings are specified. - fillOpacity : :class:`NumericMarkPropDef` - Fill opacity of the marks. - - **Default value:** If undefined, the default opacity depends on `mark config - `__ 's - ``fillOpacity`` property. - href : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`) - A URL to load upon mouse click. - key : :class:`FieldDefWithoutScale` - A data field to use as a unique key for data binding. When a visualization’s data is - updated, the key value will be used to match data elements to existing mark - instances. Use a key channel to enable object constancy for transitions over dynamic - data. - latitude : :class:`LatLongDef` - Latitude position of geographically projected marks. - latitude2 : :class:`Position2Def` - Latitude-2 position for geographically projected ranged ``"area"``, ``"bar"``, - ``"rect"``, and ``"rule"``. - longitude : :class:`LatLongDef` - Longitude position of geographically projected marks. - longitude2 : :class:`Position2Def` - Longitude-2 position for geographically projected ranged ``"area"``, ``"bar"``, - ``"rect"``, and ``"rule"``. - opacity : :class:`NumericMarkPropDef` - Opacity of the marks. - - **Default value:** If undefined, the default opacity depends on `mark config - `__ 's ``opacity`` - property. - order : anyOf(:class:`OrderFieldDef`, List(:class:`OrderFieldDef`), :class:`OrderValueDef`) - Order of the marks. - - - * For stacked marks, this ``order`` channel encodes `stack order - `__. - * For line and trail marks, this ``order`` channel encodes order of data points in - the lines. This can be useful for creating `a connected scatterplot - `__. Setting - ``order`` to ``{"value": null}`` makes the line marks use the original order in - the data sources. - * Otherwise, this ``order`` channel encodes layer order of the marks. - - **Note** : In aggregate plots, ``order`` field should be ``aggregate`` d to avoid - creating additional aggregation grouping. - radius : :class:`PolarDef` - The outer radius in pixels of arc marks. - radius2 : :class:`Position2Def` - The inner radius in pixels of arc marks. - row : :class:`RowColumnEncodingFieldDef` - A field definition for the vertical facet of trellis plots. - shape : :class:`ShapeDef` - Shape of the mark. - - - #. - For ``point`` marks the supported values include: - plotting shapes: ``"circle"``, - ``"square"``, ``"cross"``, ``"diamond"``, ``"triangle-up"``, ``"triangle-down"``, - ``"triangle-right"``, or ``"triangle-left"``. - the line symbol ``"stroke"`` - - centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - a custom - `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - #. - For ``geoshape`` marks it should be a field definition of the geojson data - - **Default value:** If undefined, the default shape depends on `mark config - `__ 's ``shape`` - property. ( ``"circle"`` if unset.) - size : :class:`NumericMarkPropDef` - Size of the mark. - - - * For ``"point"``, ``"square"`` and ``"circle"``, – the symbol size, or pixel area - of the mark. - * For ``"bar"`` and ``"tick"`` – the bar and tick's size. - * For ``"text"`` – the text's font size. - * Size is unsupported for ``"line"``, ``"area"``, and ``"rect"``. (Use ``"trail"`` - instead of line with varying size) - stroke : :class:`ColorDef` - Stroke color of the marks. **Default value:** If undefined, the default color - depends on `mark config - `__ 's ``color`` - property. - - *Note:* The ``stroke`` encoding has higher precedence than ``color``, thus may - override the ``color`` encoding if conflicting encodings are specified. - strokeDash : :class:`NumericArrayMarkPropDef` - Stroke dash of the marks. - - **Default value:** ``[1,0]`` (No dash). - strokeOpacity : :class:`NumericMarkPropDef` - Stroke opacity of the marks. - - **Default value:** If undefined, the default opacity depends on `mark config - `__ 's - ``strokeOpacity`` property. - strokeWidth : :class:`NumericMarkPropDef` - Stroke width of the marks. - - **Default value:** If undefined, the default stroke width depends on `mark config - `__ 's - ``strokeWidth`` property. - text : :class:`TextDef` - Text of the ``text`` mark. - theta : :class:`PolarDef` - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : :class:`Position2Def` - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - tooltip : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`, List(:class:`StringFieldDef`), None) - The tooltip text to show upon mouse hover. Specifying ``tooltip`` encoding overrides - `the tooltip property in the mark definition - `__. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - url : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`) - The URL of an image mark. - x : :class:`PositionDef` - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : :class:`Position2Def` - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - xError : anyOf(:class:`SecondaryFieldDef`, :class:`ValueDefnumber`) - Error value of x coordinates for error specified ``"errorbar"`` and ``"errorband"``. - xError2 : anyOf(:class:`SecondaryFieldDef`, :class:`ValueDefnumber`) - Secondary error value of x coordinates for error specified ``"errorbar"`` and - ``"errorband"``. - xOffset : :class:`OffsetDef` - Offset of x-position of the marks - y : :class:`PositionDef` - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : :class:`Position2Def` - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - yError : anyOf(:class:`SecondaryFieldDef`, :class:`ValueDefnumber`) - Error value of y coordinates for error specified ``"errorbar"`` and ``"errorband"``. - yError2 : anyOf(:class:`SecondaryFieldDef`, :class:`ValueDefnumber`) - Secondary error value of y coordinates for error specified ``"errorbar"`` and - ``"errorband"``. - yOffset : :class:`OffsetDef` - Offset of y-position of the marks - """ - _schema = {'$ref': '#/definitions/FacetedEncoding'} - - def __init__(self, angle=Undefined, color=Undefined, column=Undefined, description=Undefined, - detail=Undefined, facet=Undefined, fill=Undefined, fillOpacity=Undefined, - href=Undefined, key=Undefined, latitude=Undefined, latitude2=Undefined, - longitude=Undefined, longitude2=Undefined, opacity=Undefined, order=Undefined, - radius=Undefined, radius2=Undefined, row=Undefined, shape=Undefined, size=Undefined, - stroke=Undefined, strokeDash=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, - text=Undefined, theta=Undefined, theta2=Undefined, tooltip=Undefined, url=Undefined, - x=Undefined, x2=Undefined, xError=Undefined, xError2=Undefined, xOffset=Undefined, - y=Undefined, y2=Undefined, yError=Undefined, yError2=Undefined, yOffset=Undefined, - **kwds): - super(FacetedEncoding, self).__init__(angle=angle, color=color, column=column, - description=description, detail=detail, facet=facet, - fill=fill, fillOpacity=fillOpacity, href=href, key=key, - latitude=latitude, latitude2=latitude2, - longitude=longitude, longitude2=longitude2, - opacity=opacity, order=order, radius=radius, - radius2=radius2, row=row, shape=shape, size=size, - stroke=stroke, strokeDash=strokeDash, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - text=text, theta=theta, theta2=theta2, tooltip=tooltip, - url=url, x=x, x2=x2, xError=xError, xError2=xError2, - xOffset=xOffset, y=y, y2=y2, yError=yError, - yError2=yError2, yOffset=yOffset, **kwds) - - -class Feature(VegaLiteSchema): - """Feature schema wrapper - - Mapping(required=[geometry, properties, type]) - A feature object which contains a geometry and associated properties. - https://tools.ietf.org/html/rfc7946#section-3.2 - - Parameters - ---------- - - geometry : :class:`Geometry` - The feature's geometry - properties : :class:`GeoJsonProperties` - Properties associated with this feature. - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - id : anyOf(string, float) - A value that uniquely identifies this feature in a - https://tools.ietf.org/html/rfc7946#section-3.2. - """ - _schema = {'$ref': '#/definitions/Feature'} - - def __init__(self, geometry=Undefined, properties=Undefined, type=Undefined, bbox=Undefined, - id=Undefined, **kwds): - super(Feature, self).__init__(geometry=geometry, properties=properties, type=type, bbox=bbox, - id=id, **kwds) - - -class FeatureCollection(VegaLiteSchema): - """FeatureCollection schema wrapper - - Mapping(required=[features, type]) - A collection of feature objects. https://tools.ietf.org/html/rfc7946#section-3.3 - - Parameters - ---------- - - features : List(:class:`FeatureGeometryGeoJsonProperties`) - - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/FeatureCollection'} - - def __init__(self, features=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(FeatureCollection, self).__init__(features=features, type=type, bbox=bbox, **kwds) - - -class FeatureGeometryGeoJsonProperties(VegaLiteSchema): - """FeatureGeometryGeoJsonProperties schema wrapper - - Mapping(required=[geometry, properties, type]) - A feature object which contains a geometry and associated properties. - https://tools.ietf.org/html/rfc7946#section-3.2 - - Parameters - ---------- - - geometry : :class:`Geometry` - The feature's geometry - properties : :class:`GeoJsonProperties` - Properties associated with this feature. - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - id : anyOf(string, float) - A value that uniquely identifies this feature in a - https://tools.ietf.org/html/rfc7946#section-3.2. - """ - _schema = {'$ref': '#/definitions/Feature'} - - def __init__(self, geometry=Undefined, properties=Undefined, type=Undefined, bbox=Undefined, - id=Undefined, **kwds): - super(FeatureGeometryGeoJsonProperties, self).__init__(geometry=geometry, properties=properties, - type=type, bbox=bbox, id=id, **kwds) - - -class Field(VegaLiteSchema): - """Field schema wrapper - - anyOf(:class:`FieldName`, :class:`RepeatRef`) - """ - _schema = {'$ref': '#/definitions/Field'} - - def __init__(self, *args, **kwds): - super(Field, self).__init__(*args, **kwds) - - -class FieldDefWithoutScale(VegaLiteSchema): - """FieldDefWithoutScale schema wrapper - - Mapping(required=[]) - Definition object for a data field, its type and transformation of an encoding channel. - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldDefWithoutScale'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(FieldDefWithoutScale, self).__init__(aggregate=aggregate, bandPosition=bandPosition, - bin=bin, field=field, timeUnit=timeUnit, title=title, - type=type, **kwds) - - -class FieldName(Field): - """FieldName schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/FieldName'} - - def __init__(self, *args): - super(FieldName, self).__init__(*args) - - -class FieldOrDatumDefWithConditionStringFieldDefstring(VegaLiteSchema): - """FieldOrDatumDefWithConditionStringFieldDefstring schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - condition : anyOf(:class:`ConditionalValueDefstringExprRef`, List(:class:`ConditionalValueDefstringExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionStringFieldDefstring, self).__init__(aggregate=aggregate, - bandPosition=bandPosition, - bin=bin, - condition=condition, - field=field, - format=format, - formatType=formatType, - timeUnit=timeUnit, - title=title, type=type, - **kwds) - - -class FieldRange(VegaLiteSchema): - """FieldRange schema wrapper - - Mapping(required=[field]) - - Parameters - ---------- - - field : string - - """ - _schema = {'$ref': '#/definitions/FieldRange'} - - def __init__(self, field=Undefined, **kwds): - super(FieldRange, self).__init__(field=field, **kwds) - - -class Fit(VegaLiteSchema): - """Fit schema wrapper - - anyOf(:class:`GeoJsonFeature`, :class:`GeoJsonFeatureCollection`, - List(:class:`GeoJsonFeature`)) - """ - _schema = {'$ref': '#/definitions/Fit'} - - def __init__(self, *args, **kwds): - super(Fit, self).__init__(*args, **kwds) - - -class FontStyle(VegaLiteSchema): - """FontStyle schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/FontStyle'} - - def __init__(self, *args): - super(FontStyle, self).__init__(*args) - - -class FontWeight(VegaLiteSchema): - """FontWeight schema wrapper - - enum('normal', 'bold', 'lighter', 'bolder', 100, 200, 300, 400, 500, 600, 700, 800, 900) - """ - _schema = {'$ref': '#/definitions/FontWeight'} - - def __init__(self, *args): - super(FontWeight, self).__init__(*args) - - -class Generator(Data): - """Generator schema wrapper - - anyOf(:class:`SequenceGenerator`, :class:`SphereGenerator`, :class:`GraticuleGenerator`) - """ - _schema = {'$ref': '#/definitions/Generator'} - - def __init__(self, *args, **kwds): - super(Generator, self).__init__(*args, **kwds) - - -class GenericUnitSpecEncodingAnyMark(VegaLiteSchema): - """GenericUnitSpecEncodingAnyMark schema wrapper - - Mapping(required=[mark]) - Base interface for a unit (single-view) specification. - - Parameters - ---------- - - mark : :class:`AnyMark` - A string describing the mark type (one of ``"bar"``, ``"circle"``, ``"square"``, - ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"rule"``, ``"geoshape"``, and - ``"text"`` ) or a `mark definition object - `__. - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - encoding : :class:`Encoding` - A key-value mapping between encoding channels and definition of fields. - name : string - Name of the visualization for later reference. - params : List(:class:`SelectionParameter`) - An array of parameters that may either be simple variables, or more complex - selections that map user input to data queries. - projection : :class:`Projection` - An object defining properties of geographic projection, which will be applied to - ``shape`` path for ``"geoshape"`` marks and to ``latitude`` and ``"longitude"`` - channels for other marks. - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - """ - _schema = {'$ref': '#/definitions/GenericUnitSpec'} - - def __init__(self, mark=Undefined, data=Undefined, description=Undefined, encoding=Undefined, - name=Undefined, params=Undefined, projection=Undefined, title=Undefined, - transform=Undefined, **kwds): - super(GenericUnitSpecEncodingAnyMark, self).__init__(mark=mark, data=data, - description=description, encoding=encoding, - name=name, params=params, - projection=projection, title=title, - transform=transform, **kwds) - - -class GeoJsonFeature(Fit): - """GeoJsonFeature schema wrapper - - Mapping(required=[geometry, properties, type]) - A feature object which contains a geometry and associated properties. - https://tools.ietf.org/html/rfc7946#section-3.2 - - Parameters - ---------- - - geometry : :class:`Geometry` - The feature's geometry - properties : :class:`GeoJsonProperties` - Properties associated with this feature. - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - id : anyOf(string, float) - A value that uniquely identifies this feature in a - https://tools.ietf.org/html/rfc7946#section-3.2. - """ - _schema = {'$ref': '#/definitions/GeoJsonFeature'} - - def __init__(self, geometry=Undefined, properties=Undefined, type=Undefined, bbox=Undefined, - id=Undefined, **kwds): - super(GeoJsonFeature, self).__init__(geometry=geometry, properties=properties, type=type, - bbox=bbox, id=id, **kwds) - - -class GeoJsonFeatureCollection(Fit): - """GeoJsonFeatureCollection schema wrapper - - Mapping(required=[features, type]) - A collection of feature objects. https://tools.ietf.org/html/rfc7946#section-3.3 - - Parameters - ---------- - - features : List(:class:`FeatureGeometryGeoJsonProperties`) - - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/GeoJsonFeatureCollection'} - - def __init__(self, features=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(GeoJsonFeatureCollection, self).__init__(features=features, type=type, bbox=bbox, **kwds) - - -class GeoJsonProperties(VegaLiteSchema): - """GeoJsonProperties schema wrapper - - anyOf(Mapping(required=[]), None) - """ - _schema = {'$ref': '#/definitions/GeoJsonProperties'} - - def __init__(self, *args, **kwds): - super(GeoJsonProperties, self).__init__(*args, **kwds) - - -class Geometry(VegaLiteSchema): - """Geometry schema wrapper - - anyOf(:class:`Point`, :class:`MultiPoint`, :class:`LineString`, :class:`MultiLineString`, - :class:`Polygon`, :class:`MultiPolygon`, :class:`GeometryCollection`) - Union of geometry objects. https://tools.ietf.org/html/rfc7946#section-3 - """ - _schema = {'$ref': '#/definitions/Geometry'} - - def __init__(self, *args, **kwds): - super(Geometry, self).__init__(*args, **kwds) - - -class GeometryCollection(Geometry): - """GeometryCollection schema wrapper - - Mapping(required=[geometries, type]) - Geometry Collection https://tools.ietf.org/html/rfc7946#section-3.1.8 - - Parameters - ---------- - - geometries : List(:class:`Geometry`) - - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/GeometryCollection'} - - def __init__(self, geometries=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(GeometryCollection, self).__init__(geometries=geometries, type=type, bbox=bbox, **kwds) - - -class Gradient(VegaLiteSchema): - """Gradient schema wrapper - - anyOf(:class:`LinearGradient`, :class:`RadialGradient`) - """ - _schema = {'$ref': '#/definitions/Gradient'} - - def __init__(self, *args, **kwds): - super(Gradient, self).__init__(*args, **kwds) - - -class GradientStop(VegaLiteSchema): - """GradientStop schema wrapper - - Mapping(required=[offset, color]) - - Parameters - ---------- - - color : :class:`Color` - The color value at this point in the gradient. - offset : float - The offset fraction for the color stop, indicating its position within the gradient. - """ - _schema = {'$ref': '#/definitions/GradientStop'} - - def __init__(self, color=Undefined, offset=Undefined, **kwds): - super(GradientStop, self).__init__(color=color, offset=offset, **kwds) - - -class GraticuleGenerator(Generator): - """GraticuleGenerator schema wrapper - - Mapping(required=[graticule]) - - Parameters - ---------- - - graticule : anyOf(boolean, :class:`GraticuleParams`) - Generate graticule GeoJSON data for geographic reference lines. - name : string - Provide a placeholder name and bind data at runtime. - """ - _schema = {'$ref': '#/definitions/GraticuleGenerator'} - - def __init__(self, graticule=Undefined, name=Undefined, **kwds): - super(GraticuleGenerator, self).__init__(graticule=graticule, name=name, **kwds) - - -class GraticuleParams(VegaLiteSchema): - """GraticuleParams schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - extent : :class:`Vector2Vector2number` - Sets both the major and minor extents to the same values. - extentMajor : :class:`Vector2Vector2number` - The major extent of the graticule as a two-element array of coordinates. - extentMinor : :class:`Vector2Vector2number` - The minor extent of the graticule as a two-element array of coordinates. - precision : float - The precision of the graticule in degrees. - - **Default value:** ``2.5`` - step : :class:`Vector2number` - Sets both the major and minor step angles to the same values. - stepMajor : :class:`Vector2number` - The major step angles of the graticule. - - **Default value:** ``[90, 360]`` - stepMinor : :class:`Vector2number` - The minor step angles of the graticule. - - **Default value:** ``[10, 10]`` - """ - _schema = {'$ref': '#/definitions/GraticuleParams'} - - def __init__(self, extent=Undefined, extentMajor=Undefined, extentMinor=Undefined, - precision=Undefined, step=Undefined, stepMajor=Undefined, stepMinor=Undefined, **kwds): - super(GraticuleParams, self).__init__(extent=extent, extentMajor=extentMajor, - extentMinor=extentMinor, precision=precision, step=step, - stepMajor=stepMajor, stepMinor=stepMinor, **kwds) - - -class Header(VegaLiteSchema): - """Header schema wrapper - - Mapping(required=[]) - Headers of row / column channels for faceted plots. - - Parameters - ---------- - - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`) - Horizontal text alignment of header labels. One of ``"left"``, ``"center"``, or - ``"right"``. - labelAnchor : :class:`TitleAnchor` - The anchor position for placing the labels. One of ``"start"``, ``"middle"``, or - ``"end"``. For example, with a label orientation of top these anchor positions map - to a left-, center-, or right-aligned label. - labelAngle : float - The rotation angle of the header labels. - - **Default value:** ``0`` for column header, ``-90`` for row header. - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - The vertical text baseline for the header labels. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The - ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and - ``"bottom"``, but are calculated relative to the ``titleLineHeight`` rather than - ``titleFontSize`` alone. - labelColor : anyOf(:class:`Color`, :class:`ExprRef`) - The color of the header label, can be in hex color code or regular color name. - labelExpr : string - `Vega expression `__ for customizing - labels. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the header's backing ``datum`` object. - labelFont : anyOf(string, :class:`ExprRef`) - The font of the header label. - labelFontSize : anyOf(float, :class:`ExprRef`) - The font size of the header label, in pixels. - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style of the header label. - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight of the header label. - labelLimit : anyOf(float, :class:`ExprRef`) - The maximum length of the header label in pixels. The text value will be - automatically truncated if the rendered size exceeds the limit. - - **Default value:** ``0``, indicating no limit - labelLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line header labels or title text with ``"line-top"`` - or ``"line-bottom"`` baseline. - labelOrient : :class:`Orient` - The orientation of the header label. One of ``"top"``, ``"bottom"``, ``"left"`` or - ``"right"``. - labelPadding : anyOf(float, :class:`ExprRef`) - The padding, in pixel, between facet header's label and the plot. - - **Default value:** ``10`` - labels : boolean - A boolean flag indicating if labels should be included as part of the header. - - **Default value:** ``true``. - orient : :class:`Orient` - Shortcut for setting both labelOrient and titleOrient. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - titleAlign : anyOf(:class:`Align`, :class:`ExprRef`) - Horizontal text alignment (to the anchor) of header titles. - titleAnchor : :class:`TitleAnchor` - The anchor position for placing the title. One of ``"start"``, ``"middle"``, or - ``"end"``. For example, with an orientation of top these anchor positions map to a - left-, center-, or right-aligned title. - titleAngle : float - The rotation angle of the header title. - - **Default value:** ``0``. - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - The vertical text baseline for the header title. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The - ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and - ``"bottom"``, but are calculated relative to the ``titleLineHeight`` rather than - ``titleFontSize`` alone. - - **Default value:** ``"middle"`` - titleColor : anyOf(:class:`Color`, :class:`ExprRef`) - Color of the header title, can be in hex color code or regular color name. - titleFont : anyOf(string, :class:`ExprRef`) - Font of the header title. (e.g., ``"Helvetica Neue"`` ). - titleFontSize : anyOf(float, :class:`ExprRef`) - Font size of the header title. - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style of the header title. - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight of the header title. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - titleLimit : anyOf(float, :class:`ExprRef`) - The maximum length of the header title in pixels. The text value will be - automatically truncated if the rendered size exceeds the limit. - - **Default value:** ``0``, indicating no limit - titleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line header title text or title text with - ``"line-top"`` or ``"line-bottom"`` baseline. - titleOrient : :class:`Orient` - The orientation of the header title. One of ``"top"``, ``"bottom"``, ``"left"`` or - ``"right"``. - titlePadding : anyOf(float, :class:`ExprRef`) - The padding, in pixel, between facet header's title and the label. - - **Default value:** ``10`` - """ - _schema = {'$ref': '#/definitions/Header'} - - def __init__(self, format=Undefined, formatType=Undefined, labelAlign=Undefined, - labelAnchor=Undefined, labelAngle=Undefined, labelBaseline=Undefined, - labelColor=Undefined, labelExpr=Undefined, labelFont=Undefined, - labelFontSize=Undefined, labelFontStyle=Undefined, labelFontWeight=Undefined, - labelLimit=Undefined, labelLineHeight=Undefined, labelOrient=Undefined, - labelPadding=Undefined, labels=Undefined, orient=Undefined, title=Undefined, - titleAlign=Undefined, titleAnchor=Undefined, titleAngle=Undefined, - titleBaseline=Undefined, titleColor=Undefined, titleFont=Undefined, - titleFontSize=Undefined, titleFontStyle=Undefined, titleFontWeight=Undefined, - titleLimit=Undefined, titleLineHeight=Undefined, titleOrient=Undefined, - titlePadding=Undefined, **kwds): - super(Header, self).__init__(format=format, formatType=formatType, labelAlign=labelAlign, - labelAnchor=labelAnchor, labelAngle=labelAngle, - labelBaseline=labelBaseline, labelColor=labelColor, - labelExpr=labelExpr, labelFont=labelFont, - labelFontSize=labelFontSize, labelFontStyle=labelFontStyle, - labelFontWeight=labelFontWeight, labelLimit=labelLimit, - labelLineHeight=labelLineHeight, labelOrient=labelOrient, - labelPadding=labelPadding, labels=labels, orient=orient, - title=title, titleAlign=titleAlign, titleAnchor=titleAnchor, - titleAngle=titleAngle, titleBaseline=titleBaseline, - titleColor=titleColor, titleFont=titleFont, - titleFontSize=titleFontSize, titleFontStyle=titleFontStyle, - titleFontWeight=titleFontWeight, titleLimit=titleLimit, - titleLineHeight=titleLineHeight, titleOrient=titleOrient, - titlePadding=titlePadding, **kwds) - - -class HeaderConfig(VegaLiteSchema): - """HeaderConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`) - Horizontal text alignment of header labels. One of ``"left"``, ``"center"``, or - ``"right"``. - labelAnchor : :class:`TitleAnchor` - The anchor position for placing the labels. One of ``"start"``, ``"middle"``, or - ``"end"``. For example, with a label orientation of top these anchor positions map - to a left-, center-, or right-aligned label. - labelAngle : float - The rotation angle of the header labels. - - **Default value:** ``0`` for column header, ``-90`` for row header. - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - The vertical text baseline for the header labels. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The - ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and - ``"bottom"``, but are calculated relative to the ``titleLineHeight`` rather than - ``titleFontSize`` alone. - labelColor : anyOf(:class:`Color`, :class:`ExprRef`) - The color of the header label, can be in hex color code or regular color name. - labelExpr : string - `Vega expression `__ for customizing - labels. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the header's backing ``datum`` object. - labelFont : anyOf(string, :class:`ExprRef`) - The font of the header label. - labelFontSize : anyOf(float, :class:`ExprRef`) - The font size of the header label, in pixels. - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style of the header label. - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight of the header label. - labelLimit : anyOf(float, :class:`ExprRef`) - The maximum length of the header label in pixels. The text value will be - automatically truncated if the rendered size exceeds the limit. - - **Default value:** ``0``, indicating no limit - labelLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line header labels or title text with ``"line-top"`` - or ``"line-bottom"`` baseline. - labelOrient : :class:`Orient` - The orientation of the header label. One of ``"top"``, ``"bottom"``, ``"left"`` or - ``"right"``. - labelPadding : anyOf(float, :class:`ExprRef`) - The padding, in pixel, between facet header's label and the plot. - - **Default value:** ``10`` - labels : boolean - A boolean flag indicating if labels should be included as part of the header. - - **Default value:** ``true``. - orient : :class:`Orient` - Shortcut for setting both labelOrient and titleOrient. - title : None - Set to null to disable title for the axis, legend, or header. - titleAlign : anyOf(:class:`Align`, :class:`ExprRef`) - Horizontal text alignment (to the anchor) of header titles. - titleAnchor : :class:`TitleAnchor` - The anchor position for placing the title. One of ``"start"``, ``"middle"``, or - ``"end"``. For example, with an orientation of top these anchor positions map to a - left-, center-, or right-aligned title. - titleAngle : float - The rotation angle of the header title. - - **Default value:** ``0``. - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - The vertical text baseline for the header title. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The - ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and - ``"bottom"``, but are calculated relative to the ``titleLineHeight`` rather than - ``titleFontSize`` alone. - - **Default value:** ``"middle"`` - titleColor : anyOf(:class:`Color`, :class:`ExprRef`) - Color of the header title, can be in hex color code or regular color name. - titleFont : anyOf(string, :class:`ExprRef`) - Font of the header title. (e.g., ``"Helvetica Neue"`` ). - titleFontSize : anyOf(float, :class:`ExprRef`) - Font size of the header title. - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style of the header title. - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight of the header title. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - titleLimit : anyOf(float, :class:`ExprRef`) - The maximum length of the header title in pixels. The text value will be - automatically truncated if the rendered size exceeds the limit. - - **Default value:** ``0``, indicating no limit - titleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line header title text or title text with - ``"line-top"`` or ``"line-bottom"`` baseline. - titleOrient : :class:`Orient` - The orientation of the header title. One of ``"top"``, ``"bottom"``, ``"left"`` or - ``"right"``. - titlePadding : anyOf(float, :class:`ExprRef`) - The padding, in pixel, between facet header's title and the label. - - **Default value:** ``10`` - """ - _schema = {'$ref': '#/definitions/HeaderConfig'} - - def __init__(self, format=Undefined, formatType=Undefined, labelAlign=Undefined, - labelAnchor=Undefined, labelAngle=Undefined, labelBaseline=Undefined, - labelColor=Undefined, labelExpr=Undefined, labelFont=Undefined, - labelFontSize=Undefined, labelFontStyle=Undefined, labelFontWeight=Undefined, - labelLimit=Undefined, labelLineHeight=Undefined, labelOrient=Undefined, - labelPadding=Undefined, labels=Undefined, orient=Undefined, title=Undefined, - titleAlign=Undefined, titleAnchor=Undefined, titleAngle=Undefined, - titleBaseline=Undefined, titleColor=Undefined, titleFont=Undefined, - titleFontSize=Undefined, titleFontStyle=Undefined, titleFontWeight=Undefined, - titleLimit=Undefined, titleLineHeight=Undefined, titleOrient=Undefined, - titlePadding=Undefined, **kwds): - super(HeaderConfig, self).__init__(format=format, formatType=formatType, labelAlign=labelAlign, - labelAnchor=labelAnchor, labelAngle=labelAngle, - labelBaseline=labelBaseline, labelColor=labelColor, - labelExpr=labelExpr, labelFont=labelFont, - labelFontSize=labelFontSize, labelFontStyle=labelFontStyle, - labelFontWeight=labelFontWeight, labelLimit=labelLimit, - labelLineHeight=labelLineHeight, labelOrient=labelOrient, - labelPadding=labelPadding, labels=labels, orient=orient, - title=title, titleAlign=titleAlign, titleAnchor=titleAnchor, - titleAngle=titleAngle, titleBaseline=titleBaseline, - titleColor=titleColor, titleFont=titleFont, - titleFontSize=titleFontSize, titleFontStyle=titleFontStyle, - titleFontWeight=titleFontWeight, titleLimit=titleLimit, - titleLineHeight=titleLineHeight, titleOrient=titleOrient, - titlePadding=titlePadding, **kwds) - - -class HexColor(Color): - """HexColor schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/HexColor'} - - def __init__(self, *args): - super(HexColor, self).__init__(*args) - - -class ImputeMethod(VegaLiteSchema): - """ImputeMethod schema wrapper - - enum('value', 'median', 'max', 'min', 'mean') - """ - _schema = {'$ref': '#/definitions/ImputeMethod'} - - def __init__(self, *args): - super(ImputeMethod, self).__init__(*args) - - -class ImputeParams(VegaLiteSchema): - """ImputeParams schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - frame : List(anyOf(None, float)) - A frame specification as a two-element array used to control the window over which - the specified method is applied. The array entries should either be a number - indicating the offset from the current data object, or null to indicate unbounded - rows preceding or following the current data object. For example, the value ``[-5, - 5]`` indicates that the window should include five objects preceding and five - objects following the current object. - - **Default value:** : ``[null, null]`` indicating that the window includes all - objects. - keyvals : anyOf(List(Any), :class:`ImputeSequence`) - Defines the key values that should be considered for imputation. An array of key - values or an object defining a `number sequence - `__. - - If provided, this will be used in addition to the key values observed within the - input data. If not provided, the values will be derived from all unique values of - the ``key`` field. For ``impute`` in ``encoding``, the key field is the x-field if - the y-field is imputed, or vice versa. - - If there is no impute grouping, this property *must* be specified. - method : :class:`ImputeMethod` - The imputation method to use for the field value of imputed data objects. One of - ``"value"``, ``"mean"``, ``"median"``, ``"max"`` or ``"min"``. - - **Default value:** ``"value"`` - value : Any - The field value to use when the imputation ``method`` is ``"value"``. - """ - _schema = {'$ref': '#/definitions/ImputeParams'} - - def __init__(self, frame=Undefined, keyvals=Undefined, method=Undefined, value=Undefined, **kwds): - super(ImputeParams, self).__init__(frame=frame, keyvals=keyvals, method=method, value=value, - **kwds) - - -class ImputeSequence(VegaLiteSchema): - """ImputeSequence schema wrapper - - Mapping(required=[stop]) - - Parameters - ---------- - - stop : float - The ending value(exclusive) of the sequence. - start : float - The starting value of the sequence. **Default value:** ``0`` - step : float - The step value between sequence entries. **Default value:** ``1`` or ``-1`` if - ``stop < start`` - """ - _schema = {'$ref': '#/definitions/ImputeSequence'} - - def __init__(self, stop=Undefined, start=Undefined, step=Undefined, **kwds): - super(ImputeSequence, self).__init__(stop=stop, start=start, step=step, **kwds) - - -class InlineData(DataSource): - """InlineData schema wrapper - - Mapping(required=[values]) - - Parameters - ---------- - - values : :class:`InlineDataset` - The full data set, included inline. This can be an array of objects or primitive - values, an object, or a string. Arrays of primitive values are ingested as objects - with a ``data`` property. Strings are parsed according to the specified format type. - format : :class:`DataFormat` - An object that specifies the format for parsing the data. - name : string - Provide a placeholder name and bind data at runtime. - """ - _schema = {'$ref': '#/definitions/InlineData'} - - def __init__(self, values=Undefined, format=Undefined, name=Undefined, **kwds): - super(InlineData, self).__init__(values=values, format=format, name=name, **kwds) - - -class InlineDataset(VegaLiteSchema): - """InlineDataset schema wrapper - - anyOf(List(float), List(string), List(boolean), List(Mapping(required=[])), string, - Mapping(required=[])) - """ - _schema = {'$ref': '#/definitions/InlineDataset'} - - def __init__(self, *args, **kwds): - super(InlineDataset, self).__init__(*args, **kwds) - - -class Interpolate(VegaLiteSchema): - """Interpolate schema wrapper - - enum('basis', 'basis-open', 'basis-closed', 'bundle', 'cardinal', 'cardinal-open', - 'cardinal-closed', 'catmull-rom', 'linear', 'linear-closed', 'monotone', 'natural', 'step', - 'step-before', 'step-after') - """ - _schema = {'$ref': '#/definitions/Interpolate'} - - def __init__(self, *args): - super(Interpolate, self).__init__(*args) - - -class IntervalSelectionConfig(VegaLiteSchema): - """IntervalSelectionConfig schema wrapper - - Mapping(required=[type]) - - Parameters - ---------- - - type : string - Determines the default event processing and data query for the selection. Vega-Lite - currently supports two selection types: - - - * ``"point"`` -- to select multiple discrete data values; the first value is - selected on ``click`` and additional values toggled on shift-click. - * ``"interval"`` -- to select a continuous range of data values on ``drag``. - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. This property can be a `Event - Stream `__ or ``false`` to disable - clear. - - **Default value:** ``dblclick``. - - **See also:** `clear examples - `__ in the - documentation. - encodings : List(:class:`SingleDefUnitChannel`) - An array of encoding channels. The corresponding data field values must match for a - data tuple to fall within the selection. - - **See also:** The `projection with encodings and fields section - `__ in the - documentation. - mark : :class:`BrushConfig` - An interval selection also adds a rectangle mark to depict the extents of the - interval. The ``mark`` property can be used to customize the appearance of the mark. - - **See also:** `mark examples - `__ in the documentation. - on : anyOf(:class:`Stream`, string) - A `Vega event stream `__ (object or - selector) that triggers the selection. For interval selections, the event stream - must specify a `start and end - `__. - - **See also:** `on examples - `__ in the documentation. - resolve : :class:`SelectionResolution` - With layered and multi-view displays, a strategy that determines how selections' - data queries are resolved when applied in a filter transform, conditional encoding - rule, or scale domain. - - One of: - - - * ``"global"`` -- only one brush exists for the entire SPLOM. When the user begins - to drag, any previous brushes are cleared, and a new one is constructed. - * ``"union"`` -- each cell contains its own brush, and points are highlighted if - they lie within *any* of these individual brushes. - * ``"intersect"`` -- each cell contains its own brush, and points are highlighted - only if they fall within *all* of these individual brushes. - - **Default value:** ``global``. - - **See also:** `resolve examples - `__ in the - documentation. - translate : anyOf(string, boolean) - When truthy, allows a user to interactively move an interval selection - back-and-forth. Can be ``true``, ``false`` (to disable panning), or a `Vega event - stream definition `__ which must - include a start and end event to trigger continuous panning. Discrete panning (e.g., - pressing the left/right arrow keys) will be supported in future versions. - - **Default value:** ``true``, which corresponds to ``[mousedown, window:mouseup] > - window:mousemove!``. This default allows users to clicks and drags within an - interval selection to reposition it. - - **See also:** `translate examples - `__ in the - documentation. - zoom : anyOf(string, boolean) - When truthy, allows a user to interactively resize an interval selection. Can be - ``true``, ``false`` (to disable zooming), or a `Vega event stream definition - `__. Currently, only ``wheel`` - events are supported, but custom event streams can still be used to specify filters, - debouncing, and throttling. Future versions will expand the set of events that can - trigger this transformation. - - **Default value:** ``true``, which corresponds to ``wheel!``. This default allows - users to use the mouse wheel to resize an interval selection. - - **See also:** `zoom examples - `__ in the documentation. - """ - _schema = {'$ref': '#/definitions/IntervalSelectionConfig'} - - def __init__(self, type=Undefined, clear=Undefined, encodings=Undefined, mark=Undefined, - on=Undefined, resolve=Undefined, translate=Undefined, zoom=Undefined, **kwds): - super(IntervalSelectionConfig, self).__init__(type=type, clear=clear, encodings=encodings, - mark=mark, on=on, resolve=resolve, - translate=translate, zoom=zoom, **kwds) - - -class IntervalSelectionConfigWithoutType(VegaLiteSchema): - """IntervalSelectionConfigWithoutType schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. This property can be a `Event - Stream `__ or ``false`` to disable - clear. - - **Default value:** ``dblclick``. - - **See also:** `clear examples - `__ in the - documentation. - encodings : List(:class:`SingleDefUnitChannel`) - An array of encoding channels. The corresponding data field values must match for a - data tuple to fall within the selection. - - **See also:** The `projection with encodings and fields section - `__ in the - documentation. - mark : :class:`BrushConfig` - An interval selection also adds a rectangle mark to depict the extents of the - interval. The ``mark`` property can be used to customize the appearance of the mark. - - **See also:** `mark examples - `__ in the documentation. - on : anyOf(:class:`Stream`, string) - A `Vega event stream `__ (object or - selector) that triggers the selection. For interval selections, the event stream - must specify a `start and end - `__. - - **See also:** `on examples - `__ in the documentation. - resolve : :class:`SelectionResolution` - With layered and multi-view displays, a strategy that determines how selections' - data queries are resolved when applied in a filter transform, conditional encoding - rule, or scale domain. - - One of: - - - * ``"global"`` -- only one brush exists for the entire SPLOM. When the user begins - to drag, any previous brushes are cleared, and a new one is constructed. - * ``"union"`` -- each cell contains its own brush, and points are highlighted if - they lie within *any* of these individual brushes. - * ``"intersect"`` -- each cell contains its own brush, and points are highlighted - only if they fall within *all* of these individual brushes. - - **Default value:** ``global``. - - **See also:** `resolve examples - `__ in the - documentation. - translate : anyOf(string, boolean) - When truthy, allows a user to interactively move an interval selection - back-and-forth. Can be ``true``, ``false`` (to disable panning), or a `Vega event - stream definition `__ which must - include a start and end event to trigger continuous panning. Discrete panning (e.g., - pressing the left/right arrow keys) will be supported in future versions. - - **Default value:** ``true``, which corresponds to ``[mousedown, window:mouseup] > - window:mousemove!``. This default allows users to clicks and drags within an - interval selection to reposition it. - - **See also:** `translate examples - `__ in the - documentation. - zoom : anyOf(string, boolean) - When truthy, allows a user to interactively resize an interval selection. Can be - ``true``, ``false`` (to disable zooming), or a `Vega event stream definition - `__. Currently, only ``wheel`` - events are supported, but custom event streams can still be used to specify filters, - debouncing, and throttling. Future versions will expand the set of events that can - trigger this transformation. - - **Default value:** ``true``, which corresponds to ``wheel!``. This default allows - users to use the mouse wheel to resize an interval selection. - - **See also:** `zoom examples - `__ in the documentation. - """ - _schema = {'$ref': '#/definitions/IntervalSelectionConfigWithoutType'} - - def __init__(self, clear=Undefined, encodings=Undefined, mark=Undefined, on=Undefined, - resolve=Undefined, translate=Undefined, zoom=Undefined, **kwds): - super(IntervalSelectionConfigWithoutType, self).__init__(clear=clear, encodings=encodings, - mark=mark, on=on, resolve=resolve, - translate=translate, zoom=zoom, **kwds) - - -class JoinAggregateFieldDef(VegaLiteSchema): - """JoinAggregateFieldDef schema wrapper - - Mapping(required=[op, as]) - - Parameters - ---------- - - op : :class:`AggregateOp` - The aggregation operation to apply (e.g., ``"sum"``, ``"average"`` or ``"count"`` ). - See the list of all supported operations `here - `__. - field : :class:`FieldName` - The data field for which to compute the aggregate function. This can be omitted for - functions that do not operate over a field such as ``"count"``. - as : :class:`FieldName` - The output name for the join aggregate operation. - """ - _schema = {'$ref': '#/definitions/JoinAggregateFieldDef'} - - def __init__(self, op=Undefined, field=Undefined, **kwds): - super(JoinAggregateFieldDef, self).__init__(op=op, field=field, **kwds) - - -class JsonDataFormat(DataFormat): - """JsonDataFormat schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - parse : anyOf(:class:`Parse`, None) - If set to ``null``, disable type inference based on the spec and only use type - inference based on the data. Alternatively, a parsing directive object can be - provided for explicit data types. Each property of the object corresponds to a field - name, and the value to the desired data type (one of ``"number"``, ``"boolean"``, - ``"date"``, or null (do not parse the field)). For example, ``"parse": - {"modified_on": "date"}`` parses the ``modified_on`` field in each input record a - Date value. - - For ``"date"``, we parse data based using JavaScript's `Date.parse() - `__. - For Specific date formats can be provided (e.g., ``{foo: "date:'%m%d%Y'"}`` ), using - the `d3-time-format syntax `__. - UTC date format parsing is supported similarly (e.g., ``{foo: "utc:'%m%d%Y'"}`` ). - See more about `UTC time - `__ - property : string - The JSON property containing the desired data. This parameter can be used when the - loaded JSON file may have surrounding structure or meta-data. For example - ``"property": "values.features"`` is equivalent to retrieving - ``json.values.features`` from the loaded JSON object. - type : string - Type of input data: ``"json"``, ``"csv"``, ``"tsv"``, ``"dsv"``. - - **Default value:** The default format type is determined by the extension of the - file URL. If no extension is detected, ``"json"`` will be used by default. - """ - _schema = {'$ref': '#/definitions/JsonDataFormat'} - - def __init__(self, parse=Undefined, property=Undefined, type=Undefined, **kwds): - super(JsonDataFormat, self).__init__(parse=parse, property=property, type=type, **kwds) - - -class LabelOverlap(VegaLiteSchema): - """LabelOverlap schema wrapper - - anyOf(boolean, string, string) - """ - _schema = {'$ref': '#/definitions/LabelOverlap'} - - def __init__(self, *args, **kwds): - super(LabelOverlap, self).__init__(*args, **kwds) - - -class LatLongDef(VegaLiteSchema): - """LatLongDef schema wrapper - - anyOf(:class:`LatLongFieldDef`, :class:`DatumDef`) - """ - _schema = {'$ref': '#/definitions/LatLongDef'} - - def __init__(self, *args, **kwds): - super(LatLongDef, self).__init__(*args, **kwds) - - -class LatLongFieldDef(LatLongDef): - """LatLongFieldDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : None - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : string - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/LatLongFieldDef'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(LatLongFieldDef, self).__init__(aggregate=aggregate, bandPosition=bandPosition, bin=bin, - field=field, timeUnit=timeUnit, title=title, type=type, - **kwds) - - -class LayerRepeatMapping(VegaLiteSchema): - """LayerRepeatMapping schema wrapper - - Mapping(required=[layer]) - - Parameters - ---------- - - layer : List(string) - An array of fields to be repeated as layers. - column : List(string) - An array of fields to be repeated horizontally. - row : List(string) - An array of fields to be repeated vertically. - """ - _schema = {'$ref': '#/definitions/LayerRepeatMapping'} - - def __init__(self, layer=Undefined, column=Undefined, row=Undefined, **kwds): - super(LayerRepeatMapping, self).__init__(layer=layer, column=column, row=row, **kwds) - - -class LayoutAlign(VegaLiteSchema): - """LayoutAlign schema wrapper - - enum('all', 'each', 'none') - """ - _schema = {'$ref': '#/definitions/LayoutAlign'} - - def __init__(self, *args): - super(LayoutAlign, self).__init__(*args) - - -class Legend(VegaLiteSchema): - """Legend schema wrapper - - Mapping(required=[]) - Properties of a legend or boolean flag for determining whether to show it. - - Parameters - ---------- - - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG group, removing the legend from the ARIA accessibility tree. - - **Default value:** ``true`` - clipHeight : anyOf(float, :class:`ExprRef`) - The height in pixels to clip symbol legend entries and limit their size. - columnPadding : anyOf(float, :class:`ExprRef`) - The horizontal padding in pixels between symbol legend entries. - - **Default value:** ``10``. - columns : anyOf(float, :class:`ExprRef`) - The number of columns in which to arrange symbol legend entries. A value of ``0`` or - lower indicates a single row with one column per entry. - cornerRadius : anyOf(float, :class:`ExprRef`) - Corner radius for the full legend. - description : anyOf(string, :class:`ExprRef`) - A text description of this legend for `ARIA accessibility - `__ (SVG output - only). If the ``aria`` property is true, for SVG output the `"aria-label" attribute - `__ - will be set to this description. If the description is unspecified it will be - automatically generated. - direction : :class:`Orientation` - The direction of the legend, one of ``"vertical"`` or ``"horizontal"``. - - **Default value:** - - - * For top-/bottom- ``orient`` ed legends, ``"horizontal"`` - * For left-/right- ``orient`` ed legends, ``"vertical"`` - * For top/bottom-left/right- ``orient`` ed legends, ``"horizontal"`` for gradient - legends and ``"vertical"`` for symbol legends. - fillColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Background fill color for the full legend. - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - gradientLength : anyOf(float, :class:`ExprRef`) - The length in pixels of the primary axis of a color gradient. This value corresponds - to the height of a vertical gradient or the width of a horizontal gradient. - - **Default value:** ``200``. - gradientOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the color gradient. - gradientStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - The color of the gradient stroke, can be in hex color code or regular color name. - - **Default value:** ``"lightGray"``. - gradientStrokeWidth : anyOf(float, :class:`ExprRef`) - The width of the gradient stroke, in pixels. - - **Default value:** ``0``. - gradientThickness : anyOf(float, :class:`ExprRef`) - The thickness in pixels of the color gradient. This value corresponds to the width - of a vertical gradient or the height of a horizontal gradient. - - **Default value:** ``16``. - gridAlign : anyOf(:class:`LayoutAlign`, :class:`ExprRef`) - The alignment to apply to symbol legends rows and columns. The supported string - values are ``"all"``, ``"each"`` (the default), and ``none``. For more information, - see the `grid layout documentation `__. - - **Default value:** ``"each"``. - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`) - The alignment of the legend label, can be left, center, or right. - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - The position of the baseline of legend label, can be ``"top"``, ``"middle"``, - ``"bottom"``, or ``"alphabetic"``. - - **Default value:** ``"middle"``. - labelColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - The color of the legend label, can be in hex color code or regular color name. - labelExpr : string - `Vega expression `__ for customizing - labels. - - **Note:** The label text and value can be assessed via the ``label`` and ``value`` - properties of the legend's backing ``datum`` object. - labelFont : anyOf(string, :class:`ExprRef`) - The font of the legend label. - labelFontSize : anyOf(float, :class:`ExprRef`) - The font size of legend label. - - **Default value:** ``10``. - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style of legend label. - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight of legend label. - labelLimit : anyOf(float, :class:`ExprRef`) - Maximum allowed pixel width of legend tick labels. - - **Default value:** ``160``. - labelOffset : anyOf(float, :class:`ExprRef`) - The offset of the legend label. - - **Default value:** ``4``. - labelOpacity : anyOf(float, :class:`ExprRef`) - Opacity of labels. - labelOverlap : anyOf(:class:`LabelOverlap`, :class:`ExprRef`) - The strategy to use for resolving overlap of labels in gradient legends. If - ``false``, no overlap reduction is attempted. If set to ``true`` (default) or - ``"parity"``, a strategy of removing every other label is used. If set to - ``"greedy"``, a linear scan of the labels is performed, removing any label that - overlaps with the last visible label (this often works better for log-scaled axes). - - **Default value:** ``true``. - labelPadding : anyOf(float, :class:`ExprRef`) - Padding in pixels between the legend and legend labels. - labelSeparation : anyOf(float, :class:`ExprRef`) - The minimum separation that must be between label bounding boxes for them to be - considered non-overlapping (default ``0`` ). This property is ignored if - *labelOverlap* resolution is not enabled. - legendX : anyOf(float, :class:`ExprRef`) - Custom x-position for legend with orient "none". - legendY : anyOf(float, :class:`ExprRef`) - Custom y-position for legend with orient "none". - offset : anyOf(float, :class:`ExprRef`) - The offset in pixels by which to displace the legend from the data rectangle and - axes. - - **Default value:** ``18``. - orient : :class:`LegendOrient` - The orientation of the legend, which determines how the legend is positioned within - the scene. One of ``"left"``, ``"right"``, ``"top"``, ``"bottom"``, ``"top-left"``, - ``"top-right"``, ``"bottom-left"``, ``"bottom-right"``, ``"none"``. - - **Default value:** ``"right"`` - padding : anyOf(float, :class:`ExprRef`) - The padding between the border and content of the legend group. - - **Default value:** ``0``. - rowPadding : anyOf(float, :class:`ExprRef`) - The vertical padding in pixels between symbol legend entries. - - **Default value:** ``2``. - strokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Border stroke color for the full legend. - symbolDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating [stroke, space] lengths for dashed symbol strokes. - symbolDashOffset : anyOf(float, :class:`ExprRef`) - The pixel offset at which to start drawing with the symbol stroke dash array. - symbolFillColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - The color of the legend symbol, - symbolLimit : anyOf(float, :class:`ExprRef`) - The maximum number of allowed entries for a symbol legend. Additional entries will - be dropped. - symbolOffset : anyOf(float, :class:`ExprRef`) - Horizontal pixel offset for legend symbols. - - **Default value:** ``0``. - symbolOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the legend symbols. - symbolSize : anyOf(float, :class:`ExprRef`) - The size of the legend symbol, in pixels. - - **Default value:** ``100``. - symbolStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Stroke color for legend symbols. - symbolStrokeWidth : anyOf(float, :class:`ExprRef`) - The width of the symbol's stroke. - - **Default value:** ``1.5``. - symbolType : anyOf(:class:`SymbolShape`, :class:`ExprRef`) - The symbol shape. One of the plotting shapes ``circle`` (default), ``square``, - ``cross``, ``diamond``, ``triangle-up``, ``triangle-down``, ``triangle-right``, or - ``triangle-left``, the line symbol ``stroke``, or one of the centered directional - shapes ``arrow``, ``wedge``, or ``triangle``. Alternatively, a custom `SVG path - string `__ can be - provided. For correct sizing, custom shape paths should be defined within a square - bounding box with coordinates ranging from -1 to 1 along both the x and y - dimensions. - - **Default value:** ``"circle"``. - tickCount : anyOf(:class:`TickCount`, :class:`ExprRef`) - The desired number of tick values for quantitative legends. - tickMinStep : anyOf(float, :class:`ExprRef`) - The minimum desired step between legend ticks, in terms of scale domain values. For - example, a value of ``1`` indicates that ticks should not be less than 1 unit apart. - If ``tickMinStep`` is specified, the ``tickCount`` value will be adjusted, if - necessary, to enforce the minimum step value. - - **Default value** : ``undefined`` - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - titleAlign : anyOf(:class:`Align`, :class:`ExprRef`) - Horizontal text alignment for legend titles. - - **Default value:** ``"left"``. - titleAnchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - Text anchor position for placing legend titles. - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - Vertical text baseline for legend titles. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The - ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and - ``"bottom"``, but are calculated relative to the *lineHeight* rather than *fontSize* - alone. - - **Default value:** ``"top"``. - titleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - The color of the legend title, can be in hex color code or regular color name. - titleFont : anyOf(string, :class:`ExprRef`) - The font of the legend title. - titleFontSize : anyOf(float, :class:`ExprRef`) - The font size of the legend title. - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style of the legend title. - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight of the legend title. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - titleLimit : anyOf(float, :class:`ExprRef`) - Maximum allowed pixel width of legend titles. - - **Default value:** ``180``. - titleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line title text or title text with ``"line-top"`` or - ``"line-bottom"`` baseline. - titleOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the legend title. - titleOrient : anyOf(:class:`Orient`, :class:`ExprRef`) - Orientation of the legend title. - titlePadding : anyOf(float, :class:`ExprRef`) - The padding, in pixels, between title and legend. - - **Default value:** ``5``. - type : enum('symbol', 'gradient') - The type of the legend. Use ``"symbol"`` to create a discrete legend and - ``"gradient"`` for a continuous color gradient. - - **Default value:** ``"gradient"`` for non-binned quantitative fields and temporal - fields; ``"symbol"`` otherwise. - values : anyOf(List(float), List(string), List(boolean), List(:class:`DateTime`), :class:`ExprRef`) - Explicitly set the visible legend values. - zindex : float - A non-negative integer indicating the z-index of the legend. If zindex is 0, legend - should be drawn behind all chart elements. To put them in front, use zindex = 1. - """ - _schema = {'$ref': '#/definitions/Legend'} - - def __init__(self, aria=Undefined, clipHeight=Undefined, columnPadding=Undefined, columns=Undefined, - cornerRadius=Undefined, description=Undefined, direction=Undefined, - fillColor=Undefined, format=Undefined, formatType=Undefined, gradientLength=Undefined, - gradientOpacity=Undefined, gradientStrokeColor=Undefined, - gradientStrokeWidth=Undefined, gradientThickness=Undefined, gridAlign=Undefined, - labelAlign=Undefined, labelBaseline=Undefined, labelColor=Undefined, - labelExpr=Undefined, labelFont=Undefined, labelFontSize=Undefined, - labelFontStyle=Undefined, labelFontWeight=Undefined, labelLimit=Undefined, - labelOffset=Undefined, labelOpacity=Undefined, labelOverlap=Undefined, - labelPadding=Undefined, labelSeparation=Undefined, legendX=Undefined, - legendY=Undefined, offset=Undefined, orient=Undefined, padding=Undefined, - rowPadding=Undefined, strokeColor=Undefined, symbolDash=Undefined, - symbolDashOffset=Undefined, symbolFillColor=Undefined, symbolLimit=Undefined, - symbolOffset=Undefined, symbolOpacity=Undefined, symbolSize=Undefined, - symbolStrokeColor=Undefined, symbolStrokeWidth=Undefined, symbolType=Undefined, - tickCount=Undefined, tickMinStep=Undefined, title=Undefined, titleAlign=Undefined, - titleAnchor=Undefined, titleBaseline=Undefined, titleColor=Undefined, - titleFont=Undefined, titleFontSize=Undefined, titleFontStyle=Undefined, - titleFontWeight=Undefined, titleLimit=Undefined, titleLineHeight=Undefined, - titleOpacity=Undefined, titleOrient=Undefined, titlePadding=Undefined, type=Undefined, - values=Undefined, zindex=Undefined, **kwds): - super(Legend, self).__init__(aria=aria, clipHeight=clipHeight, columnPadding=columnPadding, - columns=columns, cornerRadius=cornerRadius, - description=description, direction=direction, fillColor=fillColor, - format=format, formatType=formatType, - gradientLength=gradientLength, gradientOpacity=gradientOpacity, - gradientStrokeColor=gradientStrokeColor, - gradientStrokeWidth=gradientStrokeWidth, - gradientThickness=gradientThickness, gridAlign=gridAlign, - labelAlign=labelAlign, labelBaseline=labelBaseline, - labelColor=labelColor, labelExpr=labelExpr, labelFont=labelFont, - labelFontSize=labelFontSize, labelFontStyle=labelFontStyle, - labelFontWeight=labelFontWeight, labelLimit=labelLimit, - labelOffset=labelOffset, labelOpacity=labelOpacity, - labelOverlap=labelOverlap, labelPadding=labelPadding, - labelSeparation=labelSeparation, legendX=legendX, legendY=legendY, - offset=offset, orient=orient, padding=padding, - rowPadding=rowPadding, strokeColor=strokeColor, - symbolDash=symbolDash, symbolDashOffset=symbolDashOffset, - symbolFillColor=symbolFillColor, symbolLimit=symbolLimit, - symbolOffset=symbolOffset, symbolOpacity=symbolOpacity, - symbolSize=symbolSize, symbolStrokeColor=symbolStrokeColor, - symbolStrokeWidth=symbolStrokeWidth, symbolType=symbolType, - tickCount=tickCount, tickMinStep=tickMinStep, title=title, - titleAlign=titleAlign, titleAnchor=titleAnchor, - titleBaseline=titleBaseline, titleColor=titleColor, - titleFont=titleFont, titleFontSize=titleFontSize, - titleFontStyle=titleFontStyle, titleFontWeight=titleFontWeight, - titleLimit=titleLimit, titleLineHeight=titleLineHeight, - titleOpacity=titleOpacity, titleOrient=titleOrient, - titlePadding=titlePadding, type=type, values=values, zindex=zindex, - **kwds) - - -class LegendBinding(VegaLiteSchema): - """LegendBinding schema wrapper - - anyOf(string, :class:`LegendStreamBinding`) - """ - _schema = {'$ref': '#/definitions/LegendBinding'} - - def __init__(self, *args, **kwds): - super(LegendBinding, self).__init__(*args, **kwds) - - -class LegendConfig(VegaLiteSchema): - """LegendConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG group, removing the legend from the ARIA accessibility tree. - - **Default value:** ``true`` - clipHeight : anyOf(float, :class:`ExprRef`) - The height in pixels to clip symbol legend entries and limit their size. - columnPadding : anyOf(float, :class:`ExprRef`) - The horizontal padding in pixels between symbol legend entries. - - **Default value:** ``10``. - columns : anyOf(float, :class:`ExprRef`) - The number of columns in which to arrange symbol legend entries. A value of ``0`` or - lower indicates a single row with one column per entry. - cornerRadius : anyOf(float, :class:`ExprRef`) - Corner radius for the full legend. - description : anyOf(string, :class:`ExprRef`) - A text description of this legend for `ARIA accessibility - `__ (SVG output - only). If the ``aria`` property is true, for SVG output the `"aria-label" attribute - `__ - will be set to this description. If the description is unspecified it will be - automatically generated. - direction : :class:`Orientation` - The direction of the legend, one of ``"vertical"`` or ``"horizontal"``. - - **Default value:** - - - * For top-/bottom- ``orient`` ed legends, ``"horizontal"`` - * For left-/right- ``orient`` ed legends, ``"vertical"`` - * For top/bottom-left/right- ``orient`` ed legends, ``"horizontal"`` for gradient - legends and ``"vertical"`` for symbol legends. - disable : boolean - Disable legend by default - fillColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Background fill color for the full legend. - gradientDirection : anyOf(:class:`Orientation`, :class:`ExprRef`) - The default direction ( ``"horizontal"`` or ``"vertical"`` ) for gradient legends. - - **Default value:** ``"vertical"``. - gradientHorizontalMaxLength : float - Max legend length for a horizontal gradient when ``config.legend.gradientLength`` is - undefined. - - **Default value:** ``200`` - gradientHorizontalMinLength : float - Min legend length for a horizontal gradient when ``config.legend.gradientLength`` is - undefined. - - **Default value:** ``100`` - gradientLabelLimit : anyOf(float, :class:`ExprRef`) - The maximum allowed length in pixels of color ramp gradient labels. - gradientLabelOffset : anyOf(float, :class:`ExprRef`) - Vertical offset in pixels for color ramp gradient labels. - - **Default value:** ``2``. - gradientLength : anyOf(float, :class:`ExprRef`) - The length in pixels of the primary axis of a color gradient. This value corresponds - to the height of a vertical gradient or the width of a horizontal gradient. - - **Default value:** ``200``. - gradientOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the color gradient. - gradientStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - The color of the gradient stroke, can be in hex color code or regular color name. - - **Default value:** ``"lightGray"``. - gradientStrokeWidth : anyOf(float, :class:`ExprRef`) - The width of the gradient stroke, in pixels. - - **Default value:** ``0``. - gradientThickness : anyOf(float, :class:`ExprRef`) - The thickness in pixels of the color gradient. This value corresponds to the width - of a vertical gradient or the height of a horizontal gradient. - - **Default value:** ``16``. - gradientVerticalMaxLength : float - Max legend length for a vertical gradient when ``config.legend.gradientLength`` is - undefined. - - **Default value:** ``200`` - gradientVerticalMinLength : float - Min legend length for a vertical gradient when ``config.legend.gradientLength`` is - undefined. - - **Default value:** ``100`` - gridAlign : anyOf(:class:`LayoutAlign`, :class:`ExprRef`) - The alignment to apply to symbol legends rows and columns. The supported string - values are ``"all"``, ``"each"`` (the default), and ``none``. For more information, - see the `grid layout documentation `__. - - **Default value:** ``"each"``. - labelAlign : anyOf(:class:`Align`, :class:`ExprRef`) - The alignment of the legend label, can be left, center, or right. - labelBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - The position of the baseline of legend label, can be ``"top"``, ``"middle"``, - ``"bottom"``, or ``"alphabetic"``. - - **Default value:** ``"middle"``. - labelColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - The color of the legend label, can be in hex color code or regular color name. - labelFont : anyOf(string, :class:`ExprRef`) - The font of the legend label. - labelFontSize : anyOf(float, :class:`ExprRef`) - The font size of legend label. - - **Default value:** ``10``. - labelFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style of legend label. - labelFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight of legend label. - labelLimit : anyOf(float, :class:`ExprRef`) - Maximum allowed pixel width of legend tick labels. - - **Default value:** ``160``. - labelOffset : anyOf(float, :class:`ExprRef`) - The offset of the legend label. - - **Default value:** ``4``. - labelOpacity : anyOf(float, :class:`ExprRef`) - Opacity of labels. - labelOverlap : anyOf(:class:`LabelOverlap`, :class:`ExprRef`) - The strategy to use for resolving overlap of labels in gradient legends. If - ``false``, no overlap reduction is attempted. If set to ``true`` or ``"parity"``, a - strategy of removing every other label is used. If set to ``"greedy"``, a linear - scan of the labels is performed, removing any label that overlaps with the last - visible label (this often works better for log-scaled axes). - - **Default value:** ``"greedy"`` for ``log scales otherwise`` true`. - labelPadding : anyOf(float, :class:`ExprRef`) - Padding in pixels between the legend and legend labels. - labelSeparation : anyOf(float, :class:`ExprRef`) - The minimum separation that must be between label bounding boxes for them to be - considered non-overlapping (default ``0`` ). This property is ignored if - *labelOverlap* resolution is not enabled. - layout : :class:`ExprRef` - - legendX : anyOf(float, :class:`ExprRef`) - Custom x-position for legend with orient "none". - legendY : anyOf(float, :class:`ExprRef`) - Custom y-position for legend with orient "none". - offset : anyOf(float, :class:`ExprRef`) - The offset in pixels by which to displace the legend from the data rectangle and - axes. - - **Default value:** ``18``. - orient : :class:`LegendOrient` - The orientation of the legend, which determines how the legend is positioned within - the scene. One of ``"left"``, ``"right"``, ``"top"``, ``"bottom"``, ``"top-left"``, - ``"top-right"``, ``"bottom-left"``, ``"bottom-right"``, ``"none"``. - - **Default value:** ``"right"`` - padding : anyOf(float, :class:`ExprRef`) - The padding between the border and content of the legend group. - - **Default value:** ``0``. - rowPadding : anyOf(float, :class:`ExprRef`) - The vertical padding in pixels between symbol legend entries. - - **Default value:** ``2``. - strokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Border stroke color for the full legend. - strokeDash : anyOf(List(float), :class:`ExprRef`) - Border stroke dash pattern for the full legend. - strokeWidth : anyOf(float, :class:`ExprRef`) - Border stroke width for the full legend. - symbolBaseFillColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Default fill color for legend symbols. Only applied if there is no ``"fill"`` scale - color encoding for the legend. - - **Default value:** ``"transparent"``. - symbolBaseStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Default stroke color for legend symbols. Only applied if there is no ``"fill"`` - scale color encoding for the legend. - - **Default value:** ``"gray"``. - symbolDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating [stroke, space] lengths for dashed symbol strokes. - symbolDashOffset : anyOf(float, :class:`ExprRef`) - The pixel offset at which to start drawing with the symbol stroke dash array. - symbolDirection : anyOf(:class:`Orientation`, :class:`ExprRef`) - The default direction ( ``"horizontal"`` or ``"vertical"`` ) for symbol legends. - - **Default value:** ``"vertical"``. - symbolFillColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - The color of the legend symbol, - symbolLimit : anyOf(float, :class:`ExprRef`) - The maximum number of allowed entries for a symbol legend. Additional entries will - be dropped. - symbolOffset : anyOf(float, :class:`ExprRef`) - Horizontal pixel offset for legend symbols. - - **Default value:** ``0``. - symbolOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the legend symbols. - symbolSize : anyOf(float, :class:`ExprRef`) - The size of the legend symbol, in pixels. - - **Default value:** ``100``. - symbolStrokeColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Stroke color for legend symbols. - symbolStrokeWidth : anyOf(float, :class:`ExprRef`) - The width of the symbol's stroke. - - **Default value:** ``1.5``. - symbolType : anyOf(:class:`SymbolShape`, :class:`ExprRef`) - The symbol shape. One of the plotting shapes ``circle`` (default), ``square``, - ``cross``, ``diamond``, ``triangle-up``, ``triangle-down``, ``triangle-right``, or - ``triangle-left``, the line symbol ``stroke``, or one of the centered directional - shapes ``arrow``, ``wedge``, or ``triangle``. Alternatively, a custom `SVG path - string `__ can be - provided. For correct sizing, custom shape paths should be defined within a square - bounding box with coordinates ranging from -1 to 1 along both the x and y - dimensions. - - **Default value:** ``"circle"``. - tickCount : anyOf(:class:`TickCount`, :class:`ExprRef`) - The desired number of tick values for quantitative legends. - title : None - Set to null to disable title for the axis, legend, or header. - titleAlign : anyOf(:class:`Align`, :class:`ExprRef`) - Horizontal text alignment for legend titles. - - **Default value:** ``"left"``. - titleAnchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - Text anchor position for placing legend titles. - titleBaseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - Vertical text baseline for legend titles. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or ``"line-bottom"``. The - ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and - ``"bottom"``, but are calculated relative to the *lineHeight* rather than *fontSize* - alone. - - **Default value:** ``"top"``. - titleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - The color of the legend title, can be in hex color code or regular color name. - titleFont : anyOf(string, :class:`ExprRef`) - The font of the legend title. - titleFontSize : anyOf(float, :class:`ExprRef`) - The font size of the legend title. - titleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style of the legend title. - titleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight of the legend title. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - titleLimit : anyOf(float, :class:`ExprRef`) - Maximum allowed pixel width of legend titles. - - **Default value:** ``180``. - titleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line title text or title text with ``"line-top"`` or - ``"line-bottom"`` baseline. - titleOpacity : anyOf(float, :class:`ExprRef`) - Opacity of the legend title. - titleOrient : anyOf(:class:`Orient`, :class:`ExprRef`) - Orientation of the legend title. - titlePadding : anyOf(float, :class:`ExprRef`) - The padding, in pixels, between title and legend. - - **Default value:** ``5``. - unselectedOpacity : float - The opacity of unselected legend entries. - - **Default value:** 0.35. - zindex : anyOf(float, :class:`ExprRef`) - The integer z-index indicating the layering of the legend group relative to other - axis, mark, and legend groups. - """ - _schema = {'$ref': '#/definitions/LegendConfig'} - - def __init__(self, aria=Undefined, clipHeight=Undefined, columnPadding=Undefined, columns=Undefined, - cornerRadius=Undefined, description=Undefined, direction=Undefined, disable=Undefined, - fillColor=Undefined, gradientDirection=Undefined, - gradientHorizontalMaxLength=Undefined, gradientHorizontalMinLength=Undefined, - gradientLabelLimit=Undefined, gradientLabelOffset=Undefined, gradientLength=Undefined, - gradientOpacity=Undefined, gradientStrokeColor=Undefined, - gradientStrokeWidth=Undefined, gradientThickness=Undefined, - gradientVerticalMaxLength=Undefined, gradientVerticalMinLength=Undefined, - gridAlign=Undefined, labelAlign=Undefined, labelBaseline=Undefined, - labelColor=Undefined, labelFont=Undefined, labelFontSize=Undefined, - labelFontStyle=Undefined, labelFontWeight=Undefined, labelLimit=Undefined, - labelOffset=Undefined, labelOpacity=Undefined, labelOverlap=Undefined, - labelPadding=Undefined, labelSeparation=Undefined, layout=Undefined, legendX=Undefined, - legendY=Undefined, offset=Undefined, orient=Undefined, padding=Undefined, - rowPadding=Undefined, strokeColor=Undefined, strokeDash=Undefined, - strokeWidth=Undefined, symbolBaseFillColor=Undefined, symbolBaseStrokeColor=Undefined, - symbolDash=Undefined, symbolDashOffset=Undefined, symbolDirection=Undefined, - symbolFillColor=Undefined, symbolLimit=Undefined, symbolOffset=Undefined, - symbolOpacity=Undefined, symbolSize=Undefined, symbolStrokeColor=Undefined, - symbolStrokeWidth=Undefined, symbolType=Undefined, tickCount=Undefined, - title=Undefined, titleAlign=Undefined, titleAnchor=Undefined, titleBaseline=Undefined, - titleColor=Undefined, titleFont=Undefined, titleFontSize=Undefined, - titleFontStyle=Undefined, titleFontWeight=Undefined, titleLimit=Undefined, - titleLineHeight=Undefined, titleOpacity=Undefined, titleOrient=Undefined, - titlePadding=Undefined, unselectedOpacity=Undefined, zindex=Undefined, **kwds): - super(LegendConfig, self).__init__(aria=aria, clipHeight=clipHeight, - columnPadding=columnPadding, columns=columns, - cornerRadius=cornerRadius, description=description, - direction=direction, disable=disable, fillColor=fillColor, - gradientDirection=gradientDirection, - gradientHorizontalMaxLength=gradientHorizontalMaxLength, - gradientHorizontalMinLength=gradientHorizontalMinLength, - gradientLabelLimit=gradientLabelLimit, - gradientLabelOffset=gradientLabelOffset, - gradientLength=gradientLength, - gradientOpacity=gradientOpacity, - gradientStrokeColor=gradientStrokeColor, - gradientStrokeWidth=gradientStrokeWidth, - gradientThickness=gradientThickness, - gradientVerticalMaxLength=gradientVerticalMaxLength, - gradientVerticalMinLength=gradientVerticalMinLength, - gridAlign=gridAlign, labelAlign=labelAlign, - labelBaseline=labelBaseline, labelColor=labelColor, - labelFont=labelFont, labelFontSize=labelFontSize, - labelFontStyle=labelFontStyle, - labelFontWeight=labelFontWeight, labelLimit=labelLimit, - labelOffset=labelOffset, labelOpacity=labelOpacity, - labelOverlap=labelOverlap, labelPadding=labelPadding, - labelSeparation=labelSeparation, layout=layout, - legendX=legendX, legendY=legendY, offset=offset, - orient=orient, padding=padding, rowPadding=rowPadding, - strokeColor=strokeColor, strokeDash=strokeDash, - strokeWidth=strokeWidth, - symbolBaseFillColor=symbolBaseFillColor, - symbolBaseStrokeColor=symbolBaseStrokeColor, - symbolDash=symbolDash, symbolDashOffset=symbolDashOffset, - symbolDirection=symbolDirection, - symbolFillColor=symbolFillColor, symbolLimit=symbolLimit, - symbolOffset=symbolOffset, symbolOpacity=symbolOpacity, - symbolSize=symbolSize, symbolStrokeColor=symbolStrokeColor, - symbolStrokeWidth=symbolStrokeWidth, symbolType=symbolType, - tickCount=tickCount, title=title, titleAlign=titleAlign, - titleAnchor=titleAnchor, titleBaseline=titleBaseline, - titleColor=titleColor, titleFont=titleFont, - titleFontSize=titleFontSize, titleFontStyle=titleFontStyle, - titleFontWeight=titleFontWeight, titleLimit=titleLimit, - titleLineHeight=titleLineHeight, titleOpacity=titleOpacity, - titleOrient=titleOrient, titlePadding=titlePadding, - unselectedOpacity=unselectedOpacity, zindex=zindex, **kwds) - - -class LegendOrient(VegaLiteSchema): - """LegendOrient schema wrapper - - enum('none', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', - 'bottom-right') - """ - _schema = {'$ref': '#/definitions/LegendOrient'} - - def __init__(self, *args): - super(LegendOrient, self).__init__(*args) - - -class LegendResolveMap(VegaLiteSchema): - """LegendResolveMap schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - angle : :class:`ResolveMode` - - color : :class:`ResolveMode` - - fill : :class:`ResolveMode` - - fillOpacity : :class:`ResolveMode` - - opacity : :class:`ResolveMode` - - shape : :class:`ResolveMode` - - size : :class:`ResolveMode` - - stroke : :class:`ResolveMode` - - strokeDash : :class:`ResolveMode` - - strokeOpacity : :class:`ResolveMode` - - strokeWidth : :class:`ResolveMode` - - """ - _schema = {'$ref': '#/definitions/LegendResolveMap'} - - def __init__(self, angle=Undefined, color=Undefined, fill=Undefined, fillOpacity=Undefined, - opacity=Undefined, shape=Undefined, size=Undefined, stroke=Undefined, - strokeDash=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, **kwds): - super(LegendResolveMap, self).__init__(angle=angle, color=color, fill=fill, - fillOpacity=fillOpacity, opacity=opacity, shape=shape, - size=size, stroke=stroke, strokeDash=strokeDash, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - **kwds) - - -class LegendStreamBinding(LegendBinding): - """LegendStreamBinding schema wrapper - - Mapping(required=[legend]) - - Parameters - ---------- - - legend : anyOf(string, :class:`Stream`) - - """ - _schema = {'$ref': '#/definitions/LegendStreamBinding'} - - def __init__(self, legend=Undefined, **kwds): - super(LegendStreamBinding, self).__init__(legend=legend, **kwds) - - -class LineConfig(AnyMarkConfig): - """LineConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : anyOf(:class:`Align`, :class:`ExprRef`) - The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). - One of ``"left"``, ``"right"``, ``"center"``. - - **Note:** Expression reference is *not* supported for range marks. - angle : anyOf(float, :class:`ExprRef`) - The rotation angle of the text, in degrees. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG element, removing the mark item from the ARIA accessibility tree. - ariaRole : anyOf(string, :class:`ExprRef`) - Sets the type of user interface element of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "role" attribute. Warning: this - property is experimental and may be changed in the future. - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - A human-readable, author-localized description for the role of the mark item for - `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "aria-roledescription" attribute. - Warning: this property is experimental and may be changed in the future. - aspect : anyOf(boolean, :class:`ExprRef`) - Whether to keep aspect ratio of image marks. - baseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an - expression reference that provides one of the valid values. The ``"line-top"`` and - ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are - calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. - - For range marks, the vertical alignment of the marks. One of ``"top"``, - ``"middle"``, ``"bottom"``. - - **Note:** Expression reference is *not* supported for range marks. - blend : anyOf(:class:`Blend`, :class:`ExprRef`) - The color blend mode for drawing an item on its current background. Any valid `CSS - mix-blend-mode `__ - value can be used. - - __Default value:__ ``"source-over"`` - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom left corner. - - **Default value:** ``0`` - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom right corner. - - **Default value:** ``0`` - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top right corner. - - **Default value:** ``0`` - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top left corner. - - **Default value:** ``0`` - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - The mouse cursor used over the mark. Any valid `CSS cursor type - `__ can be used. - description : anyOf(string, :class:`ExprRef`) - A text description of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the `"aria-label" attribute - `__. - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` - (right-to-left). This property determines on which side is truncated in response to - the limit parameter. - - **Default value:** ``"ltr"`` - dx : anyOf(float, :class:`ExprRef`) - The horizontal offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - dy : anyOf(float, :class:`ExprRef`) - The vertical offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - ellipsis : anyOf(string, :class:`ExprRef`) - The ellipsis string for text truncated in response to the limit parameter. - - **Default value:** ``"…"`` - endAngle : anyOf(float, :class:`ExprRef`) - The end angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - filled : boolean - Whether the mark's color should be used as fill color instead of stroke color. - - **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well - as ``geoshape`` marks for `graticule - `__ data sources; - otherwise, ``true``. - - **Note:** This property cannot be used in a `style config - `__. - font : anyOf(string, :class:`ExprRef`) - The typeface to set the text in (e.g., ``"Helvetica Neue"`` ). - fontSize : anyOf(float, :class:`ExprRef`) - The font size, in pixels. - - **Default value:** ``11`` - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style (e.g., ``"italic"`` ). - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight. This can be either a string (e.g ``"bold"``, ``"normal"`` ) or a - number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and - ``"bold"`` = ``700`` ). - height : anyOf(float, :class:`ExprRef`) - Height of the marks. - href : anyOf(:class:`URI`, :class:`ExprRef`) - A URL to load upon mouse click. If defined, the mark acts as a hyperlink. - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - - **Default value:** ``0`` - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - The line interpolation method to use for line and area marks. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : alternate between horizontal and vertical segments, as in a step - function. - * ``"step-before"`` : alternate between vertical and horizontal segments, as in a - step function. - * ``"step-after"`` : alternate between horizontal and vertical segments, as in a - step function. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - limit : anyOf(float, :class:`ExprRef`) - The maximum length of the text mark in pixels. The text value will be automatically - truncated if the rendered size exceeds the limit. - - **Default value:** ``0`` -- indicating no limit - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property is ignored if the text is array-valued. - lineHeight : anyOf(float, :class:`ExprRef`) - The line height in pixels (the spacing between subsequent lines of text) for - multi-line text marks. - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - order : anyOf(None, boolean) - For line and trail marks, this ``order`` property can be set to ``null`` or - ``false`` to make the lines use the original order in the data sources. - orient : :class:`Orientation` - The orientation of a non-stacked bar, tick, area, and line charts. The value is - either horizontal (default) or vertical. - - - * For bar, rule and tick, this determines whether the size of the bar and tick - should be applied to x or y dimension. - * For area, this property determines the orient property of the Vega output. - * For line and trail marks, this property determines the sort order of the points in - the line if ``config.sortLineBy`` is not specified. For stacked charts, this is - always determined by the orientation of the stack; therefore explicitly specified - value will be ignored. - outerRadius : anyOf(float, :class:`ExprRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - - **Default value:** ``0`` - padAngle : anyOf(float, :class:`ExprRef`) - The angular padding applied to sides of the arc, in radians. - point : anyOf(boolean, :class:`OverlayMarkDef`, string) - A flag for overlaying points on top of line or area marks, or an object defining the - properties of the overlayed points. - - - If this property is ``"transparent"``, transparent points will be used (for - enhancing tooltips and selections). - - If this property is an empty object ( ``{}`` ) or ``true``, filled points with - default properties will be used. - - If this property is ``false``, no points would be automatically added to line or - area marks. - - **Default value:** ``false``. - radius : anyOf(float, :class:`ExprRef`) - For arc mark, the primary (outer) radius in pixels. - - For text marks, polar coordinate radial offset, in pixels, of the text from the - origin determined by the ``x`` and ``y`` properties. - - **Default value:** ``min(plot_width, plot_height)/2`` - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - - **Default value:** ``0`` - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - Shape of the point marks. Supported values include: - - - * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, - ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or - ``"triangle-left"``. - * the line symbol ``"stroke"`` - * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - * a custom `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - **Default value:** ``"circle"`` - size : anyOf(float, :class:`ExprRef`) - Default size for marks. - - - * For ``point`` / ``circle`` / ``square``, this represents the pixel area of the - marks. Note that this value sets the area of the symbol; the side lengths will - increase with the square root of this value. - * For ``bar``, this represents the band size of the bar, in pixels. - * For ``text``, this represents the font size, in pixels. - - **Default value:** - - - * ``30`` for point, circle, square marks; width/height's ``step`` - * ``2`` for bar marks with discrete dimensions; - * ``5`` for bar marks with continuous dimensions; - * ``11`` for text marks. - smooth : anyOf(boolean, :class:`ExprRef`) - A boolean flag (default true) indicating if the image should be smoothed when - resized. If false, individual pixels should be scaled directly rather than - interpolated with smoothing. For SVG rendering, this option may not work in some - browsers due to lack of standardization. - startAngle : anyOf(float, :class:`ExprRef`) - The start angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default stroke color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove stroke. - - **Default value:** (None) - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOffset : anyOf(float, :class:`ExprRef`) - The offset in pixels at which to draw the group stroke and fill. If unspecified, the - default behavior is to dynamically offset stroked groups such that 1 pixel stroke - widths align with the pixel grid. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - tension : anyOf(float, :class:`ExprRef`) - Depending on the interpolation type, sets the tension parameter (for line and area - marks). - text : anyOf(:class:`Text`, :class:`ExprRef`) - Placeholder text if the ``text`` channel is not specified - theta : anyOf(float, :class:`ExprRef`) - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : anyOf(float, :class:`ExprRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - timeUnitBandPosition : float - Default relative band position for a time unit. If set to ``0``, the marks will be - positioned at the beginning of the time unit band step. If set to ``0.5``, the marks - will be positioned in the middle of the time unit band step. - timeUnitBandSize : float - Default relative band size for a time unit. If set to ``1``, the bandwidth of the - marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the - marks will be half of the time unit band step. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprRef`, None) - The tooltip text string to show upon mouse hover or an object defining which fields - should the tooltip be derived from. - - - * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from - ``encoding`` will be used. - * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the - highlighted data point will be used. - * If set to ``null`` or ``false``, then no tooltip will be used. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - - **Default value:** ``null`` - url : anyOf(:class:`URI`, :class:`ExprRef`) - The URL of the image file for image marks. - width : anyOf(float, :class:`ExprRef`) - Width of the marks. - x : anyOf(float, string, :class:`ExprRef`) - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : anyOf(float, string, :class:`ExprRef`) - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - y : anyOf(float, string, :class:`ExprRef`) - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : anyOf(float, string, :class:`ExprRef`) - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - """ - _schema = {'$ref': '#/definitions/LineConfig'} - - def __init__(self, align=Undefined, angle=Undefined, aria=Undefined, ariaRole=Undefined, - ariaRoleDescription=Undefined, aspect=Undefined, baseline=Undefined, blend=Undefined, - color=Undefined, cornerRadius=Undefined, cornerRadiusBottomLeft=Undefined, - cornerRadiusBottomRight=Undefined, cornerRadiusTopLeft=Undefined, - cornerRadiusTopRight=Undefined, cursor=Undefined, description=Undefined, dir=Undefined, - dx=Undefined, dy=Undefined, ellipsis=Undefined, endAngle=Undefined, fill=Undefined, - fillOpacity=Undefined, filled=Undefined, font=Undefined, fontSize=Undefined, - fontStyle=Undefined, fontWeight=Undefined, height=Undefined, href=Undefined, - innerRadius=Undefined, interpolate=Undefined, invalid=Undefined, limit=Undefined, - lineBreak=Undefined, lineHeight=Undefined, opacity=Undefined, order=Undefined, - orient=Undefined, outerRadius=Undefined, padAngle=Undefined, point=Undefined, - radius=Undefined, radius2=Undefined, shape=Undefined, size=Undefined, smooth=Undefined, - startAngle=Undefined, stroke=Undefined, strokeCap=Undefined, strokeDash=Undefined, - strokeDashOffset=Undefined, strokeJoin=Undefined, strokeMiterLimit=Undefined, - strokeOffset=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, - tension=Undefined, text=Undefined, theta=Undefined, theta2=Undefined, - timeUnitBandPosition=Undefined, timeUnitBandSize=Undefined, tooltip=Undefined, - url=Undefined, width=Undefined, x=Undefined, x2=Undefined, y=Undefined, y2=Undefined, - **kwds): - super(LineConfig, self).__init__(align=align, angle=angle, aria=aria, ariaRole=ariaRole, - ariaRoleDescription=ariaRoleDescription, aspect=aspect, - baseline=baseline, blend=blend, color=color, - cornerRadius=cornerRadius, - cornerRadiusBottomLeft=cornerRadiusBottomLeft, - cornerRadiusBottomRight=cornerRadiusBottomRight, - cornerRadiusTopLeft=cornerRadiusTopLeft, - cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, - description=description, dir=dir, dx=dx, dy=dy, - ellipsis=ellipsis, endAngle=endAngle, fill=fill, - fillOpacity=fillOpacity, filled=filled, font=font, - fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, - height=height, href=href, innerRadius=innerRadius, - interpolate=interpolate, invalid=invalid, limit=limit, - lineBreak=lineBreak, lineHeight=lineHeight, opacity=opacity, - order=order, orient=orient, outerRadius=outerRadius, - padAngle=padAngle, point=point, radius=radius, radius2=radius2, - shape=shape, size=size, smooth=smooth, startAngle=startAngle, - stroke=stroke, strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, strokeOffset=strokeOffset, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - tension=tension, text=text, theta=theta, theta2=theta2, - timeUnitBandPosition=timeUnitBandPosition, - timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, url=url, - width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class LineString(Geometry): - """LineString schema wrapper - - Mapping(required=[coordinates, type]) - LineString geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.4 - - Parameters - ---------- - - coordinates : List(:class:`Position`) - - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/LineString'} - - def __init__(self, coordinates=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(LineString, self).__init__(coordinates=coordinates, type=type, bbox=bbox, **kwds) - - -class LinearGradient(Gradient): - """LinearGradient schema wrapper - - Mapping(required=[gradient, stops]) - - Parameters - ---------- - - gradient : string - The type of gradient. Use ``"linear"`` for a linear gradient. - stops : List(:class:`GradientStop`) - An array of gradient stops defining the gradient color sequence. - id : string - - x1 : float - The starting x-coordinate, in normalized [0, 1] coordinates, of the linear gradient. - - **Default value:** ``0`` - x2 : float - The ending x-coordinate, in normalized [0, 1] coordinates, of the linear gradient. - - **Default value:** ``1`` - y1 : float - The starting y-coordinate, in normalized [0, 1] coordinates, of the linear gradient. - - **Default value:** ``0`` - y2 : float - The ending y-coordinate, in normalized [0, 1] coordinates, of the linear gradient. - - **Default value:** ``0`` - """ - _schema = {'$ref': '#/definitions/LinearGradient'} - - def __init__(self, gradient=Undefined, stops=Undefined, id=Undefined, x1=Undefined, x2=Undefined, - y1=Undefined, y2=Undefined, **kwds): - super(LinearGradient, self).__init__(gradient=gradient, stops=stops, id=id, x1=x1, x2=x2, y1=y1, - y2=y2, **kwds) - - -class Locale(VegaLiteSchema): - """Locale schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - number : :class:`NumberLocale` - Locale definition for formatting numbers. - time : :class:`TimeLocale` - Locale definition for formatting dates and times. - """ - _schema = {'$ref': '#/definitions/Locale'} - - def __init__(self, number=Undefined, time=Undefined, **kwds): - super(Locale, self).__init__(number=number, time=time, **kwds) - - -class LookupData(VegaLiteSchema): - """LookupData schema wrapper - - Mapping(required=[data, key]) - - Parameters - ---------- - - data : :class:`Data` - Secondary data source to lookup in. - key : :class:`FieldName` - Key in data to lookup. - fields : List(:class:`FieldName`) - Fields in foreign data or selection to lookup. If not specified, the entire object - is queried. - """ - _schema = {'$ref': '#/definitions/LookupData'} - - def __init__(self, data=Undefined, key=Undefined, fields=Undefined, **kwds): - super(LookupData, self).__init__(data=data, key=key, fields=fields, **kwds) - - -class LookupSelection(VegaLiteSchema): - """LookupSelection schema wrapper - - Mapping(required=[key, param]) - - Parameters - ---------- - - key : :class:`FieldName` - Key in data to lookup. - param : :class:`ParameterName` - Selection parameter name to look up. - fields : List(:class:`FieldName`) - Fields in foreign data or selection to lookup. If not specified, the entire object - is queried. - """ - _schema = {'$ref': '#/definitions/LookupSelection'} - - def __init__(self, key=Undefined, param=Undefined, fields=Undefined, **kwds): - super(LookupSelection, self).__init__(key=key, param=param, fields=fields, **kwds) - - -class Mark(AnyMark): - """Mark schema wrapper - - enum('arc', 'area', 'bar', 'image', 'line', 'point', 'rect', 'rule', 'text', 'tick', - 'trail', 'circle', 'square', 'geoshape') - All types of primitive marks. - """ - _schema = {'$ref': '#/definitions/Mark'} - - def __init__(self, *args): - super(Mark, self).__init__(*args) - - -class MarkConfig(AnyMarkConfig): - """MarkConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : anyOf(:class:`Align`, :class:`ExprRef`) - The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). - One of ``"left"``, ``"right"``, ``"center"``. - - **Note:** Expression reference is *not* supported for range marks. - angle : anyOf(float, :class:`ExprRef`) - The rotation angle of the text, in degrees. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG element, removing the mark item from the ARIA accessibility tree. - ariaRole : anyOf(string, :class:`ExprRef`) - Sets the type of user interface element of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "role" attribute. Warning: this - property is experimental and may be changed in the future. - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - A human-readable, author-localized description for the role of the mark item for - `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "aria-roledescription" attribute. - Warning: this property is experimental and may be changed in the future. - aspect : anyOf(boolean, :class:`ExprRef`) - Whether to keep aspect ratio of image marks. - baseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an - expression reference that provides one of the valid values. The ``"line-top"`` and - ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are - calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. - - For range marks, the vertical alignment of the marks. One of ``"top"``, - ``"middle"``, ``"bottom"``. - - **Note:** Expression reference is *not* supported for range marks. - blend : anyOf(:class:`Blend`, :class:`ExprRef`) - The color blend mode for drawing an item on its current background. Any valid `CSS - mix-blend-mode `__ - value can be used. - - __Default value:__ ``"source-over"`` - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom left corner. - - **Default value:** ``0`` - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom right corner. - - **Default value:** ``0`` - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top right corner. - - **Default value:** ``0`` - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top left corner. - - **Default value:** ``0`` - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - The mouse cursor used over the mark. Any valid `CSS cursor type - `__ can be used. - description : anyOf(string, :class:`ExprRef`) - A text description of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the `"aria-label" attribute - `__. - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` - (right-to-left). This property determines on which side is truncated in response to - the limit parameter. - - **Default value:** ``"ltr"`` - dx : anyOf(float, :class:`ExprRef`) - The horizontal offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - dy : anyOf(float, :class:`ExprRef`) - The vertical offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - ellipsis : anyOf(string, :class:`ExprRef`) - The ellipsis string for text truncated in response to the limit parameter. - - **Default value:** ``"…"`` - endAngle : anyOf(float, :class:`ExprRef`) - The end angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - filled : boolean - Whether the mark's color should be used as fill color instead of stroke color. - - **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well - as ``geoshape`` marks for `graticule - `__ data sources; - otherwise, ``true``. - - **Note:** This property cannot be used in a `style config - `__. - font : anyOf(string, :class:`ExprRef`) - The typeface to set the text in (e.g., ``"Helvetica Neue"`` ). - fontSize : anyOf(float, :class:`ExprRef`) - The font size, in pixels. - - **Default value:** ``11`` - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style (e.g., ``"italic"`` ). - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight. This can be either a string (e.g ``"bold"``, ``"normal"`` ) or a - number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and - ``"bold"`` = ``700`` ). - height : anyOf(float, :class:`ExprRef`) - Height of the marks. - href : anyOf(:class:`URI`, :class:`ExprRef`) - A URL to load upon mouse click. If defined, the mark acts as a hyperlink. - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - - **Default value:** ``0`` - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - The line interpolation method to use for line and area marks. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : alternate between horizontal and vertical segments, as in a step - function. - * ``"step-before"`` : alternate between vertical and horizontal segments, as in a - step function. - * ``"step-after"`` : alternate between horizontal and vertical segments, as in a - step function. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - limit : anyOf(float, :class:`ExprRef`) - The maximum length of the text mark in pixels. The text value will be automatically - truncated if the rendered size exceeds the limit. - - **Default value:** ``0`` -- indicating no limit - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property is ignored if the text is array-valued. - lineHeight : anyOf(float, :class:`ExprRef`) - The line height in pixels (the spacing between subsequent lines of text) for - multi-line text marks. - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - order : anyOf(None, boolean) - For line and trail marks, this ``order`` property can be set to ``null`` or - ``false`` to make the lines use the original order in the data sources. - orient : :class:`Orientation` - The orientation of a non-stacked bar, tick, area, and line charts. The value is - either horizontal (default) or vertical. - - - * For bar, rule and tick, this determines whether the size of the bar and tick - should be applied to x or y dimension. - * For area, this property determines the orient property of the Vega output. - * For line and trail marks, this property determines the sort order of the points in - the line if ``config.sortLineBy`` is not specified. For stacked charts, this is - always determined by the orientation of the stack; therefore explicitly specified - value will be ignored. - outerRadius : anyOf(float, :class:`ExprRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - - **Default value:** ``0`` - padAngle : anyOf(float, :class:`ExprRef`) - The angular padding applied to sides of the arc, in radians. - radius : anyOf(float, :class:`ExprRef`) - For arc mark, the primary (outer) radius in pixels. - - For text marks, polar coordinate radial offset, in pixels, of the text from the - origin determined by the ``x`` and ``y`` properties. - - **Default value:** ``min(plot_width, plot_height)/2`` - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - - **Default value:** ``0`` - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - Shape of the point marks. Supported values include: - - - * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, - ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or - ``"triangle-left"``. - * the line symbol ``"stroke"`` - * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - * a custom `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - **Default value:** ``"circle"`` - size : anyOf(float, :class:`ExprRef`) - Default size for marks. - - - * For ``point`` / ``circle`` / ``square``, this represents the pixel area of the - marks. Note that this value sets the area of the symbol; the side lengths will - increase with the square root of this value. - * For ``bar``, this represents the band size of the bar, in pixels. - * For ``text``, this represents the font size, in pixels. - - **Default value:** - - - * ``30`` for point, circle, square marks; width/height's ``step`` - * ``2`` for bar marks with discrete dimensions; - * ``5`` for bar marks with continuous dimensions; - * ``11`` for text marks. - smooth : anyOf(boolean, :class:`ExprRef`) - A boolean flag (default true) indicating if the image should be smoothed when - resized. If false, individual pixels should be scaled directly rather than - interpolated with smoothing. For SVG rendering, this option may not work in some - browsers due to lack of standardization. - startAngle : anyOf(float, :class:`ExprRef`) - The start angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default stroke color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove stroke. - - **Default value:** (None) - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOffset : anyOf(float, :class:`ExprRef`) - The offset in pixels at which to draw the group stroke and fill. If unspecified, the - default behavior is to dynamically offset stroked groups such that 1 pixel stroke - widths align with the pixel grid. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - tension : anyOf(float, :class:`ExprRef`) - Depending on the interpolation type, sets the tension parameter (for line and area - marks). - text : anyOf(:class:`Text`, :class:`ExprRef`) - Placeholder text if the ``text`` channel is not specified - theta : anyOf(float, :class:`ExprRef`) - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : anyOf(float, :class:`ExprRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - timeUnitBandPosition : float - Default relative band position for a time unit. If set to ``0``, the marks will be - positioned at the beginning of the time unit band step. If set to ``0.5``, the marks - will be positioned in the middle of the time unit band step. - timeUnitBandSize : float - Default relative band size for a time unit. If set to ``1``, the bandwidth of the - marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the - marks will be half of the time unit band step. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprRef`, None) - The tooltip text string to show upon mouse hover or an object defining which fields - should the tooltip be derived from. - - - * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from - ``encoding`` will be used. - * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the - highlighted data point will be used. - * If set to ``null`` or ``false``, then no tooltip will be used. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - - **Default value:** ``null`` - url : anyOf(:class:`URI`, :class:`ExprRef`) - The URL of the image file for image marks. - width : anyOf(float, :class:`ExprRef`) - Width of the marks. - x : anyOf(float, string, :class:`ExprRef`) - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : anyOf(float, string, :class:`ExprRef`) - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - y : anyOf(float, string, :class:`ExprRef`) - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : anyOf(float, string, :class:`ExprRef`) - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - """ - _schema = {'$ref': '#/definitions/MarkConfig'} - - def __init__(self, align=Undefined, angle=Undefined, aria=Undefined, ariaRole=Undefined, - ariaRoleDescription=Undefined, aspect=Undefined, baseline=Undefined, blend=Undefined, - color=Undefined, cornerRadius=Undefined, cornerRadiusBottomLeft=Undefined, - cornerRadiusBottomRight=Undefined, cornerRadiusTopLeft=Undefined, - cornerRadiusTopRight=Undefined, cursor=Undefined, description=Undefined, dir=Undefined, - dx=Undefined, dy=Undefined, ellipsis=Undefined, endAngle=Undefined, fill=Undefined, - fillOpacity=Undefined, filled=Undefined, font=Undefined, fontSize=Undefined, - fontStyle=Undefined, fontWeight=Undefined, height=Undefined, href=Undefined, - innerRadius=Undefined, interpolate=Undefined, invalid=Undefined, limit=Undefined, - lineBreak=Undefined, lineHeight=Undefined, opacity=Undefined, order=Undefined, - orient=Undefined, outerRadius=Undefined, padAngle=Undefined, radius=Undefined, - radius2=Undefined, shape=Undefined, size=Undefined, smooth=Undefined, - startAngle=Undefined, stroke=Undefined, strokeCap=Undefined, strokeDash=Undefined, - strokeDashOffset=Undefined, strokeJoin=Undefined, strokeMiterLimit=Undefined, - strokeOffset=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, - tension=Undefined, text=Undefined, theta=Undefined, theta2=Undefined, - timeUnitBandPosition=Undefined, timeUnitBandSize=Undefined, tooltip=Undefined, - url=Undefined, width=Undefined, x=Undefined, x2=Undefined, y=Undefined, y2=Undefined, - **kwds): - super(MarkConfig, self).__init__(align=align, angle=angle, aria=aria, ariaRole=ariaRole, - ariaRoleDescription=ariaRoleDescription, aspect=aspect, - baseline=baseline, blend=blend, color=color, - cornerRadius=cornerRadius, - cornerRadiusBottomLeft=cornerRadiusBottomLeft, - cornerRadiusBottomRight=cornerRadiusBottomRight, - cornerRadiusTopLeft=cornerRadiusTopLeft, - cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, - description=description, dir=dir, dx=dx, dy=dy, - ellipsis=ellipsis, endAngle=endAngle, fill=fill, - fillOpacity=fillOpacity, filled=filled, font=font, - fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, - height=height, href=href, innerRadius=innerRadius, - interpolate=interpolate, invalid=invalid, limit=limit, - lineBreak=lineBreak, lineHeight=lineHeight, opacity=opacity, - order=order, orient=orient, outerRadius=outerRadius, - padAngle=padAngle, radius=radius, radius2=radius2, shape=shape, - size=size, smooth=smooth, startAngle=startAngle, stroke=stroke, - strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, strokeOffset=strokeOffset, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - tension=tension, text=text, theta=theta, theta2=theta2, - timeUnitBandPosition=timeUnitBandPosition, - timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, url=url, - width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class MarkDef(AnyMark): - """MarkDef schema wrapper - - Mapping(required=[type]) - - Parameters - ---------- - - type : :class:`Mark` - The mark type. This could a primitive mark type (one of ``"bar"``, ``"circle"``, - ``"square"``, ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"geoshape"``, - ``"rule"``, and ``"text"`` ) or a composite mark type ( ``"boxplot"``, - ``"errorband"``, ``"errorbar"`` ). - align : anyOf(:class:`Align`, :class:`ExprRef`) - The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). - One of ``"left"``, ``"right"``, ``"center"``. - - **Note:** Expression reference is *not* supported for range marks. - angle : anyOf(float, :class:`ExprRef`) - The rotation angle of the text, in degrees. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG element, removing the mark item from the ARIA accessibility tree. - ariaRole : anyOf(string, :class:`ExprRef`) - Sets the type of user interface element of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "role" attribute. Warning: this - property is experimental and may be changed in the future. - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - A human-readable, author-localized description for the role of the mark item for - `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "aria-roledescription" attribute. - Warning: this property is experimental and may be changed in the future. - aspect : anyOf(boolean, :class:`ExprRef`) - Whether to keep aspect ratio of image marks. - bandSize : float - The width of the ticks. - - **Default value:** 3/4 of step (width step for horizontal ticks and height step for - vertical ticks). - baseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an - expression reference that provides one of the valid values. The ``"line-top"`` and - ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are - calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. - - For range marks, the vertical alignment of the marks. One of ``"top"``, - ``"middle"``, ``"bottom"``. - - **Note:** Expression reference is *not* supported for range marks. - binSpacing : float - Offset between bars for binned field. The ideal value for this is either 0 - (preferred by statisticians) or 1 (Vega-Lite default, D3 example style). - - **Default value:** ``1`` - blend : anyOf(:class:`Blend`, :class:`ExprRef`) - The color blend mode for drawing an item on its current background. Any valid `CSS - mix-blend-mode `__ - value can be used. - - __Default value:__ ``"source-over"`` - clip : boolean - Whether a mark be clipped to the enclosing group’s width and height. - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - continuousBandSize : float - The default size of the bars on continuous scales. - - **Default value:** ``5`` - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom left corner. - - **Default value:** ``0`` - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom right corner. - - **Default value:** ``0`` - cornerRadiusEnd : anyOf(float, :class:`ExprRef`) - For vertical bars, top-left and top-right corner radius. - - For horizontal bars, top-right and bottom-right corner radius. - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top right corner. - - **Default value:** ``0`` - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top left corner. - - **Default value:** ``0`` - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - The mouse cursor used over the mark. Any valid `CSS cursor type - `__ can be used. - description : anyOf(string, :class:`ExprRef`) - A text description of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the `"aria-label" attribute - `__. - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` - (right-to-left). This property determines on which side is truncated in response to - the limit parameter. - - **Default value:** ``"ltr"`` - discreteBandSize : anyOf(float, :class:`RelativeBandSize`) - The default size of the bars with discrete dimensions. If unspecified, the default - size is ``step-2``, which provides 2 pixel offset between bars. - dx : anyOf(float, :class:`ExprRef`) - The horizontal offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - dy : anyOf(float, :class:`ExprRef`) - The vertical offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - ellipsis : anyOf(string, :class:`ExprRef`) - The ellipsis string for text truncated in response to the limit parameter. - - **Default value:** ``"…"`` - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - filled : boolean - Whether the mark's color should be used as fill color instead of stroke color. - - **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well - as ``geoshape`` marks for `graticule - `__ data sources; - otherwise, ``true``. - - **Note:** This property cannot be used in a `style config - `__. - font : anyOf(string, :class:`ExprRef`) - The typeface to set the text in (e.g., ``"Helvetica Neue"`` ). - fontSize : anyOf(float, :class:`ExprRef`) - The font size, in pixels. - - **Default value:** ``11`` - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style (e.g., ``"italic"`` ). - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight. This can be either a string (e.g ``"bold"``, ``"normal"`` ) or a - number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and - ``"bold"`` = ``700`` ). - height : anyOf(float, :class:`ExprRef`, :class:`RelativeBandSize`) - Height of the marks. One of: - - - A number representing a fixed pixel height. - - A relative band size definition. For example, ``{band: 0.5}`` represents half of - the band - href : anyOf(:class:`URI`, :class:`ExprRef`) - A URL to load upon mouse click. If defined, the mark acts as a hyperlink. - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - - **Default value:** ``0`` - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - The line interpolation method to use for line and area marks. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : alternate between horizontal and vertical segments, as in a step - function. - * ``"step-before"`` : alternate between vertical and horizontal segments, as in a - step function. - * ``"step-after"`` : alternate between horizontal and vertical segments, as in a - step function. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - limit : anyOf(float, :class:`ExprRef`) - The maximum length of the text mark in pixels. The text value will be automatically - truncated if the rendered size exceeds the limit. - - **Default value:** ``0`` -- indicating no limit - line : anyOf(boolean, :class:`OverlayMarkDef`) - A flag for overlaying line on top of area marks, or an object defining the - properties of the overlayed lines. - - - If this value is an empty object ( ``{}`` ) or ``true``, lines with default - properties will be used. - - If this value is ``false``, no lines would be automatically added to area marks. - - **Default value:** ``false``. - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property is ignored if the text is array-valued. - lineHeight : anyOf(float, :class:`ExprRef`) - The line height in pixels (the spacing between subsequent lines of text) for - multi-line text marks. - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - order : anyOf(None, boolean) - For line and trail marks, this ``order`` property can be set to ``null`` or - ``false`` to make the lines use the original order in the data sources. - orient : :class:`Orientation` - The orientation of a non-stacked bar, tick, area, and line charts. The value is - either horizontal (default) or vertical. - - - * For bar, rule and tick, this determines whether the size of the bar and tick - should be applied to x or y dimension. - * For area, this property determines the orient property of the Vega output. - * For line and trail marks, this property determines the sort order of the points in - the line if ``config.sortLineBy`` is not specified. For stacked charts, this is - always determined by the orientation of the stack; therefore explicitly specified - value will be ignored. - outerRadius : anyOf(float, :class:`ExprRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - - **Default value:** ``0`` - padAngle : anyOf(float, :class:`ExprRef`) - The angular padding applied to sides of the arc, in radians. - point : anyOf(boolean, :class:`OverlayMarkDef`, string) - A flag for overlaying points on top of line or area marks, or an object defining the - properties of the overlayed points. - - - If this property is ``"transparent"``, transparent points will be used (for - enhancing tooltips and selections). - - If this property is an empty object ( ``{}`` ) or ``true``, filled points with - default properties will be used. - - If this property is ``false``, no points would be automatically added to line or - area marks. - - **Default value:** ``false``. - radius : anyOf(float, :class:`ExprRef`) - For arc mark, the primary (outer) radius in pixels. - - For text marks, polar coordinate radial offset, in pixels, of the text from the - origin determined by the ``x`` and ``y`` properties. - - **Default value:** ``min(plot_width, plot_height)/2`` - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - - **Default value:** ``0`` - radius2Offset : anyOf(float, :class:`ExprRef`) - Offset for radius2. - radiusOffset : anyOf(float, :class:`ExprRef`) - Offset for radius. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - Shape of the point marks. Supported values include: - - - * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, - ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or - ``"triangle-left"``. - * the line symbol ``"stroke"`` - * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - * a custom `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - **Default value:** ``"circle"`` - size : anyOf(float, :class:`ExprRef`) - Default size for marks. - - - * For ``point`` / ``circle`` / ``square``, this represents the pixel area of the - marks. Note that this value sets the area of the symbol; the side lengths will - increase with the square root of this value. - * For ``bar``, this represents the band size of the bar, in pixels. - * For ``text``, this represents the font size, in pixels. - - **Default value:** - - - * ``30`` for point, circle, square marks; width/height's ``step`` - * ``2`` for bar marks with discrete dimensions; - * ``5`` for bar marks with continuous dimensions; - * ``11`` for text marks. - smooth : anyOf(boolean, :class:`ExprRef`) - A boolean flag (default true) indicating if the image should be smoothed when - resized. If false, individual pixels should be scaled directly rather than - interpolated with smoothing. For SVG rendering, this option may not work in some - browsers due to lack of standardization. - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default stroke color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove stroke. - - **Default value:** (None) - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOffset : anyOf(float, :class:`ExprRef`) - The offset in pixels at which to draw the group stroke and fill. If unspecified, the - default behavior is to dynamically offset stroked groups such that 1 pixel stroke - widths align with the pixel grid. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - style : anyOf(string, List(string)) - A string or array of strings indicating the name of custom styles to apply to the - mark. A style is a named collection of mark property defaults defined within the - `style configuration - `__. If style is an - array, later styles will override earlier styles. Any `mark properties - `__ explicitly - defined within the ``encoding`` will override a style default. - - **Default value:** The mark's name. For example, a bar mark will have style - ``"bar"`` by default. **Note:** Any specified style will augment the default style. - For example, a bar mark with ``"style": "foo"`` will receive from - ``config.style.bar`` and ``config.style.foo`` (the specified style ``"foo"`` has - higher precedence). - tension : anyOf(float, :class:`ExprRef`) - Depending on the interpolation type, sets the tension parameter (for line and area - marks). - text : anyOf(:class:`Text`, :class:`ExprRef`) - Placeholder text if the ``text`` channel is not specified - theta : anyOf(float, :class:`ExprRef`) - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : anyOf(float, :class:`ExprRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - theta2Offset : anyOf(float, :class:`ExprRef`) - Offset for theta2. - thetaOffset : anyOf(float, :class:`ExprRef`) - Offset for theta. - thickness : float - Thickness of the tick mark. - - **Default value:** ``1`` - timeUnitBandPosition : float - Default relative band position for a time unit. If set to ``0``, the marks will be - positioned at the beginning of the time unit band step. If set to ``0.5``, the marks - will be positioned in the middle of the time unit band step. - timeUnitBandSize : float - Default relative band size for a time unit. If set to ``1``, the bandwidth of the - marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the - marks will be half of the time unit band step. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprRef`, None) - The tooltip text string to show upon mouse hover or an object defining which fields - should the tooltip be derived from. - - - * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from - ``encoding`` will be used. - * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the - highlighted data point will be used. - * If set to ``null`` or ``false``, then no tooltip will be used. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - - **Default value:** ``null`` - url : anyOf(:class:`URI`, :class:`ExprRef`) - The URL of the image file for image marks. - width : anyOf(float, :class:`ExprRef`, :class:`RelativeBandSize`) - Width of the marks. One of: - - - A number representing a fixed pixel width. - - A relative band size definition. For example, ``{band: 0.5}`` represents half of - the band. - x : anyOf(float, string, :class:`ExprRef`) - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : anyOf(float, string, :class:`ExprRef`) - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2Offset : anyOf(float, :class:`ExprRef`) - Offset for x2-position. - xOffset : anyOf(float, :class:`ExprRef`) - Offset for x-position. - y : anyOf(float, string, :class:`ExprRef`) - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : anyOf(float, string, :class:`ExprRef`) - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2Offset : anyOf(float, :class:`ExprRef`) - Offset for y2-position. - yOffset : anyOf(float, :class:`ExprRef`) - Offset for y-position. - """ - _schema = {'$ref': '#/definitions/MarkDef'} - - def __init__(self, type=Undefined, align=Undefined, angle=Undefined, aria=Undefined, - ariaRole=Undefined, ariaRoleDescription=Undefined, aspect=Undefined, - bandSize=Undefined, baseline=Undefined, binSpacing=Undefined, blend=Undefined, - clip=Undefined, color=Undefined, continuousBandSize=Undefined, cornerRadius=Undefined, - cornerRadiusBottomLeft=Undefined, cornerRadiusBottomRight=Undefined, - cornerRadiusEnd=Undefined, cornerRadiusTopLeft=Undefined, - cornerRadiusTopRight=Undefined, cursor=Undefined, description=Undefined, dir=Undefined, - discreteBandSize=Undefined, dx=Undefined, dy=Undefined, ellipsis=Undefined, - fill=Undefined, fillOpacity=Undefined, filled=Undefined, font=Undefined, - fontSize=Undefined, fontStyle=Undefined, fontWeight=Undefined, height=Undefined, - href=Undefined, innerRadius=Undefined, interpolate=Undefined, invalid=Undefined, - limit=Undefined, line=Undefined, lineBreak=Undefined, lineHeight=Undefined, - opacity=Undefined, order=Undefined, orient=Undefined, outerRadius=Undefined, - padAngle=Undefined, point=Undefined, radius=Undefined, radius2=Undefined, - radius2Offset=Undefined, radiusOffset=Undefined, shape=Undefined, size=Undefined, - smooth=Undefined, stroke=Undefined, strokeCap=Undefined, strokeDash=Undefined, - strokeDashOffset=Undefined, strokeJoin=Undefined, strokeMiterLimit=Undefined, - strokeOffset=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, - style=Undefined, tension=Undefined, text=Undefined, theta=Undefined, theta2=Undefined, - theta2Offset=Undefined, thetaOffset=Undefined, thickness=Undefined, - timeUnitBandPosition=Undefined, timeUnitBandSize=Undefined, tooltip=Undefined, - url=Undefined, width=Undefined, x=Undefined, x2=Undefined, x2Offset=Undefined, - xOffset=Undefined, y=Undefined, y2=Undefined, y2Offset=Undefined, yOffset=Undefined, - **kwds): - super(MarkDef, self).__init__(type=type, align=align, angle=angle, aria=aria, ariaRole=ariaRole, - ariaRoleDescription=ariaRoleDescription, aspect=aspect, - bandSize=bandSize, baseline=baseline, binSpacing=binSpacing, - blend=blend, clip=clip, color=color, - continuousBandSize=continuousBandSize, cornerRadius=cornerRadius, - cornerRadiusBottomLeft=cornerRadiusBottomLeft, - cornerRadiusBottomRight=cornerRadiusBottomRight, - cornerRadiusEnd=cornerRadiusEnd, - cornerRadiusTopLeft=cornerRadiusTopLeft, - cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, - description=description, dir=dir, - discreteBandSize=discreteBandSize, dx=dx, dy=dy, - ellipsis=ellipsis, fill=fill, fillOpacity=fillOpacity, - filled=filled, font=font, fontSize=fontSize, fontStyle=fontStyle, - fontWeight=fontWeight, height=height, href=href, - innerRadius=innerRadius, interpolate=interpolate, invalid=invalid, - limit=limit, line=line, lineBreak=lineBreak, - lineHeight=lineHeight, opacity=opacity, order=order, - orient=orient, outerRadius=outerRadius, padAngle=padAngle, - point=point, radius=radius, radius2=radius2, - radius2Offset=radius2Offset, radiusOffset=radiusOffset, - shape=shape, size=size, smooth=smooth, stroke=stroke, - strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, strokeOffset=strokeOffset, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, style=style, - tension=tension, text=text, theta=theta, theta2=theta2, - theta2Offset=theta2Offset, thetaOffset=thetaOffset, - thickness=thickness, timeUnitBandPosition=timeUnitBandPosition, - timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, url=url, - width=width, x=x, x2=x2, x2Offset=x2Offset, xOffset=xOffset, y=y, - y2=y2, y2Offset=y2Offset, yOffset=yOffset, **kwds) - - -class MarkPropDefGradientstringnull(VegaLiteSchema): - """MarkPropDefGradientstringnull schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull`, - :class:`FieldOrDatumDefWithConditionDatumDefGradientstringnull`, - :class:`ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull`) - """ - _schema = {'$ref': '#/definitions/MarkPropDef<(Gradient|string|null)>'} - - def __init__(self, *args, **kwds): - super(MarkPropDefGradientstringnull, self).__init__(*args, **kwds) - - -class FieldOrDatumDefWithConditionDatumDefGradientstringnull(ColorDef, MarkPropDefGradientstringnull): - """FieldOrDatumDefWithConditionDatumDefGradientstringnull schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - condition : anyOf(:class:`ConditionalValueDefGradientstringnullExprRef`, List(:class:`ConditionalValueDefGradientstringnullExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, bandPosition=Undefined, condition=Undefined, datum=Undefined, title=Undefined, - type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionDatumDefGradientstringnull, self).__init__(bandPosition=bandPosition, - condition=condition, - datum=datum, - title=title, - type=type, **kwds) - - -class FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull(ColorDef, MarkPropDefGradientstringnull): - """FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - condition : anyOf(:class:`ConditionalValueDefGradientstringnullExprRef`, List(:class:`ConditionalValueDefGradientstringnullExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - legend : anyOf(:class:`Legend`, None) - An object defining properties of the legend. If ``null``, the legend for the - encoding channel will be removed. - - **Default value:** If undefined, default `legend properties - `__ are applied. - - **See also:** `legend `__ - documentation. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - sort : :class:`Sort` - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A string indicating an encoding channel name to sort by - `__ (e.g., - ``"x"`` or ``"y"`` ) with an optional minus prefix for descending sort (e.g., - ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a - sort-by-encoding definition - `__. For - example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": - "descending"}``. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` and sorting by another channel is not supported for ``row`` and - ``column``. - - **See also:** `sort `__ - documentation. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, legend=Undefined, scale=Undefined, sort=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull, self).__init__(aggregate=aggregate, - bandPosition=bandPosition, - bin=bin, - condition=condition, - field=field, - legend=legend, - scale=scale, - sort=sort, - timeUnit=timeUnit, - title=title, - type=type, - **kwds) - - -class MarkPropDefnumber(VegaLiteSchema): - """MarkPropDefnumber schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, - :class:`FieldOrDatumDefWithConditionDatumDefnumber`, - :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumber`) - """ - _schema = {'$ref': '#/definitions/MarkPropDef'} - - def __init__(self, *args, **kwds): - super(MarkPropDefnumber, self).__init__(*args, **kwds) - - -class MarkPropDefnumberArray(VegaLiteSchema): - """MarkPropDefnumberArray schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray`, - :class:`FieldOrDatumDefWithConditionDatumDefnumberArray`, - :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray`) - """ - _schema = {'$ref': '#/definitions/MarkPropDef'} - - def __init__(self, *args, **kwds): - super(MarkPropDefnumberArray, self).__init__(*args, **kwds) - - -class MarkPropDefstringnullTypeForShape(VegaLiteSchema): - """MarkPropDefstringnullTypeForShape schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull`, - :class:`FieldOrDatumDefWithConditionDatumDefstringnull`, - :class:`ValueDefWithConditionMarkPropFieldOrDatumDefTypeForShapestringnull`) - """ - _schema = {'$ref': '#/definitions/MarkPropDef<(string|null),TypeForShape>'} - - def __init__(self, *args, **kwds): - super(MarkPropDefstringnullTypeForShape, self).__init__(*args, **kwds) - - -class MarkType(VegaLiteSchema): - """MarkType schema wrapper - - enum('arc', 'area', 'image', 'group', 'line', 'path', 'rect', 'rule', 'shape', 'symbol', - 'text', 'trail') - """ - _schema = {'$ref': '#/definitions/MarkType'} - - def __init__(self, *args): - super(MarkType, self).__init__(*args) - - -class Month(VegaLiteSchema): - """Month schema wrapper - - float - """ - _schema = {'$ref': '#/definitions/Month'} - - def __init__(self, *args): - super(Month, self).__init__(*args) - - -class MultiLineString(Geometry): - """MultiLineString schema wrapper - - Mapping(required=[coordinates, type]) - MultiLineString geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.5 - - Parameters - ---------- - - coordinates : List(List(:class:`Position`)) - - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/MultiLineString'} - - def __init__(self, coordinates=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(MultiLineString, self).__init__(coordinates=coordinates, type=type, bbox=bbox, **kwds) - - -class MultiPoint(Geometry): - """MultiPoint schema wrapper - - Mapping(required=[coordinates, type]) - MultiPoint geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.3 - - Parameters - ---------- - - coordinates : List(:class:`Position`) - - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/MultiPoint'} - - def __init__(self, coordinates=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(MultiPoint, self).__init__(coordinates=coordinates, type=type, bbox=bbox, **kwds) - - -class MultiPolygon(Geometry): - """MultiPolygon schema wrapper - - Mapping(required=[coordinates, type]) - MultiPolygon geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.7 - - Parameters - ---------- - - coordinates : List(List(List(:class:`Position`))) - - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/MultiPolygon'} - - def __init__(self, coordinates=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(MultiPolygon, self).__init__(coordinates=coordinates, type=type, bbox=bbox, **kwds) - - -class NamedData(DataSource): - """NamedData schema wrapper - - Mapping(required=[name]) - - Parameters - ---------- - - name : string - Provide a placeholder name and bind data at runtime. - - New data may change the layout but Vega does not always resize the chart. To update - the layout when the data updates, set `autosize - `__ or explicitly use - `view.resize `__. - format : :class:`DataFormat` - An object that specifies the format for parsing the data. - """ - _schema = {'$ref': '#/definitions/NamedData'} - - def __init__(self, name=Undefined, format=Undefined, **kwds): - super(NamedData, self).__init__(name=name, format=format, **kwds) - - -class NonArgAggregateOp(Aggregate): - """NonArgAggregateOp schema wrapper - - enum('average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', - 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', - 'variancep') - """ - _schema = {'$ref': '#/definitions/NonArgAggregateOp'} - - def __init__(self, *args): - super(NonArgAggregateOp, self).__init__(*args) - - -class NonNormalizedSpec(VegaLiteSchema): - """NonNormalizedSpec schema wrapper - - anyOf(:class:`FacetedUnitSpec`, :class:`LayerSpec`, :class:`RepeatSpec`, :class:`FacetSpec`, - :class:`ConcatSpecGenericSpec`, :class:`VConcatSpecGenericSpec`, - :class:`HConcatSpecGenericSpec`) - Any specification in Vega-Lite. - """ - _schema = {'$ref': '#/definitions/NonNormalizedSpec'} - - def __init__(self, *args, **kwds): - super(NonNormalizedSpec, self).__init__(*args, **kwds) - - -class NumberLocale(VegaLiteSchema): - """NumberLocale schema wrapper - - Mapping(required=[decimal, thousands, grouping, currency]) - Locale definition for formatting numbers. - - Parameters - ---------- - - currency : :class:`Vector2string` - The currency prefix and suffix (e.g., ["$", ""]). - decimal : string - The decimal point (e.g., "."). - grouping : List(float) - The array of group sizes (e.g., [3]), cycled as needed. - thousands : string - The group separator (e.g., ","). - minus : string - The minus sign (defaults to hyphen-minus, "-"). - nan : string - The not-a-number value (defaults to "NaN"). - numerals : :class:`Vector10string` - An array of ten strings to replace the numerals 0-9. - percent : string - The percent sign (defaults to "%"). - """ - _schema = {'$ref': '#/definitions/NumberLocale'} - - def __init__(self, currency=Undefined, decimal=Undefined, grouping=Undefined, thousands=Undefined, - minus=Undefined, nan=Undefined, numerals=Undefined, percent=Undefined, **kwds): - super(NumberLocale, self).__init__(currency=currency, decimal=decimal, grouping=grouping, - thousands=thousands, minus=minus, nan=nan, numerals=numerals, - percent=percent, **kwds) - - -class NumericArrayMarkPropDef(VegaLiteSchema): - """NumericArrayMarkPropDef schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray`, - :class:`FieldOrDatumDefWithConditionDatumDefnumberArray`, - :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray`) - """ - _schema = {'$ref': '#/definitions/NumericArrayMarkPropDef'} - - def __init__(self, *args, **kwds): - super(NumericArrayMarkPropDef, self).__init__(*args, **kwds) - - -class FieldOrDatumDefWithConditionDatumDefnumberArray(MarkPropDefnumberArray, NumericArrayMarkPropDef): - """FieldOrDatumDefWithConditionDatumDefnumberArray schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - condition : anyOf(:class:`ConditionalValueDefnumberArrayExprRef`, List(:class:`ConditionalValueDefnumberArrayExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, bandPosition=Undefined, condition=Undefined, datum=Undefined, title=Undefined, - type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionDatumDefnumberArray, self).__init__(bandPosition=bandPosition, - condition=condition, - datum=datum, title=title, - type=type, **kwds) - - -class FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray(MarkPropDefnumberArray, NumericArrayMarkPropDef): - """FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - condition : anyOf(:class:`ConditionalValueDefnumberArrayExprRef`, List(:class:`ConditionalValueDefnumberArrayExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - legend : anyOf(:class:`Legend`, None) - An object defining properties of the legend. If ``null``, the legend for the - encoding channel will be removed. - - **Default value:** If undefined, default `legend properties - `__ are applied. - - **See also:** `legend `__ - documentation. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - sort : :class:`Sort` - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A string indicating an encoding channel name to sort by - `__ (e.g., - ``"x"`` or ``"y"`` ) with an optional minus prefix for descending sort (e.g., - ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a - sort-by-encoding definition - `__. For - example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": - "descending"}``. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` and sorting by another channel is not supported for ``row`` and - ``column``. - - **See also:** `sort `__ - documentation. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, legend=Undefined, scale=Undefined, sort=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray, self).__init__(aggregate=aggregate, - bandPosition=bandPosition, - bin=bin, - condition=condition, - field=field, - legend=legend, - scale=scale, - sort=sort, - timeUnit=timeUnit, - title=title, - type=type, **kwds) - - -class NumericMarkPropDef(VegaLiteSchema): - """NumericMarkPropDef schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, - :class:`FieldOrDatumDefWithConditionDatumDefnumber`, - :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumber`) - """ - _schema = {'$ref': '#/definitions/NumericMarkPropDef'} - - def __init__(self, *args, **kwds): - super(NumericMarkPropDef, self).__init__(*args, **kwds) - - -class FieldOrDatumDefWithConditionDatumDefnumber(MarkPropDefnumber, NumericMarkPropDef): - """FieldOrDatumDefWithConditionDatumDefnumber schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - condition : anyOf(:class:`ConditionalValueDefnumberExprRef`, List(:class:`ConditionalValueDefnumberExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, bandPosition=Undefined, condition=Undefined, datum=Undefined, title=Undefined, - type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionDatumDefnumber, self).__init__(bandPosition=bandPosition, - condition=condition, - datum=datum, title=title, - type=type, **kwds) - - -class FieldOrDatumDefWithConditionMarkPropFieldDefnumber(MarkPropDefnumber, NumericMarkPropDef): - """FieldOrDatumDefWithConditionMarkPropFieldDefnumber schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - condition : anyOf(:class:`ConditionalValueDefnumberExprRef`, List(:class:`ConditionalValueDefnumberExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - legend : anyOf(:class:`Legend`, None) - An object defining properties of the legend. If ``null``, the legend for the - encoding channel will be removed. - - **Default value:** If undefined, default `legend properties - `__ are applied. - - **See also:** `legend `__ - documentation. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - sort : :class:`Sort` - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A string indicating an encoding channel name to sort by - `__ (e.g., - ``"x"`` or ``"y"`` ) with an optional minus prefix for descending sort (e.g., - ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a - sort-by-encoding definition - `__. For - example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": - "descending"}``. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` and sorting by another channel is not supported for ``row`` and - ``column``. - - **See also:** `sort `__ - documentation. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, legend=Undefined, scale=Undefined, sort=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionMarkPropFieldDefnumber, self).__init__(aggregate=aggregate, - bandPosition=bandPosition, - bin=bin, - condition=condition, - field=field, - legend=legend, - scale=scale, sort=sort, - timeUnit=timeUnit, - title=title, type=type, - **kwds) - - -class OffsetDef(VegaLiteSchema): - """OffsetDef schema wrapper - - anyOf(:class:`ScaleFieldDef`, :class:`ScaleDatumDef`, :class:`ValueDefnumber`) - """ - _schema = {'$ref': '#/definitions/OffsetDef'} - - def __init__(self, *args, **kwds): - super(OffsetDef, self).__init__(*args, **kwds) - - -class OrderFieldDef(VegaLiteSchema): - """OrderFieldDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - sort : :class:`SortOrder` - The sort order. One of ``"ascending"`` (default) or ``"descending"``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/OrderFieldDef'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - sort=Undefined, timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(OrderFieldDef, self).__init__(aggregate=aggregate, bandPosition=bandPosition, bin=bin, - field=field, sort=sort, timeUnit=timeUnit, title=title, - type=type, **kwds) - - -class OrderValueDef(VegaLiteSchema): - """OrderValueDef schema wrapper - - Mapping(required=[value]) - - Parameters - ---------- - - value : anyOf(float, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - condition : anyOf(:class:`ConditionalValueDefnumber`, List(:class:`ConditionalValueDefnumber`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - """ - _schema = {'$ref': '#/definitions/OrderValueDef'} - - def __init__(self, value=Undefined, condition=Undefined, **kwds): - super(OrderValueDef, self).__init__(value=value, condition=condition, **kwds) - - -class Orient(VegaLiteSchema): - """Orient schema wrapper - - enum('left', 'right', 'top', 'bottom') - """ - _schema = {'$ref': '#/definitions/Orient'} - - def __init__(self, *args): - super(Orient, self).__init__(*args) - - -class Orientation(VegaLiteSchema): - """Orientation schema wrapper - - enum('horizontal', 'vertical') - """ - _schema = {'$ref': '#/definitions/Orientation'} - - def __init__(self, *args): - super(Orientation, self).__init__(*args) - - -class OverlayMarkDef(VegaLiteSchema): - """OverlayMarkDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : anyOf(:class:`Align`, :class:`ExprRef`) - The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). - One of ``"left"``, ``"right"``, ``"center"``. - - **Note:** Expression reference is *not* supported for range marks. - angle : anyOf(float, :class:`ExprRef`) - The rotation angle of the text, in degrees. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG element, removing the mark item from the ARIA accessibility tree. - ariaRole : anyOf(string, :class:`ExprRef`) - Sets the type of user interface element of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "role" attribute. Warning: this - property is experimental and may be changed in the future. - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - A human-readable, author-localized description for the role of the mark item for - `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "aria-roledescription" attribute. - Warning: this property is experimental and may be changed in the future. - aspect : anyOf(boolean, :class:`ExprRef`) - Whether to keep aspect ratio of image marks. - baseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an - expression reference that provides one of the valid values. The ``"line-top"`` and - ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are - calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. - - For range marks, the vertical alignment of the marks. One of ``"top"``, - ``"middle"``, ``"bottom"``. - - **Note:** Expression reference is *not* supported for range marks. - blend : anyOf(:class:`Blend`, :class:`ExprRef`) - The color blend mode for drawing an item on its current background. Any valid `CSS - mix-blend-mode `__ - value can be used. - - __Default value:__ ``"source-over"`` - clip : boolean - Whether a mark be clipped to the enclosing group’s width and height. - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom left corner. - - **Default value:** ``0`` - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom right corner. - - **Default value:** ``0`` - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top right corner. - - **Default value:** ``0`` - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top left corner. - - **Default value:** ``0`` - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - The mouse cursor used over the mark. Any valid `CSS cursor type - `__ can be used. - description : anyOf(string, :class:`ExprRef`) - A text description of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the `"aria-label" attribute - `__. - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` - (right-to-left). This property determines on which side is truncated in response to - the limit parameter. - - **Default value:** ``"ltr"`` - dx : anyOf(float, :class:`ExprRef`) - The horizontal offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - dy : anyOf(float, :class:`ExprRef`) - The vertical offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - ellipsis : anyOf(string, :class:`ExprRef`) - The ellipsis string for text truncated in response to the limit parameter. - - **Default value:** ``"…"`` - endAngle : anyOf(float, :class:`ExprRef`) - The end angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - filled : boolean - Whether the mark's color should be used as fill color instead of stroke color. - - **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well - as ``geoshape`` marks for `graticule - `__ data sources; - otherwise, ``true``. - - **Note:** This property cannot be used in a `style config - `__. - font : anyOf(string, :class:`ExprRef`) - The typeface to set the text in (e.g., ``"Helvetica Neue"`` ). - fontSize : anyOf(float, :class:`ExprRef`) - The font size, in pixels. - - **Default value:** ``11`` - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style (e.g., ``"italic"`` ). - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight. This can be either a string (e.g ``"bold"``, ``"normal"`` ) or a - number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and - ``"bold"`` = ``700`` ). - height : anyOf(float, :class:`ExprRef`) - Height of the marks. - href : anyOf(:class:`URI`, :class:`ExprRef`) - A URL to load upon mouse click. If defined, the mark acts as a hyperlink. - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - - **Default value:** ``0`` - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - The line interpolation method to use for line and area marks. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : alternate between horizontal and vertical segments, as in a step - function. - * ``"step-before"`` : alternate between vertical and horizontal segments, as in a - step function. - * ``"step-after"`` : alternate between horizontal and vertical segments, as in a - step function. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - limit : anyOf(float, :class:`ExprRef`) - The maximum length of the text mark in pixels. The text value will be automatically - truncated if the rendered size exceeds the limit. - - **Default value:** ``0`` -- indicating no limit - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property is ignored if the text is array-valued. - lineHeight : anyOf(float, :class:`ExprRef`) - The line height in pixels (the spacing between subsequent lines of text) for - multi-line text marks. - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - order : anyOf(None, boolean) - For line and trail marks, this ``order`` property can be set to ``null`` or - ``false`` to make the lines use the original order in the data sources. - orient : :class:`Orientation` - The orientation of a non-stacked bar, tick, area, and line charts. The value is - either horizontal (default) or vertical. - - - * For bar, rule and tick, this determines whether the size of the bar and tick - should be applied to x or y dimension. - * For area, this property determines the orient property of the Vega output. - * For line and trail marks, this property determines the sort order of the points in - the line if ``config.sortLineBy`` is not specified. For stacked charts, this is - always determined by the orientation of the stack; therefore explicitly specified - value will be ignored. - outerRadius : anyOf(float, :class:`ExprRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - - **Default value:** ``0`` - padAngle : anyOf(float, :class:`ExprRef`) - The angular padding applied to sides of the arc, in radians. - radius : anyOf(float, :class:`ExprRef`) - For arc mark, the primary (outer) radius in pixels. - - For text marks, polar coordinate radial offset, in pixels, of the text from the - origin determined by the ``x`` and ``y`` properties. - - **Default value:** ``min(plot_width, plot_height)/2`` - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - - **Default value:** ``0`` - radius2Offset : anyOf(float, :class:`ExprRef`) - Offset for radius2. - radiusOffset : anyOf(float, :class:`ExprRef`) - Offset for radius. - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - Shape of the point marks. Supported values include: - - - * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, - ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or - ``"triangle-left"``. - * the line symbol ``"stroke"`` - * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - * a custom `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - **Default value:** ``"circle"`` - size : anyOf(float, :class:`ExprRef`) - Default size for marks. - - - * For ``point`` / ``circle`` / ``square``, this represents the pixel area of the - marks. Note that this value sets the area of the symbol; the side lengths will - increase with the square root of this value. - * For ``bar``, this represents the band size of the bar, in pixels. - * For ``text``, this represents the font size, in pixels. - - **Default value:** - - - * ``30`` for point, circle, square marks; width/height's ``step`` - * ``2`` for bar marks with discrete dimensions; - * ``5`` for bar marks with continuous dimensions; - * ``11`` for text marks. - smooth : anyOf(boolean, :class:`ExprRef`) - A boolean flag (default true) indicating if the image should be smoothed when - resized. If false, individual pixels should be scaled directly rather than - interpolated with smoothing. For SVG rendering, this option may not work in some - browsers due to lack of standardization. - startAngle : anyOf(float, :class:`ExprRef`) - The start angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default stroke color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove stroke. - - **Default value:** (None) - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOffset : anyOf(float, :class:`ExprRef`) - The offset in pixels at which to draw the group stroke and fill. If unspecified, the - default behavior is to dynamically offset stroked groups such that 1 pixel stroke - widths align with the pixel grid. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - style : anyOf(string, List(string)) - A string or array of strings indicating the name of custom styles to apply to the - mark. A style is a named collection of mark property defaults defined within the - `style configuration - `__. If style is an - array, later styles will override earlier styles. Any `mark properties - `__ explicitly - defined within the ``encoding`` will override a style default. - - **Default value:** The mark's name. For example, a bar mark will have style - ``"bar"`` by default. **Note:** Any specified style will augment the default style. - For example, a bar mark with ``"style": "foo"`` will receive from - ``config.style.bar`` and ``config.style.foo`` (the specified style ``"foo"`` has - higher precedence). - tension : anyOf(float, :class:`ExprRef`) - Depending on the interpolation type, sets the tension parameter (for line and area - marks). - text : anyOf(:class:`Text`, :class:`ExprRef`) - Placeholder text if the ``text`` channel is not specified - theta : anyOf(float, :class:`ExprRef`) - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : anyOf(float, :class:`ExprRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - theta2Offset : anyOf(float, :class:`ExprRef`) - Offset for theta2. - thetaOffset : anyOf(float, :class:`ExprRef`) - Offset for theta. - timeUnitBandPosition : float - Default relative band position for a time unit. If set to ``0``, the marks will be - positioned at the beginning of the time unit band step. If set to ``0.5``, the marks - will be positioned in the middle of the time unit band step. - timeUnitBandSize : float - Default relative band size for a time unit. If set to ``1``, the bandwidth of the - marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the - marks will be half of the time unit band step. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprRef`, None) - The tooltip text string to show upon mouse hover or an object defining which fields - should the tooltip be derived from. - - - * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from - ``encoding`` will be used. - * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the - highlighted data point will be used. - * If set to ``null`` or ``false``, then no tooltip will be used. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - - **Default value:** ``null`` - url : anyOf(:class:`URI`, :class:`ExprRef`) - The URL of the image file for image marks. - width : anyOf(float, :class:`ExprRef`) - Width of the marks. - x : anyOf(float, string, :class:`ExprRef`) - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : anyOf(float, string, :class:`ExprRef`) - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2Offset : anyOf(float, :class:`ExprRef`) - Offset for x2-position. - xOffset : anyOf(float, :class:`ExprRef`) - Offset for x-position. - y : anyOf(float, string, :class:`ExprRef`) - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : anyOf(float, string, :class:`ExprRef`) - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2Offset : anyOf(float, :class:`ExprRef`) - Offset for y2-position. - yOffset : anyOf(float, :class:`ExprRef`) - Offset for y-position. - """ - _schema = {'$ref': '#/definitions/OverlayMarkDef'} - - def __init__(self, align=Undefined, angle=Undefined, aria=Undefined, ariaRole=Undefined, - ariaRoleDescription=Undefined, aspect=Undefined, baseline=Undefined, blend=Undefined, - clip=Undefined, color=Undefined, cornerRadius=Undefined, - cornerRadiusBottomLeft=Undefined, cornerRadiusBottomRight=Undefined, - cornerRadiusTopLeft=Undefined, cornerRadiusTopRight=Undefined, cursor=Undefined, - description=Undefined, dir=Undefined, dx=Undefined, dy=Undefined, ellipsis=Undefined, - endAngle=Undefined, fill=Undefined, fillOpacity=Undefined, filled=Undefined, - font=Undefined, fontSize=Undefined, fontStyle=Undefined, fontWeight=Undefined, - height=Undefined, href=Undefined, innerRadius=Undefined, interpolate=Undefined, - invalid=Undefined, limit=Undefined, lineBreak=Undefined, lineHeight=Undefined, - opacity=Undefined, order=Undefined, orient=Undefined, outerRadius=Undefined, - padAngle=Undefined, radius=Undefined, radius2=Undefined, radius2Offset=Undefined, - radiusOffset=Undefined, shape=Undefined, size=Undefined, smooth=Undefined, - startAngle=Undefined, stroke=Undefined, strokeCap=Undefined, strokeDash=Undefined, - strokeDashOffset=Undefined, strokeJoin=Undefined, strokeMiterLimit=Undefined, - strokeOffset=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, - style=Undefined, tension=Undefined, text=Undefined, theta=Undefined, theta2=Undefined, - theta2Offset=Undefined, thetaOffset=Undefined, timeUnitBandPosition=Undefined, - timeUnitBandSize=Undefined, tooltip=Undefined, url=Undefined, width=Undefined, - x=Undefined, x2=Undefined, x2Offset=Undefined, xOffset=Undefined, y=Undefined, - y2=Undefined, y2Offset=Undefined, yOffset=Undefined, **kwds): - super(OverlayMarkDef, self).__init__(align=align, angle=angle, aria=aria, ariaRole=ariaRole, - ariaRoleDescription=ariaRoleDescription, aspect=aspect, - baseline=baseline, blend=blend, clip=clip, color=color, - cornerRadius=cornerRadius, - cornerRadiusBottomLeft=cornerRadiusBottomLeft, - cornerRadiusBottomRight=cornerRadiusBottomRight, - cornerRadiusTopLeft=cornerRadiusTopLeft, - cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, - description=description, dir=dir, dx=dx, dy=dy, - ellipsis=ellipsis, endAngle=endAngle, fill=fill, - fillOpacity=fillOpacity, filled=filled, font=font, - fontSize=fontSize, fontStyle=fontStyle, - fontWeight=fontWeight, height=height, href=href, - innerRadius=innerRadius, interpolate=interpolate, - invalid=invalid, limit=limit, lineBreak=lineBreak, - lineHeight=lineHeight, opacity=opacity, order=order, - orient=orient, outerRadius=outerRadius, padAngle=padAngle, - radius=radius, radius2=radius2, - radius2Offset=radius2Offset, radiusOffset=radiusOffset, - shape=shape, size=size, smooth=smooth, - startAngle=startAngle, stroke=stroke, strokeCap=strokeCap, - strokeDash=strokeDash, strokeDashOffset=strokeDashOffset, - strokeJoin=strokeJoin, strokeMiterLimit=strokeMiterLimit, - strokeOffset=strokeOffset, strokeOpacity=strokeOpacity, - strokeWidth=strokeWidth, style=style, tension=tension, - text=text, theta=theta, theta2=theta2, - theta2Offset=theta2Offset, thetaOffset=thetaOffset, - timeUnitBandPosition=timeUnitBandPosition, - timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, - url=url, width=width, x=x, x2=x2, x2Offset=x2Offset, - xOffset=xOffset, y=y, y2=y2, y2Offset=y2Offset, - yOffset=yOffset, **kwds) - - -class Padding(VegaLiteSchema): - """Padding schema wrapper - - anyOf(float, Mapping(required=[])) - """ - _schema = {'$ref': '#/definitions/Padding'} - - def __init__(self, *args, **kwds): - super(Padding, self).__init__(*args, **kwds) - - -class ParameterExtent(BinExtent): - """ParameterExtent schema wrapper - - anyOf(Mapping(required=[param]), Mapping(required=[param])) - """ - _schema = {'$ref': '#/definitions/ParameterExtent'} - - def __init__(self, *args, **kwds): - super(ParameterExtent, self).__init__(*args, **kwds) - - -class ParameterName(VegaLiteSchema): - """ParameterName schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/ParameterName'} - - def __init__(self, *args): - super(ParameterName, self).__init__(*args) - - -class Parse(VegaLiteSchema): - """Parse schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/Parse'} - - def __init__(self, **kwds): - super(Parse, self).__init__(**kwds) - - -class ParseValue(VegaLiteSchema): - """ParseValue schema wrapper - - anyOf(None, string, string, string, string, string) - """ - _schema = {'$ref': '#/definitions/ParseValue'} - - def __init__(self, *args, **kwds): - super(ParseValue, self).__init__(*args, **kwds) - - -class Point(Geometry): - """Point schema wrapper - - Mapping(required=[coordinates, type]) - Point geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.2 - - Parameters - ---------- - - coordinates : :class:`Position` - A Position is an array of coordinates. - https://tools.ietf.org/html/rfc7946#section-3.1.1 Array should contain between two - and three elements. The previous GeoJSON specification allowed more elements (e.g., - which could be used to represent M values), but the current specification only - allows X, Y, and (optionally) Z to be defined. - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/Point'} - - def __init__(self, coordinates=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(Point, self).__init__(coordinates=coordinates, type=type, bbox=bbox, **kwds) - - -class PointSelectionConfig(VegaLiteSchema): - """PointSelectionConfig schema wrapper - - Mapping(required=[type]) - - Parameters - ---------- - - type : string - Determines the default event processing and data query for the selection. Vega-Lite - currently supports two selection types: - - - * ``"point"`` -- to select multiple discrete data values; the first value is - selected on ``click`` and additional values toggled on shift-click. - * ``"interval"`` -- to select a continuous range of data values on ``drag``. - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. This property can be a `Event - Stream `__ or ``false`` to disable - clear. - - **Default value:** ``dblclick``. - - **See also:** `clear examples - `__ in the - documentation. - encodings : List(:class:`SingleDefUnitChannel`) - An array of encoding channels. The corresponding data field values must match for a - data tuple to fall within the selection. - - **See also:** The `projection with encodings and fields section - `__ in the - documentation. - fields : List(:class:`FieldName`) - An array of field names whose values must match for a data tuple to fall within the - selection. - - **See also:** The `projection with encodings and fields section - `__ in the - documentation. - nearest : boolean - When true, an invisible voronoi diagram is computed to accelerate discrete - selection. The data value *nearest* the mouse cursor is added to the selection. - - **Default value:** ``false``, which means that data values must be interacted with - directly (e.g., clicked on) to be added to the selection. - - **See also:** `nearest examples - `__ documentation. - on : anyOf(:class:`Stream`, string) - A `Vega event stream `__ (object or - selector) that triggers the selection. For interval selections, the event stream - must specify a `start and end - `__. - - **See also:** `on examples - `__ in the documentation. - resolve : :class:`SelectionResolution` - With layered and multi-view displays, a strategy that determines how selections' - data queries are resolved when applied in a filter transform, conditional encoding - rule, or scale domain. - - One of: - - - * ``"global"`` -- only one brush exists for the entire SPLOM. When the user begins - to drag, any previous brushes are cleared, and a new one is constructed. - * ``"union"`` -- each cell contains its own brush, and points are highlighted if - they lie within *any* of these individual brushes. - * ``"intersect"`` -- each cell contains its own brush, and points are highlighted - only if they fall within *all* of these individual brushes. - - **Default value:** ``global``. - - **See also:** `resolve examples - `__ in the - documentation. - toggle : anyOf(string, boolean) - Controls whether data values should be toggled (inserted or removed from a point - selection) or only ever inserted into point selections. - - One of: - - - * ``true`` -- the default behavior, which corresponds to ``"event.shiftKey"``. As a - result, data values are toggled when the user interacts with the shift-key - pressed. - * ``false`` -- disables toggling behaviour; the selection will only ever contain a - single data value corresponding to the most recent interaction. - * A `Vega expression `__ which is - re-evaluated as the user interacts. If the expression evaluates to ``true``, the - data value is toggled into or out of the point selection. If the expression - evaluates to ``false``, the point selection is first cleared, and the data value - is then inserted. For example, setting the value to the Vega expression ``"true"`` - will toggle data values without the user pressing the shift-key. - - **Default value:** ``true`` - - **See also:** `toggle examples - `__ in the - documentation. - """ - _schema = {'$ref': '#/definitions/PointSelectionConfig'} - - def __init__(self, type=Undefined, clear=Undefined, encodings=Undefined, fields=Undefined, - nearest=Undefined, on=Undefined, resolve=Undefined, toggle=Undefined, **kwds): - super(PointSelectionConfig, self).__init__(type=type, clear=clear, encodings=encodings, - fields=fields, nearest=nearest, on=on, - resolve=resolve, toggle=toggle, **kwds) - - -class PointSelectionConfigWithoutType(VegaLiteSchema): - """PointSelectionConfigWithoutType schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - clear : anyOf(:class:`Stream`, string, boolean) - Clears the selection, emptying it of all values. This property can be a `Event - Stream `__ or ``false`` to disable - clear. - - **Default value:** ``dblclick``. - - **See also:** `clear examples - `__ in the - documentation. - encodings : List(:class:`SingleDefUnitChannel`) - An array of encoding channels. The corresponding data field values must match for a - data tuple to fall within the selection. - - **See also:** The `projection with encodings and fields section - `__ in the - documentation. - fields : List(:class:`FieldName`) - An array of field names whose values must match for a data tuple to fall within the - selection. - - **See also:** The `projection with encodings and fields section - `__ in the - documentation. - nearest : boolean - When true, an invisible voronoi diagram is computed to accelerate discrete - selection. The data value *nearest* the mouse cursor is added to the selection. - - **Default value:** ``false``, which means that data values must be interacted with - directly (e.g., clicked on) to be added to the selection. - - **See also:** `nearest examples - `__ documentation. - on : anyOf(:class:`Stream`, string) - A `Vega event stream `__ (object or - selector) that triggers the selection. For interval selections, the event stream - must specify a `start and end - `__. - - **See also:** `on examples - `__ in the documentation. - resolve : :class:`SelectionResolution` - With layered and multi-view displays, a strategy that determines how selections' - data queries are resolved when applied in a filter transform, conditional encoding - rule, or scale domain. - - One of: - - - * ``"global"`` -- only one brush exists for the entire SPLOM. When the user begins - to drag, any previous brushes are cleared, and a new one is constructed. - * ``"union"`` -- each cell contains its own brush, and points are highlighted if - they lie within *any* of these individual brushes. - * ``"intersect"`` -- each cell contains its own brush, and points are highlighted - only if they fall within *all* of these individual brushes. - - **Default value:** ``global``. - - **See also:** `resolve examples - `__ in the - documentation. - toggle : anyOf(string, boolean) - Controls whether data values should be toggled (inserted or removed from a point - selection) or only ever inserted into point selections. - - One of: - - - * ``true`` -- the default behavior, which corresponds to ``"event.shiftKey"``. As a - result, data values are toggled when the user interacts with the shift-key - pressed. - * ``false`` -- disables toggling behaviour; the selection will only ever contain a - single data value corresponding to the most recent interaction. - * A `Vega expression `__ which is - re-evaluated as the user interacts. If the expression evaluates to ``true``, the - data value is toggled into or out of the point selection. If the expression - evaluates to ``false``, the point selection is first cleared, and the data value - is then inserted. For example, setting the value to the Vega expression ``"true"`` - will toggle data values without the user pressing the shift-key. - - **Default value:** ``true`` - - **See also:** `toggle examples - `__ in the - documentation. - """ - _schema = {'$ref': '#/definitions/PointSelectionConfigWithoutType'} - - def __init__(self, clear=Undefined, encodings=Undefined, fields=Undefined, nearest=Undefined, - on=Undefined, resolve=Undefined, toggle=Undefined, **kwds): - super(PointSelectionConfigWithoutType, self).__init__(clear=clear, encodings=encodings, - fields=fields, nearest=nearest, on=on, - resolve=resolve, toggle=toggle, **kwds) - - -class PolarDef(VegaLiteSchema): - """PolarDef schema wrapper - - anyOf(:class:`PositionFieldDefBase`, :class:`PositionDatumDefBase`, - :class:`PositionValueDef`) - """ - _schema = {'$ref': '#/definitions/PolarDef'} - - def __init__(self, *args, **kwds): - super(PolarDef, self).__init__(*args, **kwds) - - -class Polygon(Geometry): - """Polygon schema wrapper - - Mapping(required=[coordinates, type]) - Polygon geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.6 - - Parameters - ---------- - - coordinates : List(List(:class:`Position`)) - - type : string - Specifies the type of GeoJSON object. - bbox : :class:`BBox` - Bounding box of the coordinate range of the object's Geometries, Features, or - Feature Collections. https://tools.ietf.org/html/rfc7946#section-5 - """ - _schema = {'$ref': '#/definitions/Polygon'} - - def __init__(self, coordinates=Undefined, type=Undefined, bbox=Undefined, **kwds): - super(Polygon, self).__init__(coordinates=coordinates, type=type, bbox=bbox, **kwds) - - -class Position(VegaLiteSchema): - """Position schema wrapper - - List(float) - A Position is an array of coordinates. https://tools.ietf.org/html/rfc7946#section-3.1.1 - Array should contain between two and three elements. The previous GeoJSON specification - allowed more elements (e.g., which could be used to represent M values), but the current - specification only allows X, Y, and (optionally) Z to be defined. - """ - _schema = {'$ref': '#/definitions/Position'} - - def __init__(self, *args): - super(Position, self).__init__(*args) - - -class Position2Def(VegaLiteSchema): - """Position2Def schema wrapper - - anyOf(:class:`SecondaryFieldDef`, :class:`DatumDef`, :class:`PositionValueDef`) - """ - _schema = {'$ref': '#/definitions/Position2Def'} - - def __init__(self, *args, **kwds): - super(Position2Def, self).__init__(*args, **kwds) - - -class DatumDef(LatLongDef, Position2Def): - """DatumDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/DatumDef'} - - def __init__(self, bandPosition=Undefined, datum=Undefined, title=Undefined, type=Undefined, **kwds): - super(DatumDef, self).__init__(bandPosition=bandPosition, datum=datum, title=title, type=type, - **kwds) - - -class PositionDatumDefBase(PolarDef): - """PositionDatumDefBase schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - stack : anyOf(:class:`StackOffset`, None, boolean) - Type of stacking offset if the field should be stacked. ``stack`` is only applicable - for ``x``, ``y``, ``theta``, and ``radius`` channels with continuous domains. For - example, ``stack`` of ``y`` can be used to customize stacking for a vertical bar - chart. - - ``stack`` can be one of the following values: - - - * ``"zero"`` or `true`: stacking with baseline offset at zero value of the scale - (for creating typical stacked - [bar](https://vega.github.io/vega-lite/docs/stack.html#bar) and `area - `__ chart). - * ``"normalize"`` - stacking with normalized domain (for creating `normalized - stacked bar and area charts - `__ and pie charts - `with percentage tooltip - `__ ). :raw-html:`
    ` - * ``"center"`` - stacking with center baseline (for `streamgraph - `__ ). - * ``null`` or ``false`` - No-stacking. This will produce layered `bar - `__ and area - chart. - - **Default value:** ``zero`` for plots with all of the following conditions are true: - (1) the mark is ``bar``, ``area``, or ``arc`` ; (2) the stacked measure channel (x - or y) has a linear scale; (3) At least one of non-position channels mapped to an - unaggregated field that is different from x and y. Otherwise, ``null`` by default. - - **See also:** `stack `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/PositionDatumDefBase'} - - def __init__(self, bandPosition=Undefined, datum=Undefined, scale=Undefined, stack=Undefined, - title=Undefined, type=Undefined, **kwds): - super(PositionDatumDefBase, self).__init__(bandPosition=bandPosition, datum=datum, scale=scale, - stack=stack, title=title, type=type, **kwds) - - -class PositionDef(VegaLiteSchema): - """PositionDef schema wrapper - - anyOf(:class:`PositionFieldDef`, :class:`PositionDatumDef`, :class:`PositionValueDef`) - """ - _schema = {'$ref': '#/definitions/PositionDef'} - - def __init__(self, *args, **kwds): - super(PositionDef, self).__init__(*args, **kwds) - - -class PositionDatumDef(PositionDef): - """PositionDatumDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - axis : anyOf(:class:`Axis`, None) - An object defining properties of axis's gridlines, ticks and labels. If ``null``, - the axis for the encoding channel will be removed. - - **Default value:** If undefined, default `axis properties - `__ are applied. - - **See also:** `axis `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - impute : anyOf(:class:`ImputeParams`, None) - An object defining the properties of the Impute Operation to be applied. The field - value of the other positional channel is taken as ``key`` of the ``Impute`` - Operation. The field of the ``color`` channel if specified is used as ``groupby`` of - the ``Impute`` Operation. - - **See also:** `impute `__ - documentation. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - stack : anyOf(:class:`StackOffset`, None, boolean) - Type of stacking offset if the field should be stacked. ``stack`` is only applicable - for ``x``, ``y``, ``theta``, and ``radius`` channels with continuous domains. For - example, ``stack`` of ``y`` can be used to customize stacking for a vertical bar - chart. - - ``stack`` can be one of the following values: - - - * ``"zero"`` or `true`: stacking with baseline offset at zero value of the scale - (for creating typical stacked - [bar](https://vega.github.io/vega-lite/docs/stack.html#bar) and `area - `__ chart). - * ``"normalize"`` - stacking with normalized domain (for creating `normalized - stacked bar and area charts - `__ and pie charts - `with percentage tooltip - `__ ). :raw-html:`
    ` - * ``"center"`` - stacking with center baseline (for `streamgraph - `__ ). - * ``null`` or ``false`` - No-stacking. This will produce layered `bar - `__ and area - chart. - - **Default value:** ``zero`` for plots with all of the following conditions are true: - (1) the mark is ``bar``, ``area``, or ``arc`` ; (2) the stacked measure channel (x - or y) has a linear scale; (3) At least one of non-position channels mapped to an - unaggregated field that is different from x and y. Otherwise, ``null`` by default. - - **See also:** `stack `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/PositionDatumDef'} - - def __init__(self, axis=Undefined, bandPosition=Undefined, datum=Undefined, impute=Undefined, - scale=Undefined, stack=Undefined, title=Undefined, type=Undefined, **kwds): - super(PositionDatumDef, self).__init__(axis=axis, bandPosition=bandPosition, datum=datum, - impute=impute, scale=scale, stack=stack, title=title, - type=type, **kwds) - - -class PositionFieldDef(PositionDef): - """PositionFieldDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - axis : anyOf(:class:`Axis`, None) - An object defining properties of axis's gridlines, ticks and labels. If ``null``, - the axis for the encoding channel will be removed. - - **Default value:** If undefined, default `axis properties - `__ are applied. - - **See also:** `axis `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - impute : anyOf(:class:`ImputeParams`, None) - An object defining the properties of the Impute Operation to be applied. The field - value of the other positional channel is taken as ``key`` of the ``Impute`` - Operation. The field of the ``color`` channel if specified is used as ``groupby`` of - the ``Impute`` Operation. - - **See also:** `impute `__ - documentation. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - sort : :class:`Sort` - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A string indicating an encoding channel name to sort by - `__ (e.g., - ``"x"`` or ``"y"`` ) with an optional minus prefix for descending sort (e.g., - ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a - sort-by-encoding definition - `__. For - example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": - "descending"}``. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` and sorting by another channel is not supported for ``row`` and - ``column``. - - **See also:** `sort `__ - documentation. - stack : anyOf(:class:`StackOffset`, None, boolean) - Type of stacking offset if the field should be stacked. ``stack`` is only applicable - for ``x``, ``y``, ``theta``, and ``radius`` channels with continuous domains. For - example, ``stack`` of ``y`` can be used to customize stacking for a vertical bar - chart. - - ``stack`` can be one of the following values: - - - * ``"zero"`` or `true`: stacking with baseline offset at zero value of the scale - (for creating typical stacked - [bar](https://vega.github.io/vega-lite/docs/stack.html#bar) and `area - `__ chart). - * ``"normalize"`` - stacking with normalized domain (for creating `normalized - stacked bar and area charts - `__ and pie charts - `with percentage tooltip - `__ ). :raw-html:`
    ` - * ``"center"`` - stacking with center baseline (for `streamgraph - `__ ). - * ``null`` or ``false`` - No-stacking. This will produce layered `bar - `__ and area - chart. - - **Default value:** ``zero`` for plots with all of the following conditions are true: - (1) the mark is ``bar``, ``area``, or ``arc`` ; (2) the stacked measure channel (x - or y) has a linear scale; (3) At least one of non-position channels mapped to an - unaggregated field that is different from x and y. Otherwise, ``null`` by default. - - **See also:** `stack `__ - documentation. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/PositionFieldDef'} - - def __init__(self, aggregate=Undefined, axis=Undefined, bandPosition=Undefined, bin=Undefined, - field=Undefined, impute=Undefined, scale=Undefined, sort=Undefined, stack=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(PositionFieldDef, self).__init__(aggregate=aggregate, axis=axis, - bandPosition=bandPosition, bin=bin, field=field, - impute=impute, scale=scale, sort=sort, stack=stack, - timeUnit=timeUnit, title=title, type=type, **kwds) - - -class PositionFieldDefBase(PolarDef): - """PositionFieldDefBase schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - sort : :class:`Sort` - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A string indicating an encoding channel name to sort by - `__ (e.g., - ``"x"`` or ``"y"`` ) with an optional minus prefix for descending sort (e.g., - ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a - sort-by-encoding definition - `__. For - example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": - "descending"}``. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` and sorting by another channel is not supported for ``row`` and - ``column``. - - **See also:** `sort `__ - documentation. - stack : anyOf(:class:`StackOffset`, None, boolean) - Type of stacking offset if the field should be stacked. ``stack`` is only applicable - for ``x``, ``y``, ``theta``, and ``radius`` channels with continuous domains. For - example, ``stack`` of ``y`` can be used to customize stacking for a vertical bar - chart. - - ``stack`` can be one of the following values: - - - * ``"zero"`` or `true`: stacking with baseline offset at zero value of the scale - (for creating typical stacked - [bar](https://vega.github.io/vega-lite/docs/stack.html#bar) and `area - `__ chart). - * ``"normalize"`` - stacking with normalized domain (for creating `normalized - stacked bar and area charts - `__ and pie charts - `with percentage tooltip - `__ ). :raw-html:`
    ` - * ``"center"`` - stacking with center baseline (for `streamgraph - `__ ). - * ``null`` or ``false`` - No-stacking. This will produce layered `bar - `__ and area - chart. - - **Default value:** ``zero`` for plots with all of the following conditions are true: - (1) the mark is ``bar``, ``area``, or ``arc`` ; (2) the stacked measure channel (x - or y) has a linear scale; (3) At least one of non-position channels mapped to an - unaggregated field that is different from x and y. Otherwise, ``null`` by default. - - **See also:** `stack `__ - documentation. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/PositionFieldDefBase'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - scale=Undefined, sort=Undefined, stack=Undefined, timeUnit=Undefined, title=Undefined, - type=Undefined, **kwds): - super(PositionFieldDefBase, self).__init__(aggregate=aggregate, bandPosition=bandPosition, - bin=bin, field=field, scale=scale, sort=sort, - stack=stack, timeUnit=timeUnit, title=title, - type=type, **kwds) - - -class PositionValueDef(PolarDef, Position2Def, PositionDef): - """PositionValueDef schema wrapper - - Mapping(required=[value]) - Definition object for a constant value (primitive value or gradient definition) of an - encoding channel. - - Parameters - ---------- - - value : anyOf(float, string, string, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/PositionValueDef'} - - def __init__(self, value=Undefined, **kwds): - super(PositionValueDef, self).__init__(value=value, **kwds) - - -class PredicateComposition(VegaLiteSchema): - """PredicateComposition schema wrapper - - anyOf(:class:`LogicalNotPredicate`, :class:`LogicalAndPredicate`, - :class:`LogicalOrPredicate`, :class:`Predicate`) - """ - _schema = {'$ref': '#/definitions/PredicateComposition'} - - def __init__(self, *args, **kwds): - super(PredicateComposition, self).__init__(*args, **kwds) - - -class LogicalAndPredicate(PredicateComposition): - """LogicalAndPredicate schema wrapper - - Mapping(required=[and]) - - Parameters - ---------- - - and : List(:class:`PredicateComposition`) - - """ - _schema = {'$ref': '#/definitions/LogicalAnd'} - - def __init__(self, **kwds): - super(LogicalAndPredicate, self).__init__(**kwds) - - -class LogicalNotPredicate(PredicateComposition): - """LogicalNotPredicate schema wrapper - - Mapping(required=[not]) - - Parameters - ---------- - - not : :class:`PredicateComposition` - - """ - _schema = {'$ref': '#/definitions/LogicalNot'} - - def __init__(self, **kwds): - super(LogicalNotPredicate, self).__init__(**kwds) - - -class LogicalOrPredicate(PredicateComposition): - """LogicalOrPredicate schema wrapper - - Mapping(required=[or]) - - Parameters - ---------- - - or : List(:class:`PredicateComposition`) - - """ - _schema = {'$ref': '#/definitions/LogicalOr'} - - def __init__(self, **kwds): - super(LogicalOrPredicate, self).__init__(**kwds) - - -class Predicate(PredicateComposition): - """Predicate schema wrapper - - anyOf(:class:`FieldEqualPredicate`, :class:`FieldRangePredicate`, - :class:`FieldOneOfPredicate`, :class:`FieldLTPredicate`, :class:`FieldGTPredicate`, - :class:`FieldLTEPredicate`, :class:`FieldGTEPredicate`, :class:`FieldValidPredicate`, - :class:`ParameterPredicate`, string) - """ - _schema = {'$ref': '#/definitions/Predicate'} - - def __init__(self, *args, **kwds): - super(Predicate, self).__init__(*args, **kwds) - - -class FieldEqualPredicate(Predicate): - """FieldEqualPredicate schema wrapper - - Mapping(required=[equal, field]) - - Parameters - ---------- - - equal : anyOf(string, float, boolean, :class:`DateTime`, :class:`ExprRef`) - The value that the field should be equal to. - field : :class:`FieldName` - Field to be tested. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit for the field to be tested. - """ - _schema = {'$ref': '#/definitions/FieldEqualPredicate'} - - def __init__(self, equal=Undefined, field=Undefined, timeUnit=Undefined, **kwds): - super(FieldEqualPredicate, self).__init__(equal=equal, field=field, timeUnit=timeUnit, **kwds) - - -class FieldGTEPredicate(Predicate): - """FieldGTEPredicate schema wrapper - - Mapping(required=[field, gte]) - - Parameters - ---------- - - field : :class:`FieldName` - Field to be tested. - gte : anyOf(string, float, :class:`DateTime`, :class:`ExprRef`) - The value that the field should be greater than or equals to. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit for the field to be tested. - """ - _schema = {'$ref': '#/definitions/FieldGTEPredicate'} - - def __init__(self, field=Undefined, gte=Undefined, timeUnit=Undefined, **kwds): - super(FieldGTEPredicate, self).__init__(field=field, gte=gte, timeUnit=timeUnit, **kwds) - - -class FieldGTPredicate(Predicate): - """FieldGTPredicate schema wrapper - - Mapping(required=[field, gt]) - - Parameters - ---------- - - field : :class:`FieldName` - Field to be tested. - gt : anyOf(string, float, :class:`DateTime`, :class:`ExprRef`) - The value that the field should be greater than. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit for the field to be tested. - """ - _schema = {'$ref': '#/definitions/FieldGTPredicate'} - - def __init__(self, field=Undefined, gt=Undefined, timeUnit=Undefined, **kwds): - super(FieldGTPredicate, self).__init__(field=field, gt=gt, timeUnit=timeUnit, **kwds) - - -class FieldLTEPredicate(Predicate): - """FieldLTEPredicate schema wrapper - - Mapping(required=[field, lte]) - - Parameters - ---------- - - field : :class:`FieldName` - Field to be tested. - lte : anyOf(string, float, :class:`DateTime`, :class:`ExprRef`) - The value that the field should be less than or equals to. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit for the field to be tested. - """ - _schema = {'$ref': '#/definitions/FieldLTEPredicate'} - - def __init__(self, field=Undefined, lte=Undefined, timeUnit=Undefined, **kwds): - super(FieldLTEPredicate, self).__init__(field=field, lte=lte, timeUnit=timeUnit, **kwds) - - -class FieldLTPredicate(Predicate): - """FieldLTPredicate schema wrapper - - Mapping(required=[field, lt]) - - Parameters - ---------- - - field : :class:`FieldName` - Field to be tested. - lt : anyOf(string, float, :class:`DateTime`, :class:`ExprRef`) - The value that the field should be less than. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit for the field to be tested. - """ - _schema = {'$ref': '#/definitions/FieldLTPredicate'} - - def __init__(self, field=Undefined, lt=Undefined, timeUnit=Undefined, **kwds): - super(FieldLTPredicate, self).__init__(field=field, lt=lt, timeUnit=timeUnit, **kwds) - - -class FieldOneOfPredicate(Predicate): - """FieldOneOfPredicate schema wrapper - - Mapping(required=[field, oneOf]) - - Parameters - ---------- - - field : :class:`FieldName` - Field to be tested. - oneOf : anyOf(List(string), List(float), List(boolean), List(:class:`DateTime`)) - A set of values that the ``field`` 's value should be a member of, for a data item - included in the filtered data. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit for the field to be tested. - """ - _schema = {'$ref': '#/definitions/FieldOneOfPredicate'} - - def __init__(self, field=Undefined, oneOf=Undefined, timeUnit=Undefined, **kwds): - super(FieldOneOfPredicate, self).__init__(field=field, oneOf=oneOf, timeUnit=timeUnit, **kwds) - - -class FieldRangePredicate(Predicate): - """FieldRangePredicate schema wrapper - - Mapping(required=[field, range]) - - Parameters - ---------- - - field : :class:`FieldName` - Field to be tested. - range : anyOf(List(anyOf(float, :class:`DateTime`, None, :class:`ExprRef`)), :class:`ExprRef`) - An array of inclusive minimum and maximum values for a field value of a data item to - be included in the filtered data. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit for the field to be tested. - """ - _schema = {'$ref': '#/definitions/FieldRangePredicate'} - - def __init__(self, field=Undefined, range=Undefined, timeUnit=Undefined, **kwds): - super(FieldRangePredicate, self).__init__(field=field, range=range, timeUnit=timeUnit, **kwds) - - -class FieldValidPredicate(Predicate): - """FieldValidPredicate schema wrapper - - Mapping(required=[field, valid]) - - Parameters - ---------- - - field : :class:`FieldName` - Field to be tested. - valid : boolean - If set to true the field's value has to be valid, meaning both not ``null`` and not - `NaN - `__. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit for the field to be tested. - """ - _schema = {'$ref': '#/definitions/FieldValidPredicate'} - - def __init__(self, field=Undefined, valid=Undefined, timeUnit=Undefined, **kwds): - super(FieldValidPredicate, self).__init__(field=field, valid=valid, timeUnit=timeUnit, **kwds) - - -class ParameterPredicate(Predicate): - """ParameterPredicate schema wrapper - - Mapping(required=[param]) - - Parameters - ---------- - - param : :class:`ParameterName` - Filter using a parameter name. - empty : boolean - For selection parameters, the predicate of empty selections returns true by default. - Override this behavior, by setting this property ``empty: false``. - """ - _schema = {'$ref': '#/definitions/ParameterPredicate'} - - def __init__(self, param=Undefined, empty=Undefined, **kwds): - super(ParameterPredicate, self).__init__(param=param, empty=empty, **kwds) - - -class Projection(VegaLiteSchema): - """Projection schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - center : anyOf(:class:`Vector2number`, :class:`ExprRef`) - The projection's center, a two-element array of longitude and latitude in degrees. - - **Default value:** ``[0, 0]`` - clipAngle : anyOf(float, :class:`ExprRef`) - The projection's clipping circle radius to the specified angle in degrees. If - ``null``, switches to `antimeridian `__ cutting - rather than small-circle clipping. - clipExtent : anyOf(:class:`Vector2Vector2number`, :class:`ExprRef`) - The projection's viewport clip extent to the specified bounds in pixels. The extent - bounds are specified as an array ``[[x0, y0], [x1, y1]]``, where ``x0`` is the - left-side of the viewport, ``y0`` is the top, ``x1`` is the right and ``y1`` is the - bottom. If ``null``, no viewport clipping is performed. - coefficient : anyOf(float, :class:`ExprRef`) - The coefficient parameter for the ``hammer`` projection. - - **Default value:** ``2`` - distance : anyOf(float, :class:`ExprRef`) - For the ``satellite`` projection, the distance from the center of the sphere to the - point of view, as a proportion of the sphere’s radius. The recommended maximum clip - angle for a given ``distance`` is acos(1 / distance) converted to degrees. If tilt - is also applied, then more conservative clipping may be necessary. - - **Default value:** ``2.0`` - extent : anyOf(:class:`Vector2Vector2number`, :class:`ExprRef`) - - fit : anyOf(:class:`Fit`, List(:class:`Fit`), :class:`ExprRef`) - - fraction : anyOf(float, :class:`ExprRef`) - The fraction parameter for the ``bottomley`` projection. - - **Default value:** ``0.5``, corresponding to a sin(ψ) where ψ = π/6. - lobes : anyOf(float, :class:`ExprRef`) - The number of lobes in projections that support multi-lobe views: ``berghaus``, - ``gingery``, or ``healpix``. The default value varies based on the projection type. - parallel : anyOf(float, :class:`ExprRef`) - The parallel parameter for projections that support it: ``armadillo``, ``bonne``, - ``craig``, ``cylindricalEqualArea``, ``cylindricalStereographic``, - ``hammerRetroazimuthal``, ``loximuthal``, or ``rectangularPolyconic``. The default - value varies based on the projection type. - parallels : anyOf(List(float), :class:`ExprRef`) - For conic projections, the `two standard parallels - `__ that define the map layout. - The default depends on the specific conic projection used. - pointRadius : anyOf(float, :class:`ExprRef`) - The default radius (in pixels) to use when drawing GeoJSON ``Point`` and - ``MultiPoint`` geometries. This parameter sets a constant default value. To modify - the point radius in response to data, see the corresponding parameter of the GeoPath - and GeoShape transforms. - - **Default value:** ``4.5`` - precision : anyOf(float, :class:`ExprRef`) - The threshold for the projection's `adaptive resampling - `__ to the specified value in pixels. This - value corresponds to the `Douglas–Peucker distance - `__. - If precision is not specified, returns the projection's current resampling precision - which defaults to ``√0.5 ≅ 0.70710…``. - radius : anyOf(float, :class:`ExprRef`) - The radius parameter for the ``airy`` or ``gingery`` projection. The default value - varies based on the projection type. - ratio : anyOf(float, :class:`ExprRef`) - The ratio parameter for the ``hill``, ``hufnagel``, or ``wagner`` projections. The - default value varies based on the projection type. - reflectX : anyOf(boolean, :class:`ExprRef`) - Sets whether or not the x-dimension is reflected (negated) in the output. - reflectY : anyOf(boolean, :class:`ExprRef`) - Sets whether or not the y-dimension is reflected (negated) in the output. - rotate : anyOf(anyOf(:class:`Vector2number`, :class:`Vector3number`), :class:`ExprRef`) - The projection's three-axis rotation to the specified angles, which must be a two- - or three-element array of numbers [ ``lambda``, ``phi``, ``gamma`` ] specifying the - rotation angles in degrees about each spherical axis. (These correspond to yaw, - pitch and roll.) - - **Default value:** ``[0, 0, 0]`` - scale : anyOf(float, :class:`ExprRef`) - The projection’s scale (zoom) factor, overriding automatic fitting. The default - scale is projection-specific. The scale factor corresponds linearly to the distance - between projected points; however, scale factor values are not equivalent across - projections. - size : anyOf(:class:`Vector2number`, :class:`ExprRef`) - Used in conjunction with fit, provides the width and height in pixels of the area to - which the projection should be automatically fit. - spacing : anyOf(float, :class:`ExprRef`) - The spacing parameter for the ``lagrange`` projection. - - **Default value:** ``0.5`` - tilt : anyOf(float, :class:`ExprRef`) - The tilt angle (in degrees) for the ``satellite`` projection. - - **Default value:** ``0``. - translate : anyOf(:class:`Vector2number`, :class:`ExprRef`) - The projection’s translation offset as a two-element array ``[tx, ty]``. - type : anyOf(:class:`ProjectionType`, :class:`ExprRef`) - The cartographic projection to use. This value is case-insensitive, for example - ``"albers"`` and ``"Albers"`` indicate the same projection type. You can find all - valid projection types `in the documentation - `__. - - **Default value:** ``equalEarth`` - """ - _schema = {'$ref': '#/definitions/Projection'} - - def __init__(self, center=Undefined, clipAngle=Undefined, clipExtent=Undefined, - coefficient=Undefined, distance=Undefined, extent=Undefined, fit=Undefined, - fraction=Undefined, lobes=Undefined, parallel=Undefined, parallels=Undefined, - pointRadius=Undefined, precision=Undefined, radius=Undefined, ratio=Undefined, - reflectX=Undefined, reflectY=Undefined, rotate=Undefined, scale=Undefined, - size=Undefined, spacing=Undefined, tilt=Undefined, translate=Undefined, type=Undefined, - **kwds): - super(Projection, self).__init__(center=center, clipAngle=clipAngle, clipExtent=clipExtent, - coefficient=coefficient, distance=distance, extent=extent, - fit=fit, fraction=fraction, lobes=lobes, parallel=parallel, - parallels=parallels, pointRadius=pointRadius, - precision=precision, radius=radius, ratio=ratio, - reflectX=reflectX, reflectY=reflectY, rotate=rotate, - scale=scale, size=size, spacing=spacing, tilt=tilt, - translate=translate, type=type, **kwds) - - -class ProjectionConfig(VegaLiteSchema): - """ProjectionConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - center : anyOf(:class:`Vector2number`, :class:`ExprRef`) - The projection's center, a two-element array of longitude and latitude in degrees. - - **Default value:** ``[0, 0]`` - clipAngle : anyOf(float, :class:`ExprRef`) - The projection's clipping circle radius to the specified angle in degrees. If - ``null``, switches to `antimeridian `__ cutting - rather than small-circle clipping. - clipExtent : anyOf(:class:`Vector2Vector2number`, :class:`ExprRef`) - The projection's viewport clip extent to the specified bounds in pixels. The extent - bounds are specified as an array ``[[x0, y0], [x1, y1]]``, where ``x0`` is the - left-side of the viewport, ``y0`` is the top, ``x1`` is the right and ``y1`` is the - bottom. If ``null``, no viewport clipping is performed. - coefficient : anyOf(float, :class:`ExprRef`) - The coefficient parameter for the ``hammer`` projection. - - **Default value:** ``2`` - distance : anyOf(float, :class:`ExprRef`) - For the ``satellite`` projection, the distance from the center of the sphere to the - point of view, as a proportion of the sphere’s radius. The recommended maximum clip - angle for a given ``distance`` is acos(1 / distance) converted to degrees. If tilt - is also applied, then more conservative clipping may be necessary. - - **Default value:** ``2.0`` - extent : anyOf(:class:`Vector2Vector2number`, :class:`ExprRef`) - - fit : anyOf(:class:`Fit`, List(:class:`Fit`), :class:`ExprRef`) - - fraction : anyOf(float, :class:`ExprRef`) - The fraction parameter for the ``bottomley`` projection. - - **Default value:** ``0.5``, corresponding to a sin(ψ) where ψ = π/6. - lobes : anyOf(float, :class:`ExprRef`) - The number of lobes in projections that support multi-lobe views: ``berghaus``, - ``gingery``, or ``healpix``. The default value varies based on the projection type. - parallel : anyOf(float, :class:`ExprRef`) - The parallel parameter for projections that support it: ``armadillo``, ``bonne``, - ``craig``, ``cylindricalEqualArea``, ``cylindricalStereographic``, - ``hammerRetroazimuthal``, ``loximuthal``, or ``rectangularPolyconic``. The default - value varies based on the projection type. - parallels : anyOf(List(float), :class:`ExprRef`) - For conic projections, the `two standard parallels - `__ that define the map layout. - The default depends on the specific conic projection used. - pointRadius : anyOf(float, :class:`ExprRef`) - The default radius (in pixels) to use when drawing GeoJSON ``Point`` and - ``MultiPoint`` geometries. This parameter sets a constant default value. To modify - the point radius in response to data, see the corresponding parameter of the GeoPath - and GeoShape transforms. - - **Default value:** ``4.5`` - precision : anyOf(float, :class:`ExprRef`) - The threshold for the projection's `adaptive resampling - `__ to the specified value in pixels. This - value corresponds to the `Douglas–Peucker distance - `__. - If precision is not specified, returns the projection's current resampling precision - which defaults to ``√0.5 ≅ 0.70710…``. - radius : anyOf(float, :class:`ExprRef`) - The radius parameter for the ``airy`` or ``gingery`` projection. The default value - varies based on the projection type. - ratio : anyOf(float, :class:`ExprRef`) - The ratio parameter for the ``hill``, ``hufnagel``, or ``wagner`` projections. The - default value varies based on the projection type. - reflectX : anyOf(boolean, :class:`ExprRef`) - Sets whether or not the x-dimension is reflected (negated) in the output. - reflectY : anyOf(boolean, :class:`ExprRef`) - Sets whether or not the y-dimension is reflected (negated) in the output. - rotate : anyOf(anyOf(:class:`Vector2number`, :class:`Vector3number`), :class:`ExprRef`) - The projection's three-axis rotation to the specified angles, which must be a two- - or three-element array of numbers [ ``lambda``, ``phi``, ``gamma`` ] specifying the - rotation angles in degrees about each spherical axis. (These correspond to yaw, - pitch and roll.) - - **Default value:** ``[0, 0, 0]`` - scale : anyOf(float, :class:`ExprRef`) - The projection’s scale (zoom) factor, overriding automatic fitting. The default - scale is projection-specific. The scale factor corresponds linearly to the distance - between projected points; however, scale factor values are not equivalent across - projections. - size : anyOf(:class:`Vector2number`, :class:`ExprRef`) - Used in conjunction with fit, provides the width and height in pixels of the area to - which the projection should be automatically fit. - spacing : anyOf(float, :class:`ExprRef`) - The spacing parameter for the ``lagrange`` projection. - - **Default value:** ``0.5`` - tilt : anyOf(float, :class:`ExprRef`) - The tilt angle (in degrees) for the ``satellite`` projection. - - **Default value:** ``0``. - translate : anyOf(:class:`Vector2number`, :class:`ExprRef`) - The projection’s translation offset as a two-element array ``[tx, ty]``. - type : anyOf(:class:`ProjectionType`, :class:`ExprRef`) - The cartographic projection to use. This value is case-insensitive, for example - ``"albers"`` and ``"Albers"`` indicate the same projection type. You can find all - valid projection types `in the documentation - `__. - - **Default value:** ``equalEarth`` - """ - _schema = {'$ref': '#/definitions/ProjectionConfig'} - - def __init__(self, center=Undefined, clipAngle=Undefined, clipExtent=Undefined, - coefficient=Undefined, distance=Undefined, extent=Undefined, fit=Undefined, - fraction=Undefined, lobes=Undefined, parallel=Undefined, parallels=Undefined, - pointRadius=Undefined, precision=Undefined, radius=Undefined, ratio=Undefined, - reflectX=Undefined, reflectY=Undefined, rotate=Undefined, scale=Undefined, - size=Undefined, spacing=Undefined, tilt=Undefined, translate=Undefined, type=Undefined, - **kwds): - super(ProjectionConfig, self).__init__(center=center, clipAngle=clipAngle, - clipExtent=clipExtent, coefficient=coefficient, - distance=distance, extent=extent, fit=fit, - fraction=fraction, lobes=lobes, parallel=parallel, - parallels=parallels, pointRadius=pointRadius, - precision=precision, radius=radius, ratio=ratio, - reflectX=reflectX, reflectY=reflectY, rotate=rotate, - scale=scale, size=size, spacing=spacing, tilt=tilt, - translate=translate, type=type, **kwds) - - -class ProjectionType(VegaLiteSchema): - """ProjectionType schema wrapper - - enum('albers', 'albersUsa', 'azimuthalEqualArea', 'azimuthalEquidistant', 'conicConformal', - 'conicEqualArea', 'conicEquidistant', 'equalEarth', 'equirectangular', 'gnomonic', - 'identity', 'mercator', 'naturalEarth1', 'orthographic', 'stereographic', - 'transverseMercator') - """ - _schema = {'$ref': '#/definitions/ProjectionType'} - - def __init__(self, *args): - super(ProjectionType, self).__init__(*args) - - -class RadialGradient(Gradient): - """RadialGradient schema wrapper - - Mapping(required=[gradient, stops]) - - Parameters - ---------- - - gradient : string - The type of gradient. Use ``"radial"`` for a radial gradient. - stops : List(:class:`GradientStop`) - An array of gradient stops defining the gradient color sequence. - id : string - - r1 : float - The radius length, in normalized [0, 1] coordinates, of the inner circle for the - gradient. - - **Default value:** ``0`` - r2 : float - The radius length, in normalized [0, 1] coordinates, of the outer circle for the - gradient. - - **Default value:** ``0.5`` - x1 : float - The x-coordinate, in normalized [0, 1] coordinates, for the center of the inner - circle for the gradient. - - **Default value:** ``0.5`` - x2 : float - The x-coordinate, in normalized [0, 1] coordinates, for the center of the outer - circle for the gradient. - - **Default value:** ``0.5`` - y1 : float - The y-coordinate, in normalized [0, 1] coordinates, for the center of the inner - circle for the gradient. - - **Default value:** ``0.5`` - y2 : float - The y-coordinate, in normalized [0, 1] coordinates, for the center of the outer - circle for the gradient. - - **Default value:** ``0.5`` - """ - _schema = {'$ref': '#/definitions/RadialGradient'} - - def __init__(self, gradient=Undefined, stops=Undefined, id=Undefined, r1=Undefined, r2=Undefined, - x1=Undefined, x2=Undefined, y1=Undefined, y2=Undefined, **kwds): - super(RadialGradient, self).__init__(gradient=gradient, stops=stops, id=id, r1=r1, r2=r2, x1=x1, - x2=x2, y1=y1, y2=y2, **kwds) - - -class RangeConfig(VegaLiteSchema): - """RangeConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - category : anyOf(:class:`RangeScheme`, List(:class:`Color`)) - Default `color scheme `__ for categorical - data. - diverging : anyOf(:class:`RangeScheme`, List(:class:`Color`)) - Default `color scheme `__ for diverging - quantitative ramps. - heatmap : anyOf(:class:`RangeScheme`, List(:class:`Color`)) - Default `color scheme `__ for - quantitative heatmaps. - ordinal : anyOf(:class:`RangeScheme`, List(:class:`Color`)) - Default `color scheme `__ for - rank-ordered data. - ramp : anyOf(:class:`RangeScheme`, List(:class:`Color`)) - Default `color scheme `__ for sequential - quantitative ramps. - symbol : List(:class:`SymbolShape`) - Array of `symbol `__ names or paths - for the default shape palette. - """ - _schema = {'$ref': '#/definitions/RangeConfig'} - - def __init__(self, category=Undefined, diverging=Undefined, heatmap=Undefined, ordinal=Undefined, - ramp=Undefined, symbol=Undefined, **kwds): - super(RangeConfig, self).__init__(category=category, diverging=diverging, heatmap=heatmap, - ordinal=ordinal, ramp=ramp, symbol=symbol, **kwds) - - -class RangeRawArray(VegaLiteSchema): - """RangeRawArray schema wrapper - - List(float) - """ - _schema = {'$ref': '#/definitions/RangeRawArray'} - - def __init__(self, *args): - super(RangeRawArray, self).__init__(*args) - - -class RangeScheme(VegaLiteSchema): - """RangeScheme schema wrapper - - anyOf(:class:`RangeEnum`, :class:`RangeRaw`, Mapping(required=[scheme])) - """ - _schema = {'$ref': '#/definitions/RangeScheme'} - - def __init__(self, *args, **kwds): - super(RangeScheme, self).__init__(*args, **kwds) - - -class RangeEnum(RangeScheme): - """RangeEnum schema wrapper - - enum('width', 'height', 'symbol', 'category', 'ordinal', 'ramp', 'diverging', 'heatmap') - """ - _schema = {'$ref': '#/definitions/RangeEnum'} - - def __init__(self, *args): - super(RangeEnum, self).__init__(*args) - - -class RangeRaw(RangeScheme): - """RangeRaw schema wrapper - - List(anyOf(None, boolean, string, float, :class:`RangeRawArray`)) - """ - _schema = {'$ref': '#/definitions/RangeRaw'} - - def __init__(self, *args): - super(RangeRaw, self).__init__(*args) - - -class RectConfig(AnyMarkConfig): - """RectConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : anyOf(:class:`Align`, :class:`ExprRef`) - The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). - One of ``"left"``, ``"right"``, ``"center"``. - - **Note:** Expression reference is *not* supported for range marks. - angle : anyOf(float, :class:`ExprRef`) - The rotation angle of the text, in degrees. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG element, removing the mark item from the ARIA accessibility tree. - ariaRole : anyOf(string, :class:`ExprRef`) - Sets the type of user interface element of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "role" attribute. Warning: this - property is experimental and may be changed in the future. - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - A human-readable, author-localized description for the role of the mark item for - `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "aria-roledescription" attribute. - Warning: this property is experimental and may be changed in the future. - aspect : anyOf(boolean, :class:`ExprRef`) - Whether to keep aspect ratio of image marks. - baseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an - expression reference that provides one of the valid values. The ``"line-top"`` and - ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are - calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. - - For range marks, the vertical alignment of the marks. One of ``"top"``, - ``"middle"``, ``"bottom"``. - - **Note:** Expression reference is *not* supported for range marks. - binSpacing : float - Offset between bars for binned field. The ideal value for this is either 0 - (preferred by statisticians) or 1 (Vega-Lite default, D3 example style). - - **Default value:** ``1`` - blend : anyOf(:class:`Blend`, :class:`ExprRef`) - The color blend mode for drawing an item on its current background. Any valid `CSS - mix-blend-mode `__ - value can be used. - - __Default value:__ ``"source-over"`` - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - continuousBandSize : float - The default size of the bars on continuous scales. - - **Default value:** ``5`` - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom left corner. - - **Default value:** ``0`` - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom right corner. - - **Default value:** ``0`` - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top right corner. - - **Default value:** ``0`` - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top left corner. - - **Default value:** ``0`` - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - The mouse cursor used over the mark. Any valid `CSS cursor type - `__ can be used. - description : anyOf(string, :class:`ExprRef`) - A text description of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the `"aria-label" attribute - `__. - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` - (right-to-left). This property determines on which side is truncated in response to - the limit parameter. - - **Default value:** ``"ltr"`` - discreteBandSize : anyOf(float, :class:`RelativeBandSize`) - The default size of the bars with discrete dimensions. If unspecified, the default - size is ``step-2``, which provides 2 pixel offset between bars. - dx : anyOf(float, :class:`ExprRef`) - The horizontal offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - dy : anyOf(float, :class:`ExprRef`) - The vertical offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - ellipsis : anyOf(string, :class:`ExprRef`) - The ellipsis string for text truncated in response to the limit parameter. - - **Default value:** ``"…"`` - endAngle : anyOf(float, :class:`ExprRef`) - The end angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - filled : boolean - Whether the mark's color should be used as fill color instead of stroke color. - - **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well - as ``geoshape`` marks for `graticule - `__ data sources; - otherwise, ``true``. - - **Note:** This property cannot be used in a `style config - `__. - font : anyOf(string, :class:`ExprRef`) - The typeface to set the text in (e.g., ``"Helvetica Neue"`` ). - fontSize : anyOf(float, :class:`ExprRef`) - The font size, in pixels. - - **Default value:** ``11`` - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style (e.g., ``"italic"`` ). - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight. This can be either a string (e.g ``"bold"``, ``"normal"`` ) or a - number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and - ``"bold"`` = ``700`` ). - height : anyOf(float, :class:`ExprRef`) - Height of the marks. - href : anyOf(:class:`URI`, :class:`ExprRef`) - A URL to load upon mouse click. If defined, the mark acts as a hyperlink. - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - - **Default value:** ``0`` - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - The line interpolation method to use for line and area marks. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : alternate between horizontal and vertical segments, as in a step - function. - * ``"step-before"`` : alternate between vertical and horizontal segments, as in a - step function. - * ``"step-after"`` : alternate between horizontal and vertical segments, as in a - step function. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - limit : anyOf(float, :class:`ExprRef`) - The maximum length of the text mark in pixels. The text value will be automatically - truncated if the rendered size exceeds the limit. - - **Default value:** ``0`` -- indicating no limit - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property is ignored if the text is array-valued. - lineHeight : anyOf(float, :class:`ExprRef`) - The line height in pixels (the spacing between subsequent lines of text) for - multi-line text marks. - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - order : anyOf(None, boolean) - For line and trail marks, this ``order`` property can be set to ``null`` or - ``false`` to make the lines use the original order in the data sources. - orient : :class:`Orientation` - The orientation of a non-stacked bar, tick, area, and line charts. The value is - either horizontal (default) or vertical. - - - * For bar, rule and tick, this determines whether the size of the bar and tick - should be applied to x or y dimension. - * For area, this property determines the orient property of the Vega output. - * For line and trail marks, this property determines the sort order of the points in - the line if ``config.sortLineBy`` is not specified. For stacked charts, this is - always determined by the orientation of the stack; therefore explicitly specified - value will be ignored. - outerRadius : anyOf(float, :class:`ExprRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - - **Default value:** ``0`` - padAngle : anyOf(float, :class:`ExprRef`) - The angular padding applied to sides of the arc, in radians. - radius : anyOf(float, :class:`ExprRef`) - For arc mark, the primary (outer) radius in pixels. - - For text marks, polar coordinate radial offset, in pixels, of the text from the - origin determined by the ``x`` and ``y`` properties. - - **Default value:** ``min(plot_width, plot_height)/2`` - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - - **Default value:** ``0`` - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - Shape of the point marks. Supported values include: - - - * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, - ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or - ``"triangle-left"``. - * the line symbol ``"stroke"`` - * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - * a custom `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - **Default value:** ``"circle"`` - size : anyOf(float, :class:`ExprRef`) - Default size for marks. - - - * For ``point`` / ``circle`` / ``square``, this represents the pixel area of the - marks. Note that this value sets the area of the symbol; the side lengths will - increase with the square root of this value. - * For ``bar``, this represents the band size of the bar, in pixels. - * For ``text``, this represents the font size, in pixels. - - **Default value:** - - - * ``30`` for point, circle, square marks; width/height's ``step`` - * ``2`` for bar marks with discrete dimensions; - * ``5`` for bar marks with continuous dimensions; - * ``11`` for text marks. - smooth : anyOf(boolean, :class:`ExprRef`) - A boolean flag (default true) indicating if the image should be smoothed when - resized. If false, individual pixels should be scaled directly rather than - interpolated with smoothing. For SVG rendering, this option may not work in some - browsers due to lack of standardization. - startAngle : anyOf(float, :class:`ExprRef`) - The start angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default stroke color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove stroke. - - **Default value:** (None) - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOffset : anyOf(float, :class:`ExprRef`) - The offset in pixels at which to draw the group stroke and fill. If unspecified, the - default behavior is to dynamically offset stroked groups such that 1 pixel stroke - widths align with the pixel grid. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - tension : anyOf(float, :class:`ExprRef`) - Depending on the interpolation type, sets the tension parameter (for line and area - marks). - text : anyOf(:class:`Text`, :class:`ExprRef`) - Placeholder text if the ``text`` channel is not specified - theta : anyOf(float, :class:`ExprRef`) - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : anyOf(float, :class:`ExprRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - timeUnitBandPosition : float - Default relative band position for a time unit. If set to ``0``, the marks will be - positioned at the beginning of the time unit band step. If set to ``0.5``, the marks - will be positioned in the middle of the time unit band step. - timeUnitBandSize : float - Default relative band size for a time unit. If set to ``1``, the bandwidth of the - marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the - marks will be half of the time unit band step. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprRef`, None) - The tooltip text string to show upon mouse hover or an object defining which fields - should the tooltip be derived from. - - - * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from - ``encoding`` will be used. - * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the - highlighted data point will be used. - * If set to ``null`` or ``false``, then no tooltip will be used. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - - **Default value:** ``null`` - url : anyOf(:class:`URI`, :class:`ExprRef`) - The URL of the image file for image marks. - width : anyOf(float, :class:`ExprRef`) - Width of the marks. - x : anyOf(float, string, :class:`ExprRef`) - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : anyOf(float, string, :class:`ExprRef`) - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - y : anyOf(float, string, :class:`ExprRef`) - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : anyOf(float, string, :class:`ExprRef`) - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - """ - _schema = {'$ref': '#/definitions/RectConfig'} - - def __init__(self, align=Undefined, angle=Undefined, aria=Undefined, ariaRole=Undefined, - ariaRoleDescription=Undefined, aspect=Undefined, baseline=Undefined, - binSpacing=Undefined, blend=Undefined, color=Undefined, continuousBandSize=Undefined, - cornerRadius=Undefined, cornerRadiusBottomLeft=Undefined, - cornerRadiusBottomRight=Undefined, cornerRadiusTopLeft=Undefined, - cornerRadiusTopRight=Undefined, cursor=Undefined, description=Undefined, dir=Undefined, - discreteBandSize=Undefined, dx=Undefined, dy=Undefined, ellipsis=Undefined, - endAngle=Undefined, fill=Undefined, fillOpacity=Undefined, filled=Undefined, - font=Undefined, fontSize=Undefined, fontStyle=Undefined, fontWeight=Undefined, - height=Undefined, href=Undefined, innerRadius=Undefined, interpolate=Undefined, - invalid=Undefined, limit=Undefined, lineBreak=Undefined, lineHeight=Undefined, - opacity=Undefined, order=Undefined, orient=Undefined, outerRadius=Undefined, - padAngle=Undefined, radius=Undefined, radius2=Undefined, shape=Undefined, - size=Undefined, smooth=Undefined, startAngle=Undefined, stroke=Undefined, - strokeCap=Undefined, strokeDash=Undefined, strokeDashOffset=Undefined, - strokeJoin=Undefined, strokeMiterLimit=Undefined, strokeOffset=Undefined, - strokeOpacity=Undefined, strokeWidth=Undefined, tension=Undefined, text=Undefined, - theta=Undefined, theta2=Undefined, timeUnitBandPosition=Undefined, - timeUnitBandSize=Undefined, tooltip=Undefined, url=Undefined, width=Undefined, - x=Undefined, x2=Undefined, y=Undefined, y2=Undefined, **kwds): - super(RectConfig, self).__init__(align=align, angle=angle, aria=aria, ariaRole=ariaRole, - ariaRoleDescription=ariaRoleDescription, aspect=aspect, - baseline=baseline, binSpacing=binSpacing, blend=blend, - color=color, continuousBandSize=continuousBandSize, - cornerRadius=cornerRadius, - cornerRadiusBottomLeft=cornerRadiusBottomLeft, - cornerRadiusBottomRight=cornerRadiusBottomRight, - cornerRadiusTopLeft=cornerRadiusTopLeft, - cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, - description=description, dir=dir, - discreteBandSize=discreteBandSize, dx=dx, dy=dy, - ellipsis=ellipsis, endAngle=endAngle, fill=fill, - fillOpacity=fillOpacity, filled=filled, font=font, - fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, - height=height, href=href, innerRadius=innerRadius, - interpolate=interpolate, invalid=invalid, limit=limit, - lineBreak=lineBreak, lineHeight=lineHeight, opacity=opacity, - order=order, orient=orient, outerRadius=outerRadius, - padAngle=padAngle, radius=radius, radius2=radius2, shape=shape, - size=size, smooth=smooth, startAngle=startAngle, stroke=stroke, - strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, strokeOffset=strokeOffset, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - tension=tension, text=text, theta=theta, theta2=theta2, - timeUnitBandPosition=timeUnitBandPosition, - timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, url=url, - width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class RelativeBandSize(VegaLiteSchema): - """RelativeBandSize schema wrapper - - Mapping(required=[band]) - - Parameters - ---------- - - band : float - The relative band size. For example ``0.5`` means half of the band scale's band - width. - """ - _schema = {'$ref': '#/definitions/RelativeBandSize'} - - def __init__(self, band=Undefined, **kwds): - super(RelativeBandSize, self).__init__(band=band, **kwds) - - -class RepeatMapping(VegaLiteSchema): - """RepeatMapping schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - column : List(string) - An array of fields to be repeated horizontally. - row : List(string) - An array of fields to be repeated vertically. - """ - _schema = {'$ref': '#/definitions/RepeatMapping'} - - def __init__(self, column=Undefined, row=Undefined, **kwds): - super(RepeatMapping, self).__init__(column=column, row=row, **kwds) - - -class RepeatRef(Field): - """RepeatRef schema wrapper - - Mapping(required=[repeat]) - Reference to a repeated value. - - Parameters - ---------- - - repeat : enum('row', 'column', 'repeat', 'layer') - - """ - _schema = {'$ref': '#/definitions/RepeatRef'} - - def __init__(self, repeat=Undefined, **kwds): - super(RepeatRef, self).__init__(repeat=repeat, **kwds) - - -class Resolve(VegaLiteSchema): - """Resolve schema wrapper - - Mapping(required=[]) - Defines how scales, axes, and legends from different specs should be combined. Resolve is a - mapping from ``scale``, ``axis``, and ``legend`` to a mapping from channels to resolutions. - Scales and guides can be resolved to be ``"independent"`` or ``"shared"``. - - Parameters - ---------- - - axis : :class:`AxisResolveMap` - - legend : :class:`LegendResolveMap` - - scale : :class:`ScaleResolveMap` - - """ - _schema = {'$ref': '#/definitions/Resolve'} - - def __init__(self, axis=Undefined, legend=Undefined, scale=Undefined, **kwds): - super(Resolve, self).__init__(axis=axis, legend=legend, scale=scale, **kwds) - - -class ResolveMode(VegaLiteSchema): - """ResolveMode schema wrapper - - enum('independent', 'shared') - """ - _schema = {'$ref': '#/definitions/ResolveMode'} - - def __init__(self, *args): - super(ResolveMode, self).__init__(*args) - - -class RowColLayoutAlign(VegaLiteSchema): - """RowColLayoutAlign schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - column : :class:`LayoutAlign` - - row : :class:`LayoutAlign` - - """ - _schema = {'$ref': '#/definitions/RowCol'} - - def __init__(self, column=Undefined, row=Undefined, **kwds): - super(RowColLayoutAlign, self).__init__(column=column, row=row, **kwds) - - -class RowColboolean(VegaLiteSchema): - """RowColboolean schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - column : boolean - - row : boolean - - """ - _schema = {'$ref': '#/definitions/RowCol'} - - def __init__(self, column=Undefined, row=Undefined, **kwds): - super(RowColboolean, self).__init__(column=column, row=row, **kwds) - - -class RowColnumber(VegaLiteSchema): - """RowColnumber schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - column : float - - row : float - - """ - _schema = {'$ref': '#/definitions/RowCol'} - - def __init__(self, column=Undefined, row=Undefined, **kwds): - super(RowColnumber, self).__init__(column=column, row=row, **kwds) - - -class RowColumnEncodingFieldDef(VegaLiteSchema): - """RowColumnEncodingFieldDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - align : :class:`LayoutAlign` - The alignment to apply to row/column facet's subplot. The supported string values - are ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - **Default value:** ``"all"``. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - center : boolean - Boolean flag indicating if facet's subviews should be centered relative to their - respective rows or columns. - - **Default value:** ``false`` - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - header : anyOf(:class:`Header`, None) - An object defining properties of a facet's header. - sort : anyOf(:class:`SortArray`, :class:`SortOrder`, :class:`EncodingSortField`, None) - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` is not supported for ``row`` and ``column``. - spacing : float - The spacing in pixels between facet's sub-views. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/RowColumnEncodingFieldDef'} - - def __init__(self, aggregate=Undefined, align=Undefined, bandPosition=Undefined, bin=Undefined, - center=Undefined, field=Undefined, header=Undefined, sort=Undefined, spacing=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(RowColumnEncodingFieldDef, self).__init__(aggregate=aggregate, align=align, - bandPosition=bandPosition, bin=bin, - center=center, field=field, header=header, - sort=sort, spacing=spacing, timeUnit=timeUnit, - title=title, type=type, **kwds) - - -class Scale(VegaLiteSchema): - """Scale schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : anyOf(float, :class:`ExprRef`) - The alignment of the steps within the scale range. - - This value must lie in the range ``[0,1]``. A value of ``0.5`` indicates that the - steps should be centered within the range. A value of ``0`` or ``1`` may be used to - shift the bands to one side, say to position them adjacent to an axis. - - **Default value:** ``0.5`` - base : anyOf(float, :class:`ExprRef`) - The logarithm base of the ``log`` scale (default ``10`` ). - bins : :class:`ScaleBins` - Bin boundaries can be provided to scales as either an explicit array of bin - boundaries or as a bin specification object. The legal values are: - - - * An `array <../types/#Array>`__ literal of bin boundary values. For example, ``[0, - 5, 10, 15, 20]``. The array must include both starting and ending boundaries. The - previous example uses five values to indicate a total of four bin intervals: - [0-5), [5-10), [10-15), [15-20]. Array literals may include signal references as - elements. - * A `bin specification object - `__ that indicates the bin - *step* size, and optionally the *start* and *stop* boundaries. - * An array of bin boundaries over the scale domain. If provided, axes and legends - will use the bin boundaries to inform the choice of tick marks and text labels. - clamp : anyOf(boolean, :class:`ExprRef`) - If ``true``, values that exceed the data domain are clamped to either the minimum or - maximum range value - - **Default value:** derived from the `scale config - `__ 's ``clamp`` ( - ``true`` by default). - constant : anyOf(float, :class:`ExprRef`) - A constant determining the slope of the symlog function around zero. Only used for - ``symlog`` scales. - - **Default value:** ``1`` - domain : anyOf(List(anyOf(None, string, float, boolean, :class:`DateTime`, :class:`ExprRef`)), string, :class:`ParameterExtent`, :class:`DomainUnionWith`, :class:`ExprRef`) - Customized domain values in the form of constant values or dynamic values driven by - a parameter. - - 1) Constant ``domain`` for *quantitative* fields can take one of the following - forms: - - - * A two-element array with minimum and maximum values. To create a diverging scale, - this two-element array can be combined with the ``domainMid`` property. - * An array with more than two entries, for `Piecewise quantitative scales - `__. - * A string value ``"unaggregated"``, if the input field is aggregated, to indicate - that the domain should include the raw data values prior to the aggregation. - - 2) Constant ``domain`` for *temporal* fields can be a two-element array with minimum - and maximum values, in the form of either timestamps or the `DateTime definition - objects `__. - - 3) Constant ``domain`` for *ordinal* and *nominal* fields can be an array that lists - valid input values. - - 4) To combine (union) specified constant domain with the field's values, ``domain`` - can be an object with a ``unionWith`` property that specify constant domain to be - combined. For example, ``domain: {unionWith: [0, 100]}`` for a quantitative scale - means that the scale domain always includes ``[0, 100]``, but will include other - values in the fields beyond ``[0, 100]``. - - 5) Domain can also takes an object defining a field or encoding of a parameter that - `interactively determines - `__ the scale - domain. - domainMax : anyOf(float, :class:`DateTime`, :class:`ExprRef`) - Sets the maximum value in the scale domain, overriding the ``domain`` property. This - property is only intended for use with scales having continuous domains. - domainMid : anyOf(float, :class:`ExprRef`) - Inserts a single mid-point value into a two-element domain. The mid-point value must - lie between the domain minimum and maximum values. This property can be useful for - setting a midpoint for `diverging color scales - `__. The domainMid - property is only intended for use with scales supporting continuous, piecewise - domains. - domainMin : anyOf(float, :class:`DateTime`, :class:`ExprRef`) - Sets the minimum value in the scale domain, overriding the domain property. This - property is only intended for use with scales having continuous domains. - exponent : anyOf(float, :class:`ExprRef`) - The exponent of the ``pow`` scale. - interpolate : anyOf(:class:`ScaleInterpolateEnum`, :class:`ExprRef`, :class:`ScaleInterpolateParams`) - The interpolation method for range values. By default, a general interpolator for - numbers, dates, strings and colors (in HCL space) is used. For color ranges, this - property allows interpolation in alternative color spaces. Legal values include - ``rgb``, ``hsl``, ``hsl-long``, ``lab``, ``hcl``, ``hcl-long``, ``cubehelix`` and - ``cubehelix-long`` ('-long' variants use longer paths in polar coordinate spaces). - If object-valued, this property accepts an object with a string-valued *type* - property and an optional numeric *gamma* property applicable to rgb and cubehelix - interpolators. For more, see the `d3-interpolate documentation - `__. - - - * **Default value:** ``hcl`` - nice : anyOf(boolean, float, :class:`TimeInterval`, :class:`TimeIntervalStep`, :class:`ExprRef`) - Extending the domain so that it starts and ends on nice round values. This method - typically modifies the scale’s domain, and may only extend the bounds to the nearest - round value. Nicing is useful if the domain is computed from data and may be - irregular. For example, for a domain of *[0.201479…, 0.996679…]*, a nice domain - might be *[0.2, 1.0]*. - - For quantitative scales such as linear, ``nice`` can be either a boolean flag or a - number. If ``nice`` is a number, it will represent a desired tick count. This allows - greater control over the step size used to extend the bounds, guaranteeing that the - returned ticks will exactly cover the domain. - - For temporal fields with time and utc scales, the ``nice`` value can be a string - indicating the desired time interval. Legal values are ``"millisecond"``, - ``"second"``, ``"minute"``, ``"hour"``, ``"day"``, ``"week"``, ``"month"``, and - ``"year"``. Alternatively, ``time`` and ``utc`` scales can accept an object-valued - interval specifier of the form ``{"interval": "month", "step": 3}``, which includes - a desired number of interval steps. Here, the domain would snap to quarter (Jan, - Apr, Jul, Oct) boundaries. - - **Default value:** ``true`` for unbinned *quantitative* fields without explicit - domain bounds; ``false`` otherwise. - padding : anyOf(float, :class:`ExprRef`) - For * `continuous `__ * - scales, expands the scale domain to accommodate the specified number of pixels on - each of the scale range. The scale range must represent pixels for this parameter to - function as intended. Padding adjustment is performed prior to all other - adjustments, including the effects of the  ``zero``,  ``nice``,  ``domainMin``, and - ``domainMax``  properties. - - For * `band `__ * scales, - shortcut for setting ``paddingInner`` and ``paddingOuter`` to the same value. - - For * `point `__ * scales, - alias for ``paddingOuter``. - - **Default value:** For *continuous* scales, derived from the `scale config - `__ 's - ``continuousPadding``. For *band and point* scales, see ``paddingInner`` and - ``paddingOuter``. By default, Vega-Lite sets padding such that *width/height = - number of unique values * step*. - paddingInner : anyOf(float, :class:`ExprRef`) - The inner padding (spacing) within each band step of band scales, as a fraction of - the step size. This value must lie in the range [0,1]. - - For point scale, this property is invalid as point scales do not have internal band - widths (only step sizes between bands). - - **Default value:** derived from the `scale config - `__ 's - ``bandPaddingInner``. - paddingOuter : anyOf(float, :class:`ExprRef`) - The outer padding (spacing) at the ends of the range of band and point scales, as a - fraction of the step size. This value must lie in the range [0,1]. - - **Default value:** derived from the `scale config - `__ 's ``bandPaddingOuter`` - for band scales and ``pointPadding`` for point scales. By default, Vega-Lite sets - outer padding such that *width/height = number of unique values * step*. - range : anyOf(:class:`RangeEnum`, List(anyOf(float, string, List(float), :class:`ExprRef`)), :class:`FieldRange`) - The range of the scale. One of: - - - A string indicating a `pre-defined named scale range - `__ (e.g., example, - ``"symbol"``, or ``"diverging"`` ). - - For `continuous scales - `__, two-element array - indicating minimum and maximum values, or an array with more than two entries for - specifying a `piecewise scale - `__. - - For `discrete `__ and - `discretizing `__ - scales, an array of desired output values or an object with a ``field`` property - representing the range values. For example, if a field ``color`` contains CSS color - names, we can set ``range`` to ``{field: "color"}``. - - **Notes:** - - 1) For color scales you can also specify a color `scheme - `__ instead of ``range``. - - 2) Any directly specified ``range`` for ``x`` and ``y`` channels will be ignored. - Range can be customized via the view's corresponding `size - `__ ( ``width`` and ``height`` ). - rangeMax : anyOf(float, string, :class:`ExprRef`) - Sets the maximum value in the scale range, overriding the ``range`` property or the - default range. This property is only intended for use with scales having continuous - ranges. - rangeMin : anyOf(float, string, :class:`ExprRef`) - Sets the minimum value in the scale range, overriding the ``range`` property or the - default range. This property is only intended for use with scales having continuous - ranges. - reverse : anyOf(boolean, :class:`ExprRef`) - If true, reverses the order of the scale range. **Default value:** ``false``. - round : anyOf(boolean, :class:`ExprRef`) - If ``true``, rounds numeric output values to integers. This can be helpful for - snapping to the pixel grid. - - **Default value:** ``false``. - scheme : anyOf(string, :class:`SchemeParams`, :class:`ExprRef`) - A string indicating a color `scheme - `__ name (e.g., - ``"category10"`` or ``"blues"`` ) or a `scheme parameter object - `__. - - Discrete color schemes may be used with `discrete - `__ or `discretizing - `__ scales. - Continuous color schemes are intended for use with color scales. - - For the full list of supported schemes, please refer to the `Vega Scheme - `__ reference. - type : :class:`ScaleType` - The type of scale. Vega-Lite supports the following categories of scale types: - - 1) `Continuous Scales - `__ -- mapping - continuous domains to continuous output ranges ( `"linear" - `__, `"pow" - `__, `"sqrt" - `__, `"symlog" - `__, `"log" - `__, `"time" - `__, `"utc" - `__. - - 2) `Discrete Scales `__ - -- mapping discrete domains to discrete ( `"ordinal" - `__ ) or continuous ( - `"band" `__ and `"point" - `__ ) output ranges. - - 3) `Discretizing Scales - `__ -- mapping - continuous domains to discrete output ranges `"bin-ordinal" - `__, `"quantile" - `__, `"quantize" - `__ and `"threshold" - `__. - - **Default value:** please see the `scale type table - `__. - zero : anyOf(boolean, :class:`ExprRef`) - If ``true``, ensures that a zero baseline value is included in the scale domain. - - **Default value:** ``true`` for x and y channels if the quantitative field is not - binned and no custom ``domain`` is provided; ``false`` otherwise. - - **Note:** Log, time, and utc scales do not support ``zero``. - """ - _schema = {'$ref': '#/definitions/Scale'} - - def __init__(self, align=Undefined, base=Undefined, bins=Undefined, clamp=Undefined, - constant=Undefined, domain=Undefined, domainMax=Undefined, domainMid=Undefined, - domainMin=Undefined, exponent=Undefined, interpolate=Undefined, nice=Undefined, - padding=Undefined, paddingInner=Undefined, paddingOuter=Undefined, range=Undefined, - rangeMax=Undefined, rangeMin=Undefined, reverse=Undefined, round=Undefined, - scheme=Undefined, type=Undefined, zero=Undefined, **kwds): - super(Scale, self).__init__(align=align, base=base, bins=bins, clamp=clamp, constant=constant, - domain=domain, domainMax=domainMax, domainMid=domainMid, - domainMin=domainMin, exponent=exponent, interpolate=interpolate, - nice=nice, padding=padding, paddingInner=paddingInner, - paddingOuter=paddingOuter, range=range, rangeMax=rangeMax, - rangeMin=rangeMin, reverse=reverse, round=round, scheme=scheme, - type=type, zero=zero, **kwds) - - -class ScaleBins(VegaLiteSchema): - """ScaleBins schema wrapper - - anyOf(List(float), :class:`ScaleBinParams`) - """ - _schema = {'$ref': '#/definitions/ScaleBins'} - - def __init__(self, *args, **kwds): - super(ScaleBins, self).__init__(*args, **kwds) - - -class ScaleBinParams(ScaleBins): - """ScaleBinParams schema wrapper - - Mapping(required=[step]) - - Parameters - ---------- - - step : float - The step size defining the bin interval width. - start : float - The starting (lowest-valued) bin boundary. - - **Default value:** The lowest value of the scale domain will be used. - stop : float - The stopping (highest-valued) bin boundary. - - **Default value:** The highest value of the scale domain will be used. - """ - _schema = {'$ref': '#/definitions/ScaleBinParams'} - - def __init__(self, step=Undefined, start=Undefined, stop=Undefined, **kwds): - super(ScaleBinParams, self).__init__(step=step, start=start, stop=stop, **kwds) - - -class ScaleConfig(VegaLiteSchema): - """ScaleConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPaddingInner : anyOf(float, :class:`ExprRef`) - Default inner padding for ``x`` and ``y`` band scales. - - **Default value:** - - - * ``nestedOffsetPaddingInner`` for x/y scales with nested x/y offset scales. - * ``barBandPaddingInner`` for bar marks ( ``0.1`` by default) - * ``rectBandPaddingInner`` for rect and other marks ( ``0`` by default) - bandPaddingOuter : anyOf(float, :class:`ExprRef`) - Default outer padding for ``x`` and ``y`` band scales. - - **Default value:** ``paddingInner/2`` (which makes *width/height = number of unique - values * step* ) - bandWithNestedOffsetPaddingInner : anyOf(float, :class:`ExprRef`) - Default inner padding for ``x`` and ``y`` band scales with nested ``xOffset`` and - ``yOffset`` encoding. - - **Default value:** ``0.2`` - bandWithNestedOffsetPaddingOuter : anyOf(float, :class:`ExprRef`) - Default outer padding for ``x`` and ``y`` band scales with nested ``xOffset`` and - ``yOffset`` encoding. - - **Default value:** ``0.2`` - barBandPaddingInner : anyOf(float, :class:`ExprRef`) - Default inner padding for ``x`` and ``y`` band-ordinal scales of ``"bar"`` marks. - - **Default value:** ``0.1`` - clamp : anyOf(boolean, :class:`ExprRef`) - If true, values that exceed the data domain are clamped to either the minimum or - maximum range value - continuousPadding : anyOf(float, :class:`ExprRef`) - Default padding for continuous x/y scales. - - **Default:** The bar width for continuous x-scale of a vertical bar and continuous - y-scale of a horizontal bar.; ``0`` otherwise. - maxBandSize : float - The default max value for mapping quantitative fields to bar's size/bandSize. - - If undefined (default), we will use the axis's size (width or height) - 1. - maxFontSize : float - The default max value for mapping quantitative fields to text's size/fontSize. - - **Default value:** ``40`` - maxOpacity : float - Default max opacity for mapping a field to opacity. - - **Default value:** ``0.8`` - maxSize : float - Default max value for point size scale. - maxStrokeWidth : float - Default max strokeWidth for the scale of strokeWidth for rule and line marks and of - size for trail marks. - - **Default value:** ``4`` - minBandSize : float - The default min value for mapping quantitative fields to bar and tick's - size/bandSize scale with zero=false. - - **Default value:** ``2`` - minFontSize : float - The default min value for mapping quantitative fields to tick's size/fontSize scale - with zero=false - - **Default value:** ``8`` - minOpacity : float - Default minimum opacity for mapping a field to opacity. - - **Default value:** ``0.3`` - minSize : float - Default minimum value for point size scale with zero=false. - - **Default value:** ``9`` - minStrokeWidth : float - Default minimum strokeWidth for the scale of strokeWidth for rule and line marks and - of size for trail marks with zero=false. - - **Default value:** ``1`` - offsetBandPaddingInner : anyOf(float, :class:`ExprRef`) - Default padding inner for xOffset/yOffset's band scales. - - **Default Value:** ``0`` - offsetBandPaddingOuter : anyOf(float, :class:`ExprRef`) - Default padding outer for xOffset/yOffset's band scales. - - **Default Value:** ``0`` - pointPadding : anyOf(float, :class:`ExprRef`) - Default outer padding for ``x`` and ``y`` point-ordinal scales. - - **Default value:** ``0.5`` (which makes *width/height = number of unique values * - step* ) - quantileCount : float - Default range cardinality for `quantile - `__ scale. - - **Default value:** ``4`` - quantizeCount : float - Default range cardinality for `quantize - `__ scale. - - **Default value:** ``4`` - rectBandPaddingInner : anyOf(float, :class:`ExprRef`) - Default inner padding for ``x`` and ``y`` band-ordinal scales of ``"rect"`` marks. - - **Default value:** ``0`` - round : anyOf(boolean, :class:`ExprRef`) - If true, rounds numeric output values to integers. This can be helpful for snapping - to the pixel grid. (Only available for ``x``, ``y``, and ``size`` scales.) - useUnaggregatedDomain : boolean - Use the source data range before aggregation as scale domain instead of aggregated - data for aggregate axis. - - This is equivalent to setting ``domain`` to ``"unaggregate"`` for aggregated - *quantitative* fields by default. - - This property only works with aggregate functions that produce values within the raw - data domain ( ``"mean"``, ``"average"``, ``"median"``, ``"q1"``, ``"q3"``, - ``"min"``, ``"max"`` ). For other aggregations that produce values outside of the - raw data domain (e.g. ``"count"``, ``"sum"`` ), this property is ignored. - - **Default value:** ``false`` - xReverse : anyOf(boolean, :class:`ExprRef`) - Reverse x-scale by default (useful for right-to-left charts). - zero : boolean - Default ``scale.zero`` for `continuous - `__ scales except for - (1) x/y-scales of non-ranged bar or area charts and (2) size scales. - - **Default value:** ``true`` - """ - _schema = {'$ref': '#/definitions/ScaleConfig'} - - def __init__(self, bandPaddingInner=Undefined, bandPaddingOuter=Undefined, - bandWithNestedOffsetPaddingInner=Undefined, bandWithNestedOffsetPaddingOuter=Undefined, - barBandPaddingInner=Undefined, clamp=Undefined, continuousPadding=Undefined, - maxBandSize=Undefined, maxFontSize=Undefined, maxOpacity=Undefined, maxSize=Undefined, - maxStrokeWidth=Undefined, minBandSize=Undefined, minFontSize=Undefined, - minOpacity=Undefined, minSize=Undefined, minStrokeWidth=Undefined, - offsetBandPaddingInner=Undefined, offsetBandPaddingOuter=Undefined, - pointPadding=Undefined, quantileCount=Undefined, quantizeCount=Undefined, - rectBandPaddingInner=Undefined, round=Undefined, useUnaggregatedDomain=Undefined, - xReverse=Undefined, zero=Undefined, **kwds): - super(ScaleConfig, self).__init__(bandPaddingInner=bandPaddingInner, - bandPaddingOuter=bandPaddingOuter, - bandWithNestedOffsetPaddingInner=bandWithNestedOffsetPaddingInner, - bandWithNestedOffsetPaddingOuter=bandWithNestedOffsetPaddingOuter, - barBandPaddingInner=barBandPaddingInner, clamp=clamp, - continuousPadding=continuousPadding, maxBandSize=maxBandSize, - maxFontSize=maxFontSize, maxOpacity=maxOpacity, - maxSize=maxSize, maxStrokeWidth=maxStrokeWidth, - minBandSize=minBandSize, minFontSize=minFontSize, - minOpacity=minOpacity, minSize=minSize, - minStrokeWidth=minStrokeWidth, - offsetBandPaddingInner=offsetBandPaddingInner, - offsetBandPaddingOuter=offsetBandPaddingOuter, - pointPadding=pointPadding, quantileCount=quantileCount, - quantizeCount=quantizeCount, - rectBandPaddingInner=rectBandPaddingInner, round=round, - useUnaggregatedDomain=useUnaggregatedDomain, - xReverse=xReverse, zero=zero, **kwds) - - -class ScaleDatumDef(OffsetDef): - """ScaleDatumDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/ScaleDatumDef'} - - def __init__(self, bandPosition=Undefined, datum=Undefined, scale=Undefined, title=Undefined, - type=Undefined, **kwds): - super(ScaleDatumDef, self).__init__(bandPosition=bandPosition, datum=datum, scale=scale, - title=title, type=type, **kwds) - - -class ScaleFieldDef(OffsetDef): - """ScaleFieldDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - sort : :class:`Sort` - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A string indicating an encoding channel name to sort by - `__ (e.g., - ``"x"`` or ``"y"`` ) with an optional minus prefix for descending sort (e.g., - ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a - sort-by-encoding definition - `__. For - example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": - "descending"}``. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` and sorting by another channel is not supported for ``row`` and - ``column``. - - **See also:** `sort `__ - documentation. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/ScaleFieldDef'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - scale=Undefined, sort=Undefined, timeUnit=Undefined, title=Undefined, type=Undefined, - **kwds): - super(ScaleFieldDef, self).__init__(aggregate=aggregate, bandPosition=bandPosition, bin=bin, - field=field, scale=scale, sort=sort, timeUnit=timeUnit, - title=title, type=type, **kwds) - - -class ScaleInterpolateEnum(VegaLiteSchema): - """ScaleInterpolateEnum schema wrapper - - enum('rgb', 'lab', 'hcl', 'hsl', 'hsl-long', 'hcl-long', 'cubehelix', 'cubehelix-long') - """ - _schema = {'$ref': '#/definitions/ScaleInterpolateEnum'} - - def __init__(self, *args): - super(ScaleInterpolateEnum, self).__init__(*args) - - -class ScaleInterpolateParams(VegaLiteSchema): - """ScaleInterpolateParams schema wrapper - - Mapping(required=[type]) - - Parameters - ---------- - - type : enum('rgb', 'cubehelix', 'cubehelix-long') - - gamma : float - - """ - _schema = {'$ref': '#/definitions/ScaleInterpolateParams'} - - def __init__(self, type=Undefined, gamma=Undefined, **kwds): - super(ScaleInterpolateParams, self).__init__(type=type, gamma=gamma, **kwds) - - -class ScaleResolveMap(VegaLiteSchema): - """ScaleResolveMap schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - angle : :class:`ResolveMode` - - color : :class:`ResolveMode` - - fill : :class:`ResolveMode` - - fillOpacity : :class:`ResolveMode` - - opacity : :class:`ResolveMode` - - radius : :class:`ResolveMode` - - shape : :class:`ResolveMode` - - size : :class:`ResolveMode` - - stroke : :class:`ResolveMode` - - strokeDash : :class:`ResolveMode` - - strokeOpacity : :class:`ResolveMode` - - strokeWidth : :class:`ResolveMode` - - theta : :class:`ResolveMode` - - x : :class:`ResolveMode` - - xOffset : :class:`ResolveMode` - - y : :class:`ResolveMode` - - yOffset : :class:`ResolveMode` - - """ - _schema = {'$ref': '#/definitions/ScaleResolveMap'} - - def __init__(self, angle=Undefined, color=Undefined, fill=Undefined, fillOpacity=Undefined, - opacity=Undefined, radius=Undefined, shape=Undefined, size=Undefined, stroke=Undefined, - strokeDash=Undefined, strokeOpacity=Undefined, strokeWidth=Undefined, theta=Undefined, - x=Undefined, xOffset=Undefined, y=Undefined, yOffset=Undefined, **kwds): - super(ScaleResolveMap, self).__init__(angle=angle, color=color, fill=fill, - fillOpacity=fillOpacity, opacity=opacity, radius=radius, - shape=shape, size=size, stroke=stroke, - strokeDash=strokeDash, strokeOpacity=strokeOpacity, - strokeWidth=strokeWidth, theta=theta, x=x, - xOffset=xOffset, y=y, yOffset=yOffset, **kwds) - - -class ScaleType(VegaLiteSchema): - """ScaleType schema wrapper - - enum('linear', 'log', 'pow', 'sqrt', 'symlog', 'identity', 'sequential', 'time', 'utc', - 'quantile', 'quantize', 'threshold', 'bin-ordinal', 'ordinal', 'point', 'band') - """ - _schema = {'$ref': '#/definitions/ScaleType'} - - def __init__(self, *args): - super(ScaleType, self).__init__(*args) - - -class SchemeParams(VegaLiteSchema): - """SchemeParams schema wrapper - - Mapping(required=[name]) - - Parameters - ---------- - - name : string - A color scheme name for ordinal scales (e.g., ``"category10"`` or ``"blues"`` ). - - For the full list of supported schemes, please refer to the `Vega Scheme - `__ reference. - count : float - The number of colors to use in the scheme. This can be useful for scale types such - as ``"quantize"``, which use the length of the scale range to determine the number - of discrete bins for the scale domain. - extent : List(float) - The extent of the color range to use. For example ``[0.2, 1]`` will rescale the - color scheme such that color values in the range *[0, 0.2)* are excluded from the - scheme. - """ - _schema = {'$ref': '#/definitions/SchemeParams'} - - def __init__(self, name=Undefined, count=Undefined, extent=Undefined, **kwds): - super(SchemeParams, self).__init__(name=name, count=count, extent=extent, **kwds) - - -class SecondaryFieldDef(Position2Def): - """SecondaryFieldDef schema wrapper - - Mapping(required=[]) - A field definition of a secondary channel that shares a scale with another primary channel. - For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``. - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : None - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - """ - _schema = {'$ref': '#/definitions/SecondaryFieldDef'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - timeUnit=Undefined, title=Undefined, **kwds): - super(SecondaryFieldDef, self).__init__(aggregate=aggregate, bandPosition=bandPosition, bin=bin, - field=field, timeUnit=timeUnit, title=title, **kwds) - - -class SelectionConfig(VegaLiteSchema): - """SelectionConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - interval : :class:`IntervalSelectionConfigWithoutType` - The default definition for an `interval - `__ selection. All - properties and transformations for an interval selection definition (except ``type`` - ) may be specified here. - - For instance, setting ``interval`` to ``{"translate": false}`` disables the ability - to move interval selections by default. - point : :class:`PointSelectionConfigWithoutType` - The default definition for a `point - `__ selection. All - properties and transformations for a point selection definition (except ``type`` ) - may be specified here. - - For instance, setting ``point`` to ``{"on": "dblclick"}`` populates point selections - on double-click by default. - """ - _schema = {'$ref': '#/definitions/SelectionConfig'} - - def __init__(self, interval=Undefined, point=Undefined, **kwds): - super(SelectionConfig, self).__init__(interval=interval, point=point, **kwds) - - -class SelectionInit(VegaLiteSchema): - """SelectionInit schema wrapper - - anyOf(:class:`PrimitiveValue`, :class:`DateTime`) - """ - _schema = {'$ref': '#/definitions/SelectionInit'} - - def __init__(self, *args, **kwds): - super(SelectionInit, self).__init__(*args, **kwds) - - -class DateTime(SelectionInit): - """DateTime schema wrapper - - Mapping(required=[]) - Object for defining datetime in Vega-Lite Filter. If both month and quarter are provided, - month has higher precedence. ``day`` cannot be combined with other date. We accept string - for month and day names. - - Parameters - ---------- - - date : float - Integer value representing the date (day of the month) from 1-31. - day : anyOf(:class:`Day`, string) - Value representing the day of a week. This can be one of: (1) integer value -- ``1`` - represents Monday; (2) case-insensitive day name (e.g., ``"Monday"`` ); (3) - case-insensitive, 3-character short day name (e.g., ``"Mon"`` ). - - **Warning:** A DateTime definition object with ``day`` ** should not be combined - with ``year``, ``quarter``, ``month``, or ``date``. - hours : float - Integer value representing the hour of a day from 0-23. - milliseconds : float - Integer value representing the millisecond segment of time. - minutes : float - Integer value representing the minute segment of time from 0-59. - month : anyOf(:class:`Month`, string) - One of: (1) integer value representing the month from ``1`` - ``12``. ``1`` - represents January; (2) case-insensitive month name (e.g., ``"January"`` ); (3) - case-insensitive, 3-character short month name (e.g., ``"Jan"`` ). - quarter : float - Integer value representing the quarter of the year (from 1-4). - seconds : float - Integer value representing the second segment (0-59) of a time value - utc : boolean - A boolean flag indicating if date time is in utc time. If false, the date time is in - local time - year : float - Integer value representing the year. - """ - _schema = {'$ref': '#/definitions/DateTime'} - - def __init__(self, date=Undefined, day=Undefined, hours=Undefined, milliseconds=Undefined, - minutes=Undefined, month=Undefined, quarter=Undefined, seconds=Undefined, - utc=Undefined, year=Undefined, **kwds): - super(DateTime, self).__init__(date=date, day=day, hours=hours, milliseconds=milliseconds, - minutes=minutes, month=month, quarter=quarter, seconds=seconds, - utc=utc, year=year, **kwds) - - -class PrimitiveValue(SelectionInit): - """PrimitiveValue schema wrapper - - anyOf(float, string, boolean, None) - """ - _schema = {'$ref': '#/definitions/PrimitiveValue'} - - def __init__(self, *args): - super(PrimitiveValue, self).__init__(*args) - - -class SelectionInitInterval(VegaLiteSchema): - """SelectionInitInterval schema wrapper - - anyOf(:class:`Vector2boolean`, :class:`Vector2number`, :class:`Vector2string`, - :class:`Vector2DateTime`) - """ - _schema = {'$ref': '#/definitions/SelectionInitInterval'} - - def __init__(self, *args, **kwds): - super(SelectionInitInterval, self).__init__(*args, **kwds) - - -class SelectionInitIntervalMapping(VegaLiteSchema): - """SelectionInitIntervalMapping schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/SelectionInitIntervalMapping'} - - def __init__(self, **kwds): - super(SelectionInitIntervalMapping, self).__init__(**kwds) - - -class SelectionInitMapping(VegaLiteSchema): - """SelectionInitMapping schema wrapper - - Mapping(required=[]) - """ - _schema = {'$ref': '#/definitions/SelectionInitMapping'} - - def __init__(self, **kwds): - super(SelectionInitMapping, self).__init__(**kwds) - - -class SelectionParameter(VegaLiteSchema): - """SelectionParameter schema wrapper - - Mapping(required=[name, select]) - - Parameters - ---------- - - name : :class:`ParameterName` - Required. A unique name for the selection parameter. Selection names should be valid - JavaScript identifiers: they should contain only alphanumeric characters (or "$", or - "_") and may not start with a digit. Reserved keywords that may not be used as - parameter names are "datum", "event", "item", and "parent". - select : anyOf(:class:`SelectionType`, :class:`PointSelectionConfig`, :class:`IntervalSelectionConfig`) - Determines the default event processing and data query for the selection. Vega-Lite - currently supports two selection types: - - - * ``"point"`` -- to select multiple discrete data values; the first value is - selected on ``click`` and additional values toggled on shift-click. - * ``"interval"`` -- to select a continuous range of data values on ``drag``. - bind : anyOf(:class:`Binding`, Mapping(required=[]), :class:`LegendBinding`, string) - When set, a selection is populated by input elements (also known as dynamic query - widgets) or by interacting with the corresponding legend. Direct manipulation - interaction is disabled by default; to re-enable it, set the selection's `on - `__ - property. - - Legend bindings are restricted to selections that only specify a single field or - encoding. - - Query widget binding takes the form of Vega's `input element binding definition - `__ or can be a mapping between - projected field/encodings and binding definitions. - - **See also:** `bind `__ - documentation. - value : anyOf(:class:`SelectionInit`, List(:class:`SelectionInitMapping`), :class:`SelectionInitIntervalMapping`) - Initialize the selection with a mapping between `projected channels or field names - `__ and initial - values. - - **See also:** `init `__ - documentation. - """ - _schema = {'$ref': '#/definitions/SelectionParameter'} - - def __init__(self, name=Undefined, select=Undefined, bind=Undefined, value=Undefined, **kwds): - super(SelectionParameter, self).__init__(name=name, select=select, bind=bind, value=value, - **kwds) - - -class SelectionResolution(VegaLiteSchema): - """SelectionResolution schema wrapper - - enum('global', 'union', 'intersect') - """ - _schema = {'$ref': '#/definitions/SelectionResolution'} - - def __init__(self, *args): - super(SelectionResolution, self).__init__(*args) - - -class SelectionType(VegaLiteSchema): - """SelectionType schema wrapper - - enum('point', 'interval') - """ - _schema = {'$ref': '#/definitions/SelectionType'} - - def __init__(self, *args): - super(SelectionType, self).__init__(*args) - - -class SequenceGenerator(Generator): - """SequenceGenerator schema wrapper - - Mapping(required=[sequence]) - - Parameters - ---------- - - sequence : :class:`SequenceParams` - Generate a sequence of numbers. - name : string - Provide a placeholder name and bind data at runtime. - """ - _schema = {'$ref': '#/definitions/SequenceGenerator'} - - def __init__(self, sequence=Undefined, name=Undefined, **kwds): - super(SequenceGenerator, self).__init__(sequence=sequence, name=name, **kwds) - - -class SequenceParams(VegaLiteSchema): - """SequenceParams schema wrapper - - Mapping(required=[start, stop]) - - Parameters - ---------- - - start : float - The starting value of the sequence (inclusive). - stop : float - The ending value of the sequence (exclusive). - step : float - The step value between sequence entries. - - **Default value:** ``1`` - as : :class:`FieldName` - The name of the generated sequence field. - - **Default value:** ``"data"`` - """ - _schema = {'$ref': '#/definitions/SequenceParams'} - - def __init__(self, start=Undefined, stop=Undefined, step=Undefined, **kwds): - super(SequenceParams, self).__init__(start=start, stop=stop, step=step, **kwds) - - -class SequentialMultiHue(ColorScheme): - """SequentialMultiHue schema wrapper - - enum('turbo', 'viridis', 'inferno', 'magma', 'plasma', 'cividis', 'bluegreen', - 'bluegreen-3', 'bluegreen-4', 'bluegreen-5', 'bluegreen-6', 'bluegreen-7', 'bluegreen-8', - 'bluegreen-9', 'bluepurple', 'bluepurple-3', 'bluepurple-4', 'bluepurple-5', 'bluepurple-6', - 'bluepurple-7', 'bluepurple-8', 'bluepurple-9', 'goldgreen', 'goldgreen-3', 'goldgreen-4', - 'goldgreen-5', 'goldgreen-6', 'goldgreen-7', 'goldgreen-8', 'goldgreen-9', 'goldorange', - 'goldorange-3', 'goldorange-4', 'goldorange-5', 'goldorange-6', 'goldorange-7', - 'goldorange-8', 'goldorange-9', 'goldred', 'goldred-3', 'goldred-4', 'goldred-5', - 'goldred-6', 'goldred-7', 'goldred-8', 'goldred-9', 'greenblue', 'greenblue-3', - 'greenblue-4', 'greenblue-5', 'greenblue-6', 'greenblue-7', 'greenblue-8', 'greenblue-9', - 'orangered', 'orangered-3', 'orangered-4', 'orangered-5', 'orangered-6', 'orangered-7', - 'orangered-8', 'orangered-9', 'purplebluegreen', 'purplebluegreen-3', 'purplebluegreen-4', - 'purplebluegreen-5', 'purplebluegreen-6', 'purplebluegreen-7', 'purplebluegreen-8', - 'purplebluegreen-9', 'purpleblue', 'purpleblue-3', 'purpleblue-4', 'purpleblue-5', - 'purpleblue-6', 'purpleblue-7', 'purpleblue-8', 'purpleblue-9', 'purplered', 'purplered-3', - 'purplered-4', 'purplered-5', 'purplered-6', 'purplered-7', 'purplered-8', 'purplered-9', - 'redpurple', 'redpurple-3', 'redpurple-4', 'redpurple-5', 'redpurple-6', 'redpurple-7', - 'redpurple-8', 'redpurple-9', 'yellowgreenblue', 'yellowgreenblue-3', 'yellowgreenblue-4', - 'yellowgreenblue-5', 'yellowgreenblue-6', 'yellowgreenblue-7', 'yellowgreenblue-8', - 'yellowgreenblue-9', 'yellowgreen', 'yellowgreen-3', 'yellowgreen-4', 'yellowgreen-5', - 'yellowgreen-6', 'yellowgreen-7', 'yellowgreen-8', 'yellowgreen-9', 'yelloworangebrown', - 'yelloworangebrown-3', 'yelloworangebrown-4', 'yelloworangebrown-5', 'yelloworangebrown-6', - 'yelloworangebrown-7', 'yelloworangebrown-8', 'yelloworangebrown-9', 'yelloworangered', - 'yelloworangered-3', 'yelloworangered-4', 'yelloworangered-5', 'yelloworangered-6', - 'yelloworangered-7', 'yelloworangered-8', 'yelloworangered-9', 'darkblue', 'darkblue-3', - 'darkblue-4', 'darkblue-5', 'darkblue-6', 'darkblue-7', 'darkblue-8', 'darkblue-9', - 'darkgold', 'darkgold-3', 'darkgold-4', 'darkgold-5', 'darkgold-6', 'darkgold-7', - 'darkgold-8', 'darkgold-9', 'darkgreen', 'darkgreen-3', 'darkgreen-4', 'darkgreen-5', - 'darkgreen-6', 'darkgreen-7', 'darkgreen-8', 'darkgreen-9', 'darkmulti', 'darkmulti-3', - 'darkmulti-4', 'darkmulti-5', 'darkmulti-6', 'darkmulti-7', 'darkmulti-8', 'darkmulti-9', - 'darkred', 'darkred-3', 'darkred-4', 'darkred-5', 'darkred-6', 'darkred-7', 'darkred-8', - 'darkred-9', 'lightgreyred', 'lightgreyred-3', 'lightgreyred-4', 'lightgreyred-5', - 'lightgreyred-6', 'lightgreyred-7', 'lightgreyred-8', 'lightgreyred-9', 'lightgreyteal', - 'lightgreyteal-3', 'lightgreyteal-4', 'lightgreyteal-5', 'lightgreyteal-6', - 'lightgreyteal-7', 'lightgreyteal-8', 'lightgreyteal-9', 'lightmulti', 'lightmulti-3', - 'lightmulti-4', 'lightmulti-5', 'lightmulti-6', 'lightmulti-7', 'lightmulti-8', - 'lightmulti-9', 'lightorange', 'lightorange-3', 'lightorange-4', 'lightorange-5', - 'lightorange-6', 'lightorange-7', 'lightorange-8', 'lightorange-9', 'lighttealblue', - 'lighttealblue-3', 'lighttealblue-4', 'lighttealblue-5', 'lighttealblue-6', - 'lighttealblue-7', 'lighttealblue-8', 'lighttealblue-9') - """ - _schema = {'$ref': '#/definitions/SequentialMultiHue'} - - def __init__(self, *args): - super(SequentialMultiHue, self).__init__(*args) - - -class SequentialSingleHue(ColorScheme): - """SequentialSingleHue schema wrapper - - enum('blues', 'tealblues', 'teals', 'greens', 'browns', 'greys', 'purples', 'warmgreys', - 'reds', 'oranges') - """ - _schema = {'$ref': '#/definitions/SequentialSingleHue'} - - def __init__(self, *args): - super(SequentialSingleHue, self).__init__(*args) - - -class ShapeDef(VegaLiteSchema): - """ShapeDef schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull`, - :class:`FieldOrDatumDefWithConditionDatumDefstringnull`, - :class:`ValueDefWithConditionMarkPropFieldOrDatumDefTypeForShapestringnull`) - """ - _schema = {'$ref': '#/definitions/ShapeDef'} - - def __init__(self, *args, **kwds): - super(ShapeDef, self).__init__(*args, **kwds) - - -class FieldOrDatumDefWithConditionDatumDefstringnull(MarkPropDefstringnullTypeForShape, ShapeDef): - """FieldOrDatumDefWithConditionDatumDefstringnull schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - condition : anyOf(:class:`ConditionalValueDefstringnullExprRef`, List(:class:`ConditionalValueDefstringnullExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, bandPosition=Undefined, condition=Undefined, datum=Undefined, title=Undefined, - type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionDatumDefstringnull, self).__init__(bandPosition=bandPosition, - condition=condition, - datum=datum, title=title, - type=type, **kwds) - - -class FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull(MarkPropDefstringnullTypeForShape, ShapeDef): - """FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - condition : anyOf(:class:`ConditionalValueDefstringnullExprRef`, List(:class:`ConditionalValueDefstringnullExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - legend : anyOf(:class:`Legend`, None) - An object defining properties of the legend. If ``null``, the legend for the - encoding channel will be removed. - - **Default value:** If undefined, default `legend properties - `__ are applied. - - **See also:** `legend `__ - documentation. - scale : anyOf(:class:`Scale`, None) - An object defining properties of the channel's scale, which is the function that - transforms values in the data domain (numbers, dates, strings, etc) to visual values - (pixels, colors, sizes) of the encoding channels. - - If ``null``, the scale will be `disabled and the data value will be directly encoded - `__. - - **Default value:** If undefined, default `scale properties - `__ are applied. - - **See also:** `scale `__ - documentation. - sort : :class:`Sort` - Sort order for the encoded field. - - For continuous fields (quantitative or temporal), ``sort`` can be either - ``"ascending"`` or ``"descending"``. - - For discrete fields, ``sort`` can be one of the following: - - - * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in - JavaScript. - * `A string indicating an encoding channel name to sort by - `__ (e.g., - ``"x"`` or ``"y"`` ) with an optional minus prefix for descending sort (e.g., - ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a - sort-by-encoding definition - `__. For - example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": - "descending"}``. - * `A sort field definition - `__ for sorting by - another field. - * `An array specifying the field values in preferred order - `__. In this case, the - sort order will obey the values in the array, followed by any unspecified values - in their original order. For discrete time field, values in the sort array can be - `date-time definition objects - `__. In addition, for time - units ``"month"`` and ``"day"``, the values can be the month or day names (case - insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"`` ). - * ``null`` indicating no sort. - - **Default value:** ``"ascending"`` - - **Note:** ``null`` and sorting by another channel is not supported for ``row`` and - ``column``. - - **See also:** `sort `__ - documentation. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`TypeForShape` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition,(string|null)>'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, legend=Undefined, scale=Undefined, sort=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull, self).__init__(aggregate=aggregate, - bandPosition=bandPosition, - bin=bin, - condition=condition, - field=field, - legend=legend, - scale=scale, - sort=sort, - timeUnit=timeUnit, - title=title, - type=type, - **kwds) - - -class SharedEncoding(VegaLiteSchema): - """SharedEncoding schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - angle : Mapping(required=[]) - - color : Mapping(required=[]) - - description : Mapping(required=[]) - - detail : anyOf(:class:`FieldDefWithoutScale`, List(:class:`FieldDefWithoutScale`)) - Additional levels of detail for grouping data in aggregate views and in line, trail, - and area marks without mapping data to a specific visual channel. - fill : Mapping(required=[]) - - fillOpacity : Mapping(required=[]) - - href : Mapping(required=[]) - - key : Mapping(required=[]) - - latitude : Mapping(required=[]) - - latitude2 : Mapping(required=[]) - - longitude : Mapping(required=[]) - - longitude2 : Mapping(required=[]) - - opacity : Mapping(required=[]) - - order : anyOf(:class:`OrderFieldDef`, List(:class:`OrderFieldDef`), :class:`OrderValueDef`) - Order of the marks. - - - * For stacked marks, this ``order`` channel encodes `stack order - `__. - * For line and trail marks, this ``order`` channel encodes order of data points in - the lines. This can be useful for creating `a connected scatterplot - `__. Setting - ``order`` to ``{"value": null}`` makes the line marks use the original order in - the data sources. - * Otherwise, this ``order`` channel encodes layer order of the marks. - - **Note** : In aggregate plots, ``order`` field should be ``aggregate`` d to avoid - creating additional aggregation grouping. - radius : Mapping(required=[]) - - radius2 : Mapping(required=[]) - - shape : Mapping(required=[]) - - size : Mapping(required=[]) - - stroke : Mapping(required=[]) - - strokeDash : Mapping(required=[]) - - strokeOpacity : Mapping(required=[]) - - strokeWidth : Mapping(required=[]) - - text : Mapping(required=[]) - - theta : Mapping(required=[]) - - theta2 : Mapping(required=[]) - - tooltip : anyOf(:class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`, List(:class:`StringFieldDef`), None) - The tooltip text to show upon mouse hover. Specifying ``tooltip`` encoding overrides - `the tooltip property in the mark definition - `__. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - url : Mapping(required=[]) - - x : Mapping(required=[]) - - x2 : Mapping(required=[]) - - xError : Mapping(required=[]) - - xError2 : Mapping(required=[]) - - xOffset : Mapping(required=[]) - - y : Mapping(required=[]) - - y2 : Mapping(required=[]) - - yError : Mapping(required=[]) - - yError2 : Mapping(required=[]) - - yOffset : Mapping(required=[]) - - """ - _schema = {'$ref': '#/definitions/SharedEncoding'} - - def __init__(self, angle=Undefined, color=Undefined, description=Undefined, detail=Undefined, - fill=Undefined, fillOpacity=Undefined, href=Undefined, key=Undefined, - latitude=Undefined, latitude2=Undefined, longitude=Undefined, longitude2=Undefined, - opacity=Undefined, order=Undefined, radius=Undefined, radius2=Undefined, - shape=Undefined, size=Undefined, stroke=Undefined, strokeDash=Undefined, - strokeOpacity=Undefined, strokeWidth=Undefined, text=Undefined, theta=Undefined, - theta2=Undefined, tooltip=Undefined, url=Undefined, x=Undefined, x2=Undefined, - xError=Undefined, xError2=Undefined, xOffset=Undefined, y=Undefined, y2=Undefined, - yError=Undefined, yError2=Undefined, yOffset=Undefined, **kwds): - super(SharedEncoding, self).__init__(angle=angle, color=color, description=description, - detail=detail, fill=fill, fillOpacity=fillOpacity, - href=href, key=key, latitude=latitude, latitude2=latitude2, - longitude=longitude, longitude2=longitude2, - opacity=opacity, order=order, radius=radius, - radius2=radius2, shape=shape, size=size, stroke=stroke, - strokeDash=strokeDash, strokeOpacity=strokeOpacity, - strokeWidth=strokeWidth, text=text, theta=theta, - theta2=theta2, tooltip=tooltip, url=url, x=x, x2=x2, - xError=xError, xError2=xError2, xOffset=xOffset, y=y, - y2=y2, yError=yError, yError2=yError2, yOffset=yOffset, - **kwds) - - -class SingleDefUnitChannel(VegaLiteSchema): - """SingleDefUnitChannel schema wrapper - - enum('x', 'y', 'xOffset', 'yOffset', 'x2', 'y2', 'longitude', 'latitude', 'longitude2', - 'latitude2', 'theta', 'theta2', 'radius', 'radius2', 'color', 'fill', 'stroke', 'opacity', - 'fillOpacity', 'strokeOpacity', 'strokeWidth', 'strokeDash', 'size', 'angle', 'shape', - 'key', 'text', 'href', 'url', 'description') - """ - _schema = {'$ref': '#/definitions/SingleDefUnitChannel'} - - def __init__(self, *args): - super(SingleDefUnitChannel, self).__init__(*args) - - -class Sort(VegaLiteSchema): - """Sort schema wrapper - - anyOf(:class:`SortArray`, :class:`AllSortString`, :class:`EncodingSortField`, - :class:`SortByEncoding`, None) - """ - _schema = {'$ref': '#/definitions/Sort'} - - def __init__(self, *args, **kwds): - super(Sort, self).__init__(*args, **kwds) - - -class AllSortString(Sort): - """AllSortString schema wrapper - - anyOf(:class:`SortOrder`, :class:`SortByChannel`, :class:`SortByChannelDesc`) - """ - _schema = {'$ref': '#/definitions/AllSortString'} - - def __init__(self, *args, **kwds): - super(AllSortString, self).__init__(*args, **kwds) - - -class EncodingSortField(Sort): - """EncodingSortField schema wrapper - - Mapping(required=[]) - A sort definition for sorting a discrete scale in an encoding field definition. - - Parameters - ---------- - - field : :class:`Field` - The data `field `__ to sort by. - - **Default value:** If unspecified, defaults to the field specified in the outer data - reference. - op : :class:`NonArgAggregateOp` - An `aggregate operation - `__ to perform on the - field prior to sorting (e.g., ``"count"``, ``"mean"`` and ``"median"`` ). An - aggregation is required when there are multiple values of the sort field for each - encoded data field. The input data objects will be aggregated, grouped by the - encoded data field. - - For a full list of operations, please see the documentation for `aggregate - `__. - - **Default value:** ``"sum"`` for stacked plots. Otherwise, ``"min"``. - order : anyOf(:class:`SortOrder`, None) - The sort order. One of ``"ascending"`` (default), ``"descending"``, or ``null`` (no - not sort). - """ - _schema = {'$ref': '#/definitions/EncodingSortField'} - - def __init__(self, field=Undefined, op=Undefined, order=Undefined, **kwds): - super(EncodingSortField, self).__init__(field=field, op=op, order=order, **kwds) - - -class SortArray(Sort): - """SortArray schema wrapper - - anyOf(List(float), List(string), List(boolean), List(:class:`DateTime`)) - """ - _schema = {'$ref': '#/definitions/SortArray'} - - def __init__(self, *args, **kwds): - super(SortArray, self).__init__(*args, **kwds) - - -class SortByChannel(AllSortString): - """SortByChannel schema wrapper - - enum('x', 'y', 'color', 'fill', 'stroke', 'strokeWidth', 'size', 'shape', 'fillOpacity', - 'strokeOpacity', 'opacity', 'text') - """ - _schema = {'$ref': '#/definitions/SortByChannel'} - - def __init__(self, *args): - super(SortByChannel, self).__init__(*args) - - -class SortByChannelDesc(AllSortString): - """SortByChannelDesc schema wrapper - - enum('-x', '-y', '-color', '-fill', '-stroke', '-strokeWidth', '-size', '-shape', - '-fillOpacity', '-strokeOpacity', '-opacity', '-text') - """ - _schema = {'$ref': '#/definitions/SortByChannelDesc'} - - def __init__(self, *args): - super(SortByChannelDesc, self).__init__(*args) - - -class SortByEncoding(Sort): - """SortByEncoding schema wrapper - - Mapping(required=[encoding]) - - Parameters - ---------- - - encoding : :class:`SortByChannel` - The `encoding channel - `__ to sort by (e.g., - ``"x"``, ``"y"`` ) - order : anyOf(:class:`SortOrder`, None) - The sort order. One of ``"ascending"`` (default), ``"descending"``, or ``null`` (no - not sort). - """ - _schema = {'$ref': '#/definitions/SortByEncoding'} - - def __init__(self, encoding=Undefined, order=Undefined, **kwds): - super(SortByEncoding, self).__init__(encoding=encoding, order=order, **kwds) - - -class SortField(VegaLiteSchema): - """SortField schema wrapper - - Mapping(required=[field]) - A sort definition for transform - - Parameters - ---------- - - field : :class:`FieldName` - The name of the field to sort. - order : anyOf(:class:`SortOrder`, None) - Whether to sort the field in ascending or descending order. One of ``"ascending"`` - (default), ``"descending"``, or ``null`` (no not sort). - """ - _schema = {'$ref': '#/definitions/SortField'} - - def __init__(self, field=Undefined, order=Undefined, **kwds): - super(SortField, self).__init__(field=field, order=order, **kwds) - - -class SortOrder(AllSortString): - """SortOrder schema wrapper - - enum('ascending', 'descending') - """ - _schema = {'$ref': '#/definitions/SortOrder'} - - def __init__(self, *args): - super(SortOrder, self).__init__(*args) - - -class Spec(VegaLiteSchema): - """Spec schema wrapper - - anyOf(:class:`FacetedUnitSpec`, :class:`LayerSpec`, :class:`RepeatSpec`, :class:`FacetSpec`, - :class:`ConcatSpecGenericSpec`, :class:`VConcatSpecGenericSpec`, - :class:`HConcatSpecGenericSpec`) - Any specification in Vega-Lite. - """ - _schema = {'$ref': '#/definitions/Spec'} - - def __init__(self, *args, **kwds): - super(Spec, self).__init__(*args, **kwds) - - -class ConcatSpecGenericSpec(Spec, NonNormalizedSpec): - """ConcatSpecGenericSpec schema wrapper - - Mapping(required=[concat]) - Base interface for a generalized concatenation specification. - - Parameters - ---------- - - concat : List(:class:`Spec`) - A list of views to be concatenated. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - columns : float - The number of columns to include in the view composition layout. - - **Default value** : ``undefined`` -- An infinite number of columns (a single row) - will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using - the ``column`` channel (for ``facet`` and ``repeat`` ). - - **Note** : - - 1) This property is only for: - - - * the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` ) - * the ``facet`` and ``repeat`` operator with one field/repetition definition - (without row/column nesting) - - 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` ) - and to using the ``row`` channel (for ``facet`` and ``repeat`` ). - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - """ - _schema = {'$ref': '#/definitions/ConcatSpec'} - - def __init__(self, concat=Undefined, align=Undefined, bounds=Undefined, center=Undefined, - columns=Undefined, data=Undefined, description=Undefined, name=Undefined, - resolve=Undefined, spacing=Undefined, title=Undefined, transform=Undefined, **kwds): - super(ConcatSpecGenericSpec, self).__init__(concat=concat, align=align, bounds=bounds, - center=center, columns=columns, data=data, - description=description, name=name, resolve=resolve, - spacing=spacing, title=title, transform=transform, - **kwds) - - -class FacetSpec(Spec, NonNormalizedSpec): - """FacetSpec schema wrapper - - Mapping(required=[facet, spec]) - Base interface for a facet specification. - - Parameters - ---------- - - facet : anyOf(:class:`FacetFieldDef`, :class:`FacetMapping`) - Definition for how to facet the data. One of: 1) `a field definition for faceting - the plot by one field - `__ 2) `An object that - maps row and column channels to their field definitions - `__ - spec : anyOf(:class:`LayerSpec`, :class:`FacetedUnitSpec`) - A specification of the view that gets faceted. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - columns : float - The number of columns to include in the view composition layout. - - **Default value** : ``undefined`` -- An infinite number of columns (a single row) - will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using - the ``column`` channel (for ``facet`` and ``repeat`` ). - - **Note** : - - 1) This property is only for: - - - * the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` ) - * the ``facet`` and ``repeat`` operator with one field/repetition definition - (without row/column nesting) - - 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` ) - and to using the ``row`` channel (for ``facet`` and ``repeat`` ). - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - """ - _schema = {'$ref': '#/definitions/FacetSpec'} - - def __init__(self, facet=Undefined, spec=Undefined, align=Undefined, bounds=Undefined, - center=Undefined, columns=Undefined, data=Undefined, description=Undefined, - name=Undefined, resolve=Undefined, spacing=Undefined, title=Undefined, - transform=Undefined, **kwds): - super(FacetSpec, self).__init__(facet=facet, spec=spec, align=align, bounds=bounds, - center=center, columns=columns, data=data, - description=description, name=name, resolve=resolve, - spacing=spacing, title=title, transform=transform, **kwds) - - -class FacetedUnitSpec(Spec, NonNormalizedSpec): - """FacetedUnitSpec schema wrapper - - Mapping(required=[mark]) - Unit spec that can have a composite mark and row or column channels (shorthand for a facet - spec). - - Parameters - ---------- - - mark : :class:`AnyMark` - A string describing the mark type (one of ``"bar"``, ``"circle"``, ``"square"``, - ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"rule"``, ``"geoshape"``, and - ``"text"`` ) or a `mark definition object - `__. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - encoding : :class:`FacetedEncoding` - A key-value mapping between encoding channels and definition of fields. - height : anyOf(float, string, :class:`Step`) - The height of a visualization. - - - * For a plot with a continuous y-field, height should be a number. - * For a plot with either a discrete y-field or no y-field, height can be either a - number indicating a fixed height or an object in the form of ``{step: number}`` - defining the height per discrete step. (No y-field is equivalent to having one - discrete step.) - * To enable responsive sizing on height, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousHeight`` for a plot with a - continuous y-field and ``config.view.discreteHeight`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - height of a single view and the ``"container"`` option cannot be used. - - **See also:** `height `__ - documentation. - name : string - Name of the visualization for later reference. - params : List(:class:`SelectionParameter`) - An array of parameters that may either be simple variables, or more complex - selections that map user input to data queries. - projection : :class:`Projection` - An object defining properties of geographic projection, which will be applied to - ``shape`` path for ``"geoshape"`` marks and to ``latitude`` and ``"longitude"`` - channels for other marks. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - view : :class:`ViewBackground` - An object defining the view background's fill and stroke. - - **Default value:** none (transparent) - width : anyOf(float, string, :class:`Step`) - The width of a visualization. - - - * For a plot with a continuous x-field, width should be a number. - * For a plot with either a discrete x-field or no x-field, width can be either a - number indicating a fixed width or an object in the form of ``{step: number}`` - defining the width per discrete step. (No x-field is equivalent to having one - discrete step.) - * To enable responsive sizing on width, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousWidth`` for a plot with a - continuous x-field and ``config.view.discreteWidth`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - width of a single view and the ``"container"`` option cannot be used. - - **See also:** `width `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FacetedUnitSpec'} - - def __init__(self, mark=Undefined, align=Undefined, bounds=Undefined, center=Undefined, - data=Undefined, description=Undefined, encoding=Undefined, height=Undefined, - name=Undefined, params=Undefined, projection=Undefined, resolve=Undefined, - spacing=Undefined, title=Undefined, transform=Undefined, view=Undefined, - width=Undefined, **kwds): - super(FacetedUnitSpec, self).__init__(mark=mark, align=align, bounds=bounds, center=center, - data=data, description=description, encoding=encoding, - height=height, name=name, params=params, - projection=projection, resolve=resolve, spacing=spacing, - title=title, transform=transform, view=view, width=width, - **kwds) - - -class HConcatSpecGenericSpec(Spec, NonNormalizedSpec): - """HConcatSpecGenericSpec schema wrapper - - Mapping(required=[hconcat]) - Base interface for a horizontal concatenation specification. - - Parameters - ---------- - - hconcat : List(:class:`Spec`) - A list of views to be concatenated and put into a row. - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : boolean - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - **Default value:** ``false`` - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : float - The spacing in pixels between sub-views of the concat operator. - - **Default value** : ``10`` - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - """ - _schema = {'$ref': '#/definitions/HConcatSpec'} - - def __init__(self, hconcat=Undefined, bounds=Undefined, center=Undefined, data=Undefined, - description=Undefined, name=Undefined, resolve=Undefined, spacing=Undefined, - title=Undefined, transform=Undefined, **kwds): - super(HConcatSpecGenericSpec, self).__init__(hconcat=hconcat, bounds=bounds, center=center, - data=data, description=description, name=name, - resolve=resolve, spacing=spacing, title=title, - transform=transform, **kwds) - - -class LayerSpec(Spec, NonNormalizedSpec): - """LayerSpec schema wrapper - - Mapping(required=[layer]) - A full layered plot specification, which may contains ``encoding`` and ``projection`` - properties that will be applied to underlying unit (single-view) specifications. - - Parameters - ---------- - - layer : List(anyOf(:class:`LayerSpec`, :class:`UnitSpec`)) - Layer or single view specifications to be layered. - - **Note** : Specifications inside ``layer`` cannot use ``row`` and ``column`` - channels as layering facet specifications is not allowed. Instead, use the `facet - operator `__ and place a layer - inside a facet. - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - encoding : :class:`SharedEncoding` - A shared key-value mapping between encoding channels and definition of fields in the - underlying layers. - height : anyOf(float, string, :class:`Step`) - The height of a visualization. - - - * For a plot with a continuous y-field, height should be a number. - * For a plot with either a discrete y-field or no y-field, height can be either a - number indicating a fixed height or an object in the form of ``{step: number}`` - defining the height per discrete step. (No y-field is equivalent to having one - discrete step.) - * To enable responsive sizing on height, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousHeight`` for a plot with a - continuous y-field and ``config.view.discreteHeight`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - height of a single view and the ``"container"`` option cannot be used. - - **See also:** `height `__ - documentation. - name : string - Name of the visualization for later reference. - projection : :class:`Projection` - An object defining properties of the geographic projection shared by underlying - layers. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - view : :class:`ViewBackground` - An object defining the view background's fill and stroke. - - **Default value:** none (transparent) - width : anyOf(float, string, :class:`Step`) - The width of a visualization. - - - * For a plot with a continuous x-field, width should be a number. - * For a plot with either a discrete x-field or no x-field, width can be either a - number indicating a fixed width or an object in the form of ``{step: number}`` - defining the width per discrete step. (No x-field is equivalent to having one - discrete step.) - * To enable responsive sizing on width, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousWidth`` for a plot with a - continuous x-field and ``config.view.discreteWidth`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - width of a single view and the ``"container"`` option cannot be used. - - **See also:** `width `__ - documentation. - """ - _schema = {'$ref': '#/definitions/LayerSpec'} - - def __init__(self, layer=Undefined, data=Undefined, description=Undefined, encoding=Undefined, - height=Undefined, name=Undefined, projection=Undefined, resolve=Undefined, - title=Undefined, transform=Undefined, view=Undefined, width=Undefined, **kwds): - super(LayerSpec, self).__init__(layer=layer, data=data, description=description, - encoding=encoding, height=height, name=name, - projection=projection, resolve=resolve, title=title, - transform=transform, view=view, width=width, **kwds) - - -class RepeatSpec(Spec, NonNormalizedSpec): - """RepeatSpec schema wrapper - - anyOf(:class:`NonLayerRepeatSpec`, :class:`LayerRepeatSpec`) - """ - _schema = {'$ref': '#/definitions/RepeatSpec'} - - def __init__(self, *args, **kwds): - super(RepeatSpec, self).__init__(*args, **kwds) - - -class LayerRepeatSpec(RepeatSpec): - """LayerRepeatSpec schema wrapper - - Mapping(required=[repeat, spec]) - - Parameters - ---------- - - repeat : :class:`LayerRepeatMapping` - Definition for fields to be repeated. One of: 1) An array of fields to be repeated. - If ``"repeat"`` is an array, the field can be referred to as ``{"repeat": - "repeat"}``. The repeated views are laid out in a wrapped row. You can set the - number of columns to control the wrapping. 2) An object that maps ``"row"`` and/or - ``"column"`` to the listed fields to be repeated along the particular orientations. - The objects ``{"repeat": "row"}`` and ``{"repeat": "column"}`` can be used to refer - to the repeated field respectively. - spec : anyOf(:class:`LayerSpec`, :class:`UnitSpecWithFrame`) - A specification of the view that gets repeated. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - columns : float - The number of columns to include in the view composition layout. - - **Default value** : ``undefined`` -- An infinite number of columns (a single row) - will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using - the ``column`` channel (for ``facet`` and ``repeat`` ). - - **Note** : - - 1) This property is only for: - - - * the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` ) - * the ``facet`` and ``repeat`` operator with one field/repetition definition - (without row/column nesting) - - 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` ) - and to using the ``row`` channel (for ``facet`` and ``repeat`` ). - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - """ - _schema = {'$ref': '#/definitions/LayerRepeatSpec'} - - def __init__(self, repeat=Undefined, spec=Undefined, align=Undefined, bounds=Undefined, - center=Undefined, columns=Undefined, data=Undefined, description=Undefined, - name=Undefined, resolve=Undefined, spacing=Undefined, title=Undefined, - transform=Undefined, **kwds): - super(LayerRepeatSpec, self).__init__(repeat=repeat, spec=spec, align=align, bounds=bounds, - center=center, columns=columns, data=data, - description=description, name=name, resolve=resolve, - spacing=spacing, title=title, transform=transform, **kwds) - - -class NonLayerRepeatSpec(RepeatSpec): - """NonLayerRepeatSpec schema wrapper - - Mapping(required=[repeat, spec]) - Base interface for a repeat specification. - - Parameters - ---------- - - repeat : anyOf(List(string), :class:`RepeatMapping`) - Definition for fields to be repeated. One of: 1) An array of fields to be repeated. - If ``"repeat"`` is an array, the field can be referred to as ``{"repeat": - "repeat"}``. The repeated views are laid out in a wrapped row. You can set the - number of columns to control the wrapping. 2) An object that maps ``"row"`` and/or - ``"column"`` to the listed fields to be repeated along the particular orientations. - The objects ``{"repeat": "row"}`` and ``{"repeat": "column"}`` can be used to refer - to the repeated field respectively. - spec : :class:`NonNormalizedSpec` - A specification of the view that gets repeated. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - columns : float - The number of columns to include in the view composition layout. - - **Default value** : ``undefined`` -- An infinite number of columns (a single row) - will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using - the ``column`` channel (for ``facet`` and ``repeat`` ). - - **Note** : - - 1) This property is only for: - - - * the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` ) - * the ``facet`` and ``repeat`` operator with one field/repetition definition - (without row/column nesting) - - 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` ) - and to using the ``row`` channel (for ``facet`` and ``repeat`` ). - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - """ - _schema = {'$ref': '#/definitions/NonLayerRepeatSpec'} - - def __init__(self, repeat=Undefined, spec=Undefined, align=Undefined, bounds=Undefined, - center=Undefined, columns=Undefined, data=Undefined, description=Undefined, - name=Undefined, resolve=Undefined, spacing=Undefined, title=Undefined, - transform=Undefined, **kwds): - super(NonLayerRepeatSpec, self).__init__(repeat=repeat, spec=spec, align=align, bounds=bounds, - center=center, columns=columns, data=data, - description=description, name=name, resolve=resolve, - spacing=spacing, title=title, transform=transform, - **kwds) - - -class SphereGenerator(Generator): - """SphereGenerator schema wrapper - - Mapping(required=[sphere]) - - Parameters - ---------- - - sphere : anyOf(boolean, Mapping(required=[])) - Generate sphere GeoJSON data for the full globe. - name : string - Provide a placeholder name and bind data at runtime. - """ - _schema = {'$ref': '#/definitions/SphereGenerator'} - - def __init__(self, sphere=Undefined, name=Undefined, **kwds): - super(SphereGenerator, self).__init__(sphere=sphere, name=name, **kwds) - - -class StackOffset(VegaLiteSchema): - """StackOffset schema wrapper - - enum('zero', 'center', 'normalize') - """ - _schema = {'$ref': '#/definitions/StackOffset'} - - def __init__(self, *args): - super(StackOffset, self).__init__(*args) - - -class StandardType(VegaLiteSchema): - """StandardType schema wrapper - - enum('quantitative', 'ordinal', 'temporal', 'nominal') - """ - _schema = {'$ref': '#/definitions/StandardType'} - - def __init__(self, *args): - super(StandardType, self).__init__(*args) - - -class Step(VegaLiteSchema): - """Step schema wrapper - - Mapping(required=[step]) - - Parameters - ---------- - - step : float - The size (width/height) per discrete step. - for : :class:`StepFor` - Whether to apply the step to position scale or offset scale when there are both - ``x`` and ``xOffset`` or both ``y`` and ``yOffset`` encodings. - """ - _schema = {'$ref': '#/definitions/Step'} - - def __init__(self, step=Undefined, **kwds): - super(Step, self).__init__(step=step, **kwds) - - -class StepFor(VegaLiteSchema): - """StepFor schema wrapper - - enum('position', 'offset') - """ - _schema = {'$ref': '#/definitions/StepFor'} - - def __init__(self, *args): - super(StepFor, self).__init__(*args) - - -class Stream(VegaLiteSchema): - """Stream schema wrapper - - anyOf(:class:`EventStream`, :class:`DerivedStream`, :class:`MergedStream`) - """ - _schema = {'$ref': '#/definitions/Stream'} - - def __init__(self, *args, **kwds): - super(Stream, self).__init__(*args, **kwds) - - -class DerivedStream(Stream): - """DerivedStream schema wrapper - - Mapping(required=[stream]) - - Parameters - ---------- - - stream : :class:`Stream` - - between : List(:class:`Stream`) - - consume : boolean - - debounce : float - - filter : anyOf(:class:`Expr`, List(:class:`Expr`)) - - markname : string - - marktype : :class:`MarkType` - - throttle : float - - """ - _schema = {'$ref': '#/definitions/DerivedStream'} - - def __init__(self, stream=Undefined, between=Undefined, consume=Undefined, debounce=Undefined, - filter=Undefined, markname=Undefined, marktype=Undefined, throttle=Undefined, **kwds): - super(DerivedStream, self).__init__(stream=stream, between=between, consume=consume, - debounce=debounce, filter=filter, markname=markname, - marktype=marktype, throttle=throttle, **kwds) - - -class EventStream(Stream): - """EventStream schema wrapper - - anyOf(Mapping(required=[type]), Mapping(required=[source, type])) - """ - _schema = {'$ref': '#/definitions/EventStream'} - - def __init__(self, *args, **kwds): - super(EventStream, self).__init__(*args, **kwds) - - -class MergedStream(Stream): - """MergedStream schema wrapper - - Mapping(required=[merge]) - - Parameters - ---------- - - merge : List(:class:`Stream`) - - between : List(:class:`Stream`) - - consume : boolean - - debounce : float - - filter : anyOf(:class:`Expr`, List(:class:`Expr`)) - - markname : string - - marktype : :class:`MarkType` - - throttle : float - - """ - _schema = {'$ref': '#/definitions/MergedStream'} - - def __init__(self, merge=Undefined, between=Undefined, consume=Undefined, debounce=Undefined, - filter=Undefined, markname=Undefined, marktype=Undefined, throttle=Undefined, **kwds): - super(MergedStream, self).__init__(merge=merge, between=between, consume=consume, - debounce=debounce, filter=filter, markname=markname, - marktype=marktype, throttle=throttle, **kwds) - - -class StringFieldDef(VegaLiteSchema): - """StringFieldDef schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/StringFieldDef'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - format=Undefined, formatType=Undefined, timeUnit=Undefined, title=Undefined, - type=Undefined, **kwds): - super(StringFieldDef, self).__init__(aggregate=aggregate, bandPosition=bandPosition, bin=bin, - field=field, format=format, formatType=formatType, - timeUnit=timeUnit, title=title, type=type, **kwds) - - -class StringFieldDefWithCondition(VegaLiteSchema): - """StringFieldDefWithCondition schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - condition : anyOf(:class:`ConditionalValueDefstringExprRef`, List(:class:`ConditionalValueDefstringExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/StringFieldDefWithCondition'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(StringFieldDefWithCondition, self).__init__(aggregate=aggregate, - bandPosition=bandPosition, bin=bin, - condition=condition, field=field, - format=format, formatType=formatType, - timeUnit=timeUnit, title=title, type=type, - **kwds) - - -class StringValueDefWithCondition(VegaLiteSchema): - """StringValueDefWithCondition schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalValueDefstringnullExprRef`, List(:class:`ConditionalValueDefstringnullExprRef`)) - A field definition or one or more value definition(s) with a parameter predicate. - value : anyOf(string, None, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/StringValueDefWithCondition'} - - def __init__(self, condition=Undefined, value=Undefined, **kwds): - super(StringValueDefWithCondition, self).__init__(condition=condition, value=value, **kwds) - - -class StrokeCap(VegaLiteSchema): - """StrokeCap schema wrapper - - enum('butt', 'round', 'square') - """ - _schema = {'$ref': '#/definitions/StrokeCap'} - - def __init__(self, *args): - super(StrokeCap, self).__init__(*args) - - -class StrokeJoin(VegaLiteSchema): - """StrokeJoin schema wrapper - - enum('miter', 'round', 'bevel') - """ - _schema = {'$ref': '#/definitions/StrokeJoin'} - - def __init__(self, *args): - super(StrokeJoin, self).__init__(*args) - - -class StyleConfigIndex(VegaLiteSchema): - """StyleConfigIndex schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - arc : :class:`RectConfig` - Arc-specific Config - area : :class:`AreaConfig` - Area-Specific Config - bar : :class:`BarConfig` - Bar-Specific Config - circle : :class:`MarkConfig` - Circle-Specific Config - geoshape : :class:`MarkConfig` - Geoshape-Specific Config - image : :class:`RectConfig` - Image-specific Config - line : :class:`LineConfig` - Line-Specific Config - mark : :class:`MarkConfig` - Mark Config - point : :class:`MarkConfig` - Point-Specific Config - rect : :class:`RectConfig` - Rect-Specific Config - rule : :class:`MarkConfig` - Rule-Specific Config - square : :class:`MarkConfig` - Square-Specific Config - text : :class:`MarkConfig` - Text-Specific Config - tick : :class:`TickConfig` - Tick-Specific Config - trail : :class:`LineConfig` - Trail-Specific Config - group-subtitle : :class:`MarkConfig` - Default style for chart subtitles - group-title : :class:`MarkConfig` - Default style for chart titles - guide-label : :class:`MarkConfig` - Default style for axis, legend, and header labels. - guide-title : :class:`MarkConfig` - Default style for axis, legend, and header titles. - """ - _schema = {'$ref': '#/definitions/StyleConfigIndex'} - - def __init__(self, arc=Undefined, area=Undefined, bar=Undefined, circle=Undefined, - geoshape=Undefined, image=Undefined, line=Undefined, mark=Undefined, point=Undefined, - rect=Undefined, rule=Undefined, square=Undefined, text=Undefined, tick=Undefined, - trail=Undefined, **kwds): - super(StyleConfigIndex, self).__init__(arc=arc, area=area, bar=bar, circle=circle, - geoshape=geoshape, image=image, line=line, mark=mark, - point=point, rect=rect, rule=rule, square=square, - text=text, tick=tick, trail=trail, **kwds) - - -class SymbolShape(VegaLiteSchema): - """SymbolShape schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/SymbolShape'} - - def __init__(self, *args): - super(SymbolShape, self).__init__(*args) - - -class Text(VegaLiteSchema): - """Text schema wrapper - - anyOf(string, List(string)) - """ - _schema = {'$ref': '#/definitions/Text'} - - def __init__(self, *args, **kwds): - super(Text, self).__init__(*args, **kwds) - - -class TextBaseline(VegaLiteSchema): - """TextBaseline schema wrapper - - anyOf(string, :class:`Baseline`, string, string) - """ - _schema = {'$ref': '#/definitions/TextBaseline'} - - def __init__(self, *args, **kwds): - super(TextBaseline, self).__init__(*args, **kwds) - - -class Baseline(TextBaseline): - """Baseline schema wrapper - - enum('top', 'middle', 'bottom') - """ - _schema = {'$ref': '#/definitions/Baseline'} - - def __init__(self, *args): - super(Baseline, self).__init__(*args) - - -class TextDef(VegaLiteSchema): - """TextDef schema wrapper - - anyOf(:class:`FieldOrDatumDefWithConditionStringFieldDefText`, - :class:`FieldOrDatumDefWithConditionStringDatumDefText`, - :class:`ValueDefWithConditionStringFieldDefText`) - """ - _schema = {'$ref': '#/definitions/TextDef'} - - def __init__(self, *args, **kwds): - super(TextDef, self).__init__(*args, **kwds) - - -class FieldOrDatumDefWithConditionStringDatumDefText(TextDef): - """FieldOrDatumDefWithConditionStringDatumDefText schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - condition : anyOf(:class:`ConditionalValueDefTextExprRef`, List(:class:`ConditionalValueDefTextExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - datum : anyOf(:class:`PrimitiveValue`, :class:`DateTime`, :class:`ExprRef`, :class:`RepeatRef`) - A constant value in data domain. - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`Type` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, bandPosition=Undefined, condition=Undefined, datum=Undefined, format=Undefined, - formatType=Undefined, title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionStringDatumDefText, self).__init__(bandPosition=bandPosition, - condition=condition, - datum=datum, format=format, - formatType=formatType, - title=title, type=type, - **kwds) - - -class FieldOrDatumDefWithConditionStringFieldDefText(TextDef): - """FieldOrDatumDefWithConditionStringFieldDefText schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - condition : anyOf(:class:`ConditionalValueDefTextExprRef`, List(:class:`ConditionalValueDefTextExprRef`)) - One or more value definition(s) with `a parameter or a test predicate - `__. - - **Note:** A field definition's ``condition`` property can only contain `conditional - value definitions `__ - since Vega-Lite only allows at most one encoded field per encoding channel. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - format : anyOf(string, :class:`Dict`) - When used with the default ``"number"`` and ``"time"`` format type, the text - formatting pattern for labels of guides (axes, legends, headers) and text marks. - - - * If the format type is ``"number"`` (e.g., for quantitative fields), this is D3's - `number format pattern `__. - * If the format type is ``"time"`` (e.g., for temporal fields), this is D3's `time - format pattern `__. - - See the `format documentation `__ - for more examples. - - When used with a `custom formatType - `__, this - value will be passed as ``format`` alongside ``datum.value`` to the registered - function. - - **Default value:** Derived from `numberFormat - `__ config for number - format and from `timeFormat - `__ config for time - format. - formatType : string - The format type for labels. One of ``"number"``, ``"time"``, or a `registered custom - format type - `__. - - **Default value:** - - - * ``"time"`` for temporal fields and ordinal and nominal fields with ``timeUnit``. - * ``"number"`` for quantitative fields as well as ordinal and nominal fields without - ``timeUnit``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/FieldOrDatumDefWithCondition'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, condition=Undefined, - field=Undefined, format=Undefined, formatType=Undefined, timeUnit=Undefined, - title=Undefined, type=Undefined, **kwds): - super(FieldOrDatumDefWithConditionStringFieldDefText, self).__init__(aggregate=aggregate, - bandPosition=bandPosition, - bin=bin, - condition=condition, - field=field, format=format, - formatType=formatType, - timeUnit=timeUnit, - title=title, type=type, - **kwds) - - -class TextDirection(VegaLiteSchema): - """TextDirection schema wrapper - - enum('ltr', 'rtl') - """ - _schema = {'$ref': '#/definitions/TextDirection'} - - def __init__(self, *args): - super(TextDirection, self).__init__(*args) - - -class TickConfig(AnyMarkConfig): - """TickConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : anyOf(:class:`Align`, :class:`ExprRef`) - The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). - One of ``"left"``, ``"right"``, ``"center"``. - - **Note:** Expression reference is *not* supported for range marks. - angle : anyOf(float, :class:`ExprRef`) - The rotation angle of the text, in degrees. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG element, removing the mark item from the ARIA accessibility tree. - ariaRole : anyOf(string, :class:`ExprRef`) - Sets the type of user interface element of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "role" attribute. Warning: this - property is experimental and may be changed in the future. - ariaRoleDescription : anyOf(string, :class:`ExprRef`) - A human-readable, author-localized description for the role of the mark item for - `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the "aria-roledescription" attribute. - Warning: this property is experimental and may be changed in the future. - aspect : anyOf(boolean, :class:`ExprRef`) - Whether to keep aspect ratio of image marks. - bandSize : float - The width of the ticks. - - **Default value:** 3/4 of step (width step for horizontal ticks and height step for - vertical ticks). - baseline : anyOf(:class:`TextBaseline`, :class:`ExprRef`) - For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), - ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an - expression reference that provides one of the valid values. The ``"line-top"`` and - ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are - calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. - - For range marks, the vertical alignment of the marks. One of ``"top"``, - ``"middle"``, ``"bottom"``. - - **Note:** Expression reference is *not* supported for range marks. - blend : anyOf(:class:`Blend`, :class:`ExprRef`) - The color blend mode for drawing an item on its current background. Any valid `CSS - mix-blend-mode `__ - value can be used. - - __Default value:__ ``"source-over"`` - color : anyOf(:class:`Color`, :class:`Gradient`, :class:`ExprRef`) - Default color. - - **Default value:** :raw-html:`` - ``"#4682b4"`` - - **Note:** - - - * This property cannot be used in a `style config - `__. - * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and - will override ``color``. - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cornerRadiusBottomLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom left corner. - - **Default value:** ``0`` - cornerRadiusBottomRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' bottom right corner. - - **Default value:** ``0`` - cornerRadiusTopLeft : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top right corner. - - **Default value:** ``0`` - cornerRadiusTopRight : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles' top left corner. - - **Default value:** ``0`` - cursor : anyOf(:class:`Cursor`, :class:`ExprRef`) - The mouse cursor used over the mark. Any valid `CSS cursor type - `__ can be used. - description : anyOf(string, :class:`ExprRef`) - A text description of the mark item for `ARIA accessibility - `__ (SVG output - only). If specified, this property determines the `"aria-label" attribute - `__. - dir : anyOf(:class:`TextDirection`, :class:`ExprRef`) - The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` - (right-to-left). This property determines on which side is truncated in response to - the limit parameter. - - **Default value:** ``"ltr"`` - dx : anyOf(float, :class:`ExprRef`) - The horizontal offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - dy : anyOf(float, :class:`ExprRef`) - The vertical offset, in pixels, between the text label and its anchor point. The - offset is applied after rotation by the *angle* property. - ellipsis : anyOf(string, :class:`ExprRef`) - The ellipsis string for text truncated in response to the limit parameter. - - **Default value:** ``"…"`` - endAngle : anyOf(float, :class:`ExprRef`) - The end angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - fill : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default fill color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove fill. - - **Default value:** (None) - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - filled : boolean - Whether the mark's color should be used as fill color instead of stroke color. - - **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well - as ``geoshape`` marks for `graticule - `__ data sources; - otherwise, ``true``. - - **Note:** This property cannot be used in a `style config - `__. - font : anyOf(string, :class:`ExprRef`) - The typeface to set the text in (e.g., ``"Helvetica Neue"`` ). - fontSize : anyOf(float, :class:`ExprRef`) - The font size, in pixels. - - **Default value:** ``11`` - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - The font style (e.g., ``"italic"`` ). - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - The font weight. This can be either a string (e.g ``"bold"``, ``"normal"`` ) or a - number ( ``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and - ``"bold"`` = ``700`` ). - height : anyOf(float, :class:`ExprRef`) - Height of the marks. - href : anyOf(:class:`URI`, :class:`ExprRef`) - A URL to load upon mouse click. If defined, the mark acts as a hyperlink. - innerRadius : anyOf(float, :class:`ExprRef`) - The inner radius in pixels of arc marks. ``innerRadius`` is an alias for - ``radius2``. - - **Default value:** ``0`` - interpolate : anyOf(:class:`Interpolate`, :class:`ExprRef`) - The line interpolation method to use for line and area marks. One of the following: - - - * ``"linear"`` : piecewise linear segments, as in a polyline. - * ``"linear-closed"`` : close the linear segments to form a polygon. - * ``"step"`` : alternate between horizontal and vertical segments, as in a step - function. - * ``"step-before"`` : alternate between vertical and horizontal segments, as in a - step function. - * ``"step-after"`` : alternate between horizontal and vertical segments, as in a - step function. - * ``"basis"`` : a B-spline, with control point duplication on the ends. - * ``"basis-open"`` : an open B-spline; may not intersect the start or end. - * ``"basis-closed"`` : a closed B-spline, as in a loop. - * ``"cardinal"`` : a Cardinal spline, with control point duplication on the ends. - * ``"cardinal-open"`` : an open Cardinal spline; may not intersect the start or end, - but will intersect other control points. - * ``"cardinal-closed"`` : a closed Cardinal spline, as in a loop. - * ``"bundle"`` : equivalent to basis, except the tension parameter is used to - straighten the spline. - * ``"monotone"`` : cubic interpolation that preserves monotonicity in y. - invalid : enum('filter', None) - Defines how Vega-Lite should handle marks for invalid values ( ``null`` and ``NaN`` - ). - - - * If set to ``"filter"`` (default), all data items with null values will be skipped - (for line, trail, and area marks) or filtered (for other marks). - * If ``null``, all data items are included. In this case, invalid values will be - interpreted as zeroes. - limit : anyOf(float, :class:`ExprRef`) - The maximum length of the text mark in pixels. The text value will be automatically - truncated if the rendered size exceeds the limit. - - **Default value:** ``0`` -- indicating no limit - lineBreak : anyOf(string, :class:`ExprRef`) - A delimiter, such as a newline character, upon which to break text strings into - multiple lines. This property is ignored if the text is array-valued. - lineHeight : anyOf(float, :class:`ExprRef`) - The line height in pixels (the spacing between subsequent lines of text) for - multi-line text marks. - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - order : anyOf(None, boolean) - For line and trail marks, this ``order`` property can be set to ``null`` or - ``false`` to make the lines use the original order in the data sources. - orient : :class:`Orientation` - The orientation of a non-stacked bar, tick, area, and line charts. The value is - either horizontal (default) or vertical. - - - * For bar, rule and tick, this determines whether the size of the bar and tick - should be applied to x or y dimension. - * For area, this property determines the orient property of the Vega output. - * For line and trail marks, this property determines the sort order of the points in - the line if ``config.sortLineBy`` is not specified. For stacked charts, this is - always determined by the orientation of the stack; therefore explicitly specified - value will be ignored. - outerRadius : anyOf(float, :class:`ExprRef`) - The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. - - **Default value:** ``0`` - padAngle : anyOf(float, :class:`ExprRef`) - The angular padding applied to sides of the arc, in radians. - radius : anyOf(float, :class:`ExprRef`) - For arc mark, the primary (outer) radius in pixels. - - For text marks, polar coordinate radial offset, in pixels, of the text from the - origin determined by the ``x`` and ``y`` properties. - - **Default value:** ``min(plot_width, plot_height)/2`` - radius2 : anyOf(float, :class:`ExprRef`) - The secondary (inner) radius in pixels of arc marks. - - **Default value:** ``0`` - shape : anyOf(anyOf(:class:`SymbolShape`, string), :class:`ExprRef`) - Shape of the point marks. Supported values include: - - - * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, - ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or - ``"triangle-left"``. - * the line symbol ``"stroke"`` - * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - * a custom `SVG path string - `__ (For correct - sizing, custom shape paths should be defined within a square bounding box with - coordinates ranging from -1 to 1 along both the x and y dimensions.) - - **Default value:** ``"circle"`` - size : anyOf(float, :class:`ExprRef`) - Default size for marks. - - - * For ``point`` / ``circle`` / ``square``, this represents the pixel area of the - marks. Note that this value sets the area of the symbol; the side lengths will - increase with the square root of this value. - * For ``bar``, this represents the band size of the bar, in pixels. - * For ``text``, this represents the font size, in pixels. - - **Default value:** - - - * ``30`` for point, circle, square marks; width/height's ``step`` - * ``2`` for bar marks with discrete dimensions; - * ``5`` for bar marks with continuous dimensions; - * ``11`` for text marks. - smooth : anyOf(boolean, :class:`ExprRef`) - A boolean flag (default true) indicating if the image should be smoothed when - resized. If false, individual pixels should be scaled directly rather than - interpolated with smoothing. For SVG rendering, this option may not work in some - browsers due to lack of standardization. - startAngle : anyOf(float, :class:`ExprRef`) - The start angle in radians for arc marks. A value of ``0`` indicates up (north), - increasing values proceed clockwise. - stroke : anyOf(:class:`Color`, :class:`Gradient`, None, :class:`ExprRef`) - Default stroke color. This property has higher precedence than ``config.color``. Set - to ``null`` to remove stroke. - - **Default value:** (None) - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOffset : anyOf(float, :class:`ExprRef`) - The offset in pixels at which to draw the group stroke and fill. If unspecified, the - default behavior is to dynamically offset stroked groups such that 1 pixel stroke - widths align with the pixel grid. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - tension : anyOf(float, :class:`ExprRef`) - Depending on the interpolation type, sets the tension parameter (for line and area - marks). - text : anyOf(:class:`Text`, :class:`ExprRef`) - Placeholder text if the ``text`` channel is not specified - theta : anyOf(float, :class:`ExprRef`) - For arc marks, the arc length in radians if theta2 is not specified, otherwise the - start arc angle. (A value of 0 indicates up or “north”, increasing values proceed - clockwise.) - - For text marks, polar coordinate angle in radians. - theta2 : anyOf(float, :class:`ExprRef`) - The end angle of arc marks in radians. A value of 0 indicates up or “north”, - increasing values proceed clockwise. - thickness : float - Thickness of the tick mark. - - **Default value:** ``1`` - timeUnitBandPosition : float - Default relative band position for a time unit. If set to ``0``, the marks will be - positioned at the beginning of the time unit band step. If set to ``0.5``, the marks - will be positioned in the middle of the time unit band step. - timeUnitBandSize : float - Default relative band size for a time unit. If set to ``1``, the bandwidth of the - marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the - marks will be half of the time unit band step. - tooltip : anyOf(float, string, boolean, :class:`TooltipContent`, :class:`ExprRef`, None) - The tooltip text string to show upon mouse hover or an object defining which fields - should the tooltip be derived from. - - - * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from - ``encoding`` will be used. - * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the - highlighted data point will be used. - * If set to ``null`` or ``false``, then no tooltip will be used. - - See the `tooltip `__ - documentation for a detailed discussion about tooltip in Vega-Lite. - - **Default value:** ``null`` - url : anyOf(:class:`URI`, :class:`ExprRef`) - The URL of the image file for image marks. - width : anyOf(float, :class:`ExprRef`) - Width of the marks. - x : anyOf(float, string, :class:`ExprRef`) - X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without - specified ``x2`` or ``width``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - x2 : anyOf(float, string, :class:`ExprRef`) - X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"width"`` for the width - of the plot. - y : anyOf(float, string, :class:`ExprRef`) - Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without - specified ``y2`` or ``height``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - y2 : anyOf(float, string, :class:`ExprRef`) - Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. - - The ``value`` of this channel can be a number or a string ``"height"`` for the - height of the plot. - """ - _schema = {'$ref': '#/definitions/TickConfig'} - - def __init__(self, align=Undefined, angle=Undefined, aria=Undefined, ariaRole=Undefined, - ariaRoleDescription=Undefined, aspect=Undefined, bandSize=Undefined, - baseline=Undefined, blend=Undefined, color=Undefined, cornerRadius=Undefined, - cornerRadiusBottomLeft=Undefined, cornerRadiusBottomRight=Undefined, - cornerRadiusTopLeft=Undefined, cornerRadiusTopRight=Undefined, cursor=Undefined, - description=Undefined, dir=Undefined, dx=Undefined, dy=Undefined, ellipsis=Undefined, - endAngle=Undefined, fill=Undefined, fillOpacity=Undefined, filled=Undefined, - font=Undefined, fontSize=Undefined, fontStyle=Undefined, fontWeight=Undefined, - height=Undefined, href=Undefined, innerRadius=Undefined, interpolate=Undefined, - invalid=Undefined, limit=Undefined, lineBreak=Undefined, lineHeight=Undefined, - opacity=Undefined, order=Undefined, orient=Undefined, outerRadius=Undefined, - padAngle=Undefined, radius=Undefined, radius2=Undefined, shape=Undefined, - size=Undefined, smooth=Undefined, startAngle=Undefined, stroke=Undefined, - strokeCap=Undefined, strokeDash=Undefined, strokeDashOffset=Undefined, - strokeJoin=Undefined, strokeMiterLimit=Undefined, strokeOffset=Undefined, - strokeOpacity=Undefined, strokeWidth=Undefined, tension=Undefined, text=Undefined, - theta=Undefined, theta2=Undefined, thickness=Undefined, timeUnitBandPosition=Undefined, - timeUnitBandSize=Undefined, tooltip=Undefined, url=Undefined, width=Undefined, - x=Undefined, x2=Undefined, y=Undefined, y2=Undefined, **kwds): - super(TickConfig, self).__init__(align=align, angle=angle, aria=aria, ariaRole=ariaRole, - ariaRoleDescription=ariaRoleDescription, aspect=aspect, - bandSize=bandSize, baseline=baseline, blend=blend, color=color, - cornerRadius=cornerRadius, - cornerRadiusBottomLeft=cornerRadiusBottomLeft, - cornerRadiusBottomRight=cornerRadiusBottomRight, - cornerRadiusTopLeft=cornerRadiusTopLeft, - cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, - description=description, dir=dir, dx=dx, dy=dy, - ellipsis=ellipsis, endAngle=endAngle, fill=fill, - fillOpacity=fillOpacity, filled=filled, font=font, - fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, - height=height, href=href, innerRadius=innerRadius, - interpolate=interpolate, invalid=invalid, limit=limit, - lineBreak=lineBreak, lineHeight=lineHeight, opacity=opacity, - order=order, orient=orient, outerRadius=outerRadius, - padAngle=padAngle, radius=radius, radius2=radius2, shape=shape, - size=size, smooth=smooth, startAngle=startAngle, stroke=stroke, - strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, strokeOffset=strokeOffset, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - tension=tension, text=text, theta=theta, theta2=theta2, - thickness=thickness, timeUnitBandPosition=timeUnitBandPosition, - timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, url=url, - width=width, x=x, x2=x2, y=y, y2=y2, **kwds) - - -class TickCount(VegaLiteSchema): - """TickCount schema wrapper - - anyOf(float, :class:`TimeInterval`, :class:`TimeIntervalStep`) - """ - _schema = {'$ref': '#/definitions/TickCount'} - - def __init__(self, *args, **kwds): - super(TickCount, self).__init__(*args, **kwds) - - -class TimeInterval(TickCount): - """TimeInterval schema wrapper - - enum('millisecond', 'second', 'minute', 'hour', 'day', 'week', 'month', 'year') - """ - _schema = {'$ref': '#/definitions/TimeInterval'} - - def __init__(self, *args): - super(TimeInterval, self).__init__(*args) - - -class TimeIntervalStep(TickCount): - """TimeIntervalStep schema wrapper - - Mapping(required=[interval, step]) - - Parameters - ---------- - - interval : :class:`TimeInterval` - - step : float - - """ - _schema = {'$ref': '#/definitions/TimeIntervalStep'} - - def __init__(self, interval=Undefined, step=Undefined, **kwds): - super(TimeIntervalStep, self).__init__(interval=interval, step=step, **kwds) - - -class TimeLocale(VegaLiteSchema): - """TimeLocale schema wrapper - - Mapping(required=[dateTime, date, time, periods, days, shortDays, months, shortMonths]) - Locale definition for formatting dates and times. - - Parameters - ---------- - - date : string - The date (%x) format specifier (e.g., "%m/%d/%Y"). - dateTime : string - The date and time (%c) format specifier (e.g., "%a %b %e %X %Y"). - days : :class:`Vector7string` - The full names of the weekdays, starting with Sunday. - months : :class:`Vector12string` - The full names of the months (starting with January). - periods : :class:`Vector2string` - The A.M. and P.M. equivalents (e.g., ["AM", "PM"]). - shortDays : :class:`Vector7string` - The abbreviated names of the weekdays, starting with Sunday. - shortMonths : :class:`Vector12string` - The abbreviated names of the months (starting with January). - time : string - The time (%X) format specifier (e.g., "%H:%M:%S"). - """ - _schema = {'$ref': '#/definitions/TimeLocale'} - - def __init__(self, date=Undefined, dateTime=Undefined, days=Undefined, months=Undefined, - periods=Undefined, shortDays=Undefined, shortMonths=Undefined, time=Undefined, **kwds): - super(TimeLocale, self).__init__(date=date, dateTime=dateTime, days=days, months=months, - periods=periods, shortDays=shortDays, shortMonths=shortMonths, - time=time, **kwds) - - -class TimeUnit(VegaLiteSchema): - """TimeUnit schema wrapper - - anyOf(:class:`SingleTimeUnit`, :class:`MultiTimeUnit`) - """ - _schema = {'$ref': '#/definitions/TimeUnit'} - - def __init__(self, *args, **kwds): - super(TimeUnit, self).__init__(*args, **kwds) - - -class MultiTimeUnit(TimeUnit): - """MultiTimeUnit schema wrapper - - anyOf(:class:`LocalMultiTimeUnit`, :class:`UtcMultiTimeUnit`) - """ - _schema = {'$ref': '#/definitions/MultiTimeUnit'} - - def __init__(self, *args, **kwds): - super(MultiTimeUnit, self).__init__(*args, **kwds) - - -class LocalMultiTimeUnit(MultiTimeUnit): - """LocalMultiTimeUnit schema wrapper - - enum('yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', - 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', - 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', - 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', - 'monthdatehoursminutesseconds', 'weekday', 'weeksdayhours', 'weekdayhoursminutes', - 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', - 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds') - """ - _schema = {'$ref': '#/definitions/LocalMultiTimeUnit'} - - def __init__(self, *args): - super(LocalMultiTimeUnit, self).__init__(*args) - - -class SingleTimeUnit(TimeUnit): - """SingleTimeUnit schema wrapper - - anyOf(:class:`LocalSingleTimeUnit`, :class:`UtcSingleTimeUnit`) - """ - _schema = {'$ref': '#/definitions/SingleTimeUnit'} - - def __init__(self, *args, **kwds): - super(SingleTimeUnit, self).__init__(*args, **kwds) - - -class LocalSingleTimeUnit(SingleTimeUnit): - """LocalSingleTimeUnit schema wrapper - - enum('year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', - 'seconds', 'milliseconds') - """ - _schema = {'$ref': '#/definitions/LocalSingleTimeUnit'} - - def __init__(self, *args): - super(LocalSingleTimeUnit, self).__init__(*args) - - -class TimeUnitParams(VegaLiteSchema): - """TimeUnitParams schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - maxbins : float - If no ``unit`` is specified, maxbins is used to infer time units. - step : float - The number of steps between bins, in terms of the least significant unit provided. - unit : :class:`TimeUnit` - Defines how date-time values should be binned. - utc : boolean - True to use UTC timezone. Equivalent to using a ``utc`` prefixed ``TimeUnit``. - """ - _schema = {'$ref': '#/definitions/TimeUnitParams'} - - def __init__(self, maxbins=Undefined, step=Undefined, unit=Undefined, utc=Undefined, **kwds): - super(TimeUnitParams, self).__init__(maxbins=maxbins, step=step, unit=unit, utc=utc, **kwds) - - -class TitleAnchor(VegaLiteSchema): - """TitleAnchor schema wrapper - - enum(None, 'start', 'middle', 'end') - """ - _schema = {'$ref': '#/definitions/TitleAnchor'} - - def __init__(self, *args): - super(TitleAnchor, self).__init__(*args) - - -class TitleConfig(VegaLiteSchema): - """TitleConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - align : :class:`Align` - Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or - ``"right"``. - anchor : anyOf(:class:`TitleAnchor`, :class:`ExprRef`) - The anchor position for placing the title and subtitle text. One of ``"start"``, - ``"middle"``, or ``"end"``. For example, with an orientation of top these anchor - positions map to a left-, center-, or right-aligned title. - angle : anyOf(float, :class:`ExprRef`) - Angle in degrees of title and subtitle text. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG group, removing the title from the ARIA accessibility tree. - - **Default value:** ``true`` - baseline : :class:`TextBaseline` - Vertical text baseline for title and subtitle text. One of ``"alphabetic"`` - (default), ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or - ``"line-bottom"``. The ``"line-top"`` and ``"line-bottom"`` values operate similarly - to ``"top"`` and ``"bottom"``, but are calculated relative to the *lineHeight* - rather than *fontSize* alone. - color : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Text color for title text. - dx : anyOf(float, :class:`ExprRef`) - Delta offset for title and subtitle text x-coordinate. - dy : anyOf(float, :class:`ExprRef`) - Delta offset for title and subtitle text y-coordinate. - font : anyOf(string, :class:`ExprRef`) - Font name for title text. - fontSize : anyOf(float, :class:`ExprRef`) - Font size in pixels for title text. - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - Font style for title text. - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight for title text. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - frame : anyOf(anyOf(:class:`TitleFrame`, string), :class:`ExprRef`) - The reference frame for the anchor position, one of ``"bounds"`` (to anchor relative - to the full bounding box) or ``"group"`` (to anchor relative to the group width or - height). - limit : anyOf(float, :class:`ExprRef`) - The maximum allowed length in pixels of title and subtitle text. - lineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line title text or title text with ``"line-top"`` or - ``"line-bottom"`` baseline. - offset : anyOf(float, :class:`ExprRef`) - The orthogonal offset in pixels by which to displace the title group from its - position along the edge of the chart. - orient : anyOf(:class:`TitleOrient`, :class:`ExprRef`) - Default title orientation ( ``"top"``, ``"bottom"``, ``"left"``, or ``"right"`` ) - subtitleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Text color for subtitle text. - subtitleFont : anyOf(string, :class:`ExprRef`) - Font name for subtitle text. - subtitleFontSize : anyOf(float, :class:`ExprRef`) - Font size in pixels for subtitle text. - subtitleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - Font style for subtitle text. - subtitleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight for subtitle text. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - subtitleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line subtitle text. - subtitlePadding : anyOf(float, :class:`ExprRef`) - The padding in pixels between title and subtitle text. - zindex : anyOf(float, :class:`ExprRef`) - The integer z-index indicating the layering of the title group relative to other - axis, mark, and legend groups. - - **Default value:** ``0``. - """ - _schema = {'$ref': '#/definitions/TitleConfig'} - - def __init__(self, align=Undefined, anchor=Undefined, angle=Undefined, aria=Undefined, - baseline=Undefined, color=Undefined, dx=Undefined, dy=Undefined, font=Undefined, - fontSize=Undefined, fontStyle=Undefined, fontWeight=Undefined, frame=Undefined, - limit=Undefined, lineHeight=Undefined, offset=Undefined, orient=Undefined, - subtitleColor=Undefined, subtitleFont=Undefined, subtitleFontSize=Undefined, - subtitleFontStyle=Undefined, subtitleFontWeight=Undefined, - subtitleLineHeight=Undefined, subtitlePadding=Undefined, zindex=Undefined, **kwds): - super(TitleConfig, self).__init__(align=align, anchor=anchor, angle=angle, aria=aria, - baseline=baseline, color=color, dx=dx, dy=dy, font=font, - fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, - frame=frame, limit=limit, lineHeight=lineHeight, - offset=offset, orient=orient, subtitleColor=subtitleColor, - subtitleFont=subtitleFont, subtitleFontSize=subtitleFontSize, - subtitleFontStyle=subtitleFontStyle, - subtitleFontWeight=subtitleFontWeight, - subtitleLineHeight=subtitleLineHeight, - subtitlePadding=subtitlePadding, zindex=zindex, **kwds) - - -class TitleFrame(VegaLiteSchema): - """TitleFrame schema wrapper - - enum('bounds', 'group') - """ - _schema = {'$ref': '#/definitions/TitleFrame'} - - def __init__(self, *args): - super(TitleFrame, self).__init__(*args) - - -class TitleOrient(VegaLiteSchema): - """TitleOrient schema wrapper - - enum('none', 'left', 'right', 'top', 'bottom') - """ - _schema = {'$ref': '#/definitions/TitleOrient'} - - def __init__(self, *args): - super(TitleOrient, self).__init__(*args) - - -class TitleParams(VegaLiteSchema): - """TitleParams schema wrapper - - Mapping(required=[text]) - - Parameters - ---------- - - text : anyOf(:class:`Text`, :class:`ExprRef`) - The title text. - align : :class:`Align` - Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or - ``"right"``. - anchor : :class:`TitleAnchor` - The anchor position for placing the title. One of ``"start"``, ``"middle"``, or - ``"end"``. For example, with an orientation of top these anchor positions map to a - left-, center-, or right-aligned title. - - **Default value:** ``"middle"`` for `single - `__ and `layered - `__ views. ``"start"`` for other - composite views. - - **Note:** `For now `__, ``anchor`` is - only customizable only for `single - `__ and `layered - `__ views. For other composite - views, ``anchor`` is always ``"start"``. - angle : anyOf(float, :class:`ExprRef`) - Angle in degrees of title and subtitle text. - aria : anyOf(boolean, :class:`ExprRef`) - A boolean flag indicating if `ARIA attributes - `__ should be - included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on - the output SVG group, removing the title from the ARIA accessibility tree. - - **Default value:** ``true`` - baseline : :class:`TextBaseline` - Vertical text baseline for title and subtitle text. One of ``"alphabetic"`` - (default), ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or - ``"line-bottom"``. The ``"line-top"`` and ``"line-bottom"`` values operate similarly - to ``"top"`` and ``"bottom"``, but are calculated relative to the *lineHeight* - rather than *fontSize* alone. - color : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Text color for title text. - dx : anyOf(float, :class:`ExprRef`) - Delta offset for title and subtitle text x-coordinate. - dy : anyOf(float, :class:`ExprRef`) - Delta offset for title and subtitle text y-coordinate. - font : anyOf(string, :class:`ExprRef`) - Font name for title text. - fontSize : anyOf(float, :class:`ExprRef`) - Font size in pixels for title text. - fontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - Font style for title text. - fontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight for title text. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - frame : anyOf(anyOf(:class:`TitleFrame`, string), :class:`ExprRef`) - The reference frame for the anchor position, one of ``"bounds"`` (to anchor relative - to the full bounding box) or ``"group"`` (to anchor relative to the group width or - height). - limit : anyOf(float, :class:`ExprRef`) - The maximum allowed length in pixels of title and subtitle text. - lineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line title text or title text with ``"line-top"`` or - ``"line-bottom"`` baseline. - offset : anyOf(float, :class:`ExprRef`) - The orthogonal offset in pixels by which to displace the title group from its - position along the edge of the chart. - orient : anyOf(:class:`TitleOrient`, :class:`ExprRef`) - Default title orientation ( ``"top"``, ``"bottom"``, ``"left"``, or ``"right"`` ) - style : anyOf(string, List(string)) - A `mark style property `__ - to apply to the title text mark. - - **Default value:** ``"group-title"``. - subtitle : :class:`Text` - The subtitle Text. - subtitleColor : anyOf(anyOf(None, :class:`Color`), :class:`ExprRef`) - Text color for subtitle text. - subtitleFont : anyOf(string, :class:`ExprRef`) - Font name for subtitle text. - subtitleFontSize : anyOf(float, :class:`ExprRef`) - Font size in pixels for subtitle text. - subtitleFontStyle : anyOf(:class:`FontStyle`, :class:`ExprRef`) - Font style for subtitle text. - subtitleFontWeight : anyOf(:class:`FontWeight`, :class:`ExprRef`) - Font weight for subtitle text. This can be either a string (e.g ``"bold"``, - ``"normal"`` ) or a number ( ``100``, ``200``, ``300``, ..., ``900`` where - ``"normal"`` = ``400`` and ``"bold"`` = ``700`` ). - subtitleLineHeight : anyOf(float, :class:`ExprRef`) - Line height in pixels for multi-line subtitle text. - subtitlePadding : anyOf(float, :class:`ExprRef`) - The padding in pixels between title and subtitle text. - zindex : float - The integer z-index indicating the layering of the title group relative to other - axis, mark and legend groups. - - **Default value:** ``0``. - """ - _schema = {'$ref': '#/definitions/TitleParams'} - - def __init__(self, text=Undefined, align=Undefined, anchor=Undefined, angle=Undefined, - aria=Undefined, baseline=Undefined, color=Undefined, dx=Undefined, dy=Undefined, - font=Undefined, fontSize=Undefined, fontStyle=Undefined, fontWeight=Undefined, - frame=Undefined, limit=Undefined, lineHeight=Undefined, offset=Undefined, - orient=Undefined, style=Undefined, subtitle=Undefined, subtitleColor=Undefined, - subtitleFont=Undefined, subtitleFontSize=Undefined, subtitleFontStyle=Undefined, - subtitleFontWeight=Undefined, subtitleLineHeight=Undefined, subtitlePadding=Undefined, - zindex=Undefined, **kwds): - super(TitleParams, self).__init__(text=text, align=align, anchor=anchor, angle=angle, aria=aria, - baseline=baseline, color=color, dx=dx, dy=dy, font=font, - fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, - frame=frame, limit=limit, lineHeight=lineHeight, - offset=offset, orient=orient, style=style, subtitle=subtitle, - subtitleColor=subtitleColor, subtitleFont=subtitleFont, - subtitleFontSize=subtitleFontSize, - subtitleFontStyle=subtitleFontStyle, - subtitleFontWeight=subtitleFontWeight, - subtitleLineHeight=subtitleLineHeight, - subtitlePadding=subtitlePadding, zindex=zindex, **kwds) - - -class TooltipContent(VegaLiteSchema): - """TooltipContent schema wrapper - - Mapping(required=[content]) - - Parameters - ---------- - - content : enum('encoding', 'data') - - """ - _schema = {'$ref': '#/definitions/TooltipContent'} - - def __init__(self, content=Undefined, **kwds): - super(TooltipContent, self).__init__(content=content, **kwds) - - -class TopLevelParameter(VegaLiteSchema): - """TopLevelParameter schema wrapper - - anyOf(:class:`VariableParameter`, :class:`TopLevelSelectionParameter`) - """ - _schema = {'$ref': '#/definitions/TopLevelParameter'} - - def __init__(self, *args, **kwds): - super(TopLevelParameter, self).__init__(*args, **kwds) - - -class TopLevelSelectionParameter(TopLevelParameter): - """TopLevelSelectionParameter schema wrapper - - Mapping(required=[name, select]) - - Parameters - ---------- - - name : :class:`ParameterName` - Required. A unique name for the selection parameter. Selection names should be valid - JavaScript identifiers: they should contain only alphanumeric characters (or "$", or - "_") and may not start with a digit. Reserved keywords that may not be used as - parameter names are "datum", "event", "item", and "parent". - select : anyOf(:class:`SelectionType`, :class:`PointSelectionConfig`, :class:`IntervalSelectionConfig`) - Determines the default event processing and data query for the selection. Vega-Lite - currently supports two selection types: - - - * ``"point"`` -- to select multiple discrete data values; the first value is - selected on ``click`` and additional values toggled on shift-click. - * ``"interval"`` -- to select a continuous range of data values on ``drag``. - bind : anyOf(:class:`Binding`, Mapping(required=[]), :class:`LegendBinding`, string) - When set, a selection is populated by input elements (also known as dynamic query - widgets) or by interacting with the corresponding legend. Direct manipulation - interaction is disabled by default; to re-enable it, set the selection's `on - `__ - property. - - Legend bindings are restricted to selections that only specify a single field or - encoding. - - Query widget binding takes the form of Vega's `input element binding definition - `__ or can be a mapping between - projected field/encodings and binding definitions. - - **See also:** `bind `__ - documentation. - value : anyOf(:class:`SelectionInit`, List(:class:`SelectionInitMapping`), :class:`SelectionInitIntervalMapping`) - Initialize the selection with a mapping between `projected channels or field names - `__ and initial - values. - - **See also:** `init `__ - documentation. - views : List(string) - By default, top-level selections are applied to every view in the visualization. If - this property is specified, selections will only be applied to views with the given - names. - """ - _schema = {'$ref': '#/definitions/TopLevelSelectionParameter'} - - def __init__(self, name=Undefined, select=Undefined, bind=Undefined, value=Undefined, - views=Undefined, **kwds): - super(TopLevelSelectionParameter, self).__init__(name=name, select=select, bind=bind, - value=value, views=views, **kwds) - - -class TopLevelSpec(VegaLiteSchema): - """TopLevelSpec schema wrapper - - anyOf(:class:`TopLevelUnitSpec`, :class:`TopLevelFacetSpec`, :class:`TopLevelLayerSpec`, - :class:`TopLevelRepeatSpec`, :class:`TopLevelConcatSpec`, :class:`TopLevelVConcatSpec`, - :class:`TopLevelHConcatSpec`) - A Vega-Lite top-level specification. This is the root class for all Vega-Lite - specifications. (The json schema is generated from this type.) - """ - _schema = {'$ref': '#/definitions/TopLevelSpec'} - - def __init__(self, *args, **kwds): - super(TopLevelSpec, self).__init__(*args, **kwds) - - -class TopLevelConcatSpec(TopLevelSpec): - """TopLevelConcatSpec schema wrapper - - Mapping(required=[concat]) - - Parameters - ---------- - - concat : List(:class:`NonNormalizedSpec`) - A list of views to be concatenated. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - autosize : anyOf(:class:`AutosizeType`, :class:`AutoSizeParams`) - How the visualization size should be determined. If a string, should be one of - ``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify - parameters for content sizing and automatic resizing. - - **Default value** : ``pad`` - background : anyOf(:class:`Color`, :class:`ExprRef`) - CSS color property to use as the background of the entire view. - - **Default value:** ``"white"`` - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - columns : float - The number of columns to include in the view composition layout. - - **Default value** : ``undefined`` -- An infinite number of columns (a single row) - will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using - the ``column`` channel (for ``facet`` and ``repeat`` ). - - **Note** : - - 1) This property is only for: - - - * the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` ) - * the ``facet`` and ``repeat`` operator with one field/repetition definition - (without row/column nesting) - - 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` ) - and to using the ``row`` channel (for ``facet`` and ``repeat`` ). - config : :class:`Config` - Vega-Lite configuration object. This property can only be defined at the top-level - of a specification. - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - datasets : :class:`Datasets` - A global data store for named datasets. This is a mapping from names to inline - datasets. This can be an array of objects or primitive values or a string. Arrays of - primitive values are ingested as objects with a ``data`` property. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - padding : anyOf(:class:`Padding`, :class:`ExprRef`) - The default visualization padding, in pixels, from the edge of the visualization - canvas to the data rectangle. If a number, specifies padding for all sides. If an - object, the value should have the format ``{"left": 5, "top": 5, "right": 5, - "bottom": 5}`` to specify padding for each side of the visualization. - - **Default value** : ``5`` - params : List(:class:`TopLevelParameter`) - Dynamic variables or selections that parameterize a visualization. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - usermeta : :class:`Dict` - Optional metadata that will be passed to Vega. This object is completely ignored by - Vega and Vega-Lite and can be used for custom metadata. - $schema : string - URL to `JSON schema `__ for a Vega-Lite specification. - Unless you have a reason to change this, use - ``https://vega.github.io/schema/vega-lite/v5.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelConcatSpec'} - - def __init__(self, concat=Undefined, align=Undefined, autosize=Undefined, background=Undefined, - bounds=Undefined, center=Undefined, columns=Undefined, config=Undefined, - data=Undefined, datasets=Undefined, description=Undefined, name=Undefined, - padding=Undefined, params=Undefined, resolve=Undefined, spacing=Undefined, - title=Undefined, transform=Undefined, usermeta=Undefined, **kwds): - super(TopLevelConcatSpec, self).__init__(concat=concat, align=align, autosize=autosize, - background=background, bounds=bounds, center=center, - columns=columns, config=config, data=data, - datasets=datasets, description=description, name=name, - padding=padding, params=params, resolve=resolve, - spacing=spacing, title=title, transform=transform, - usermeta=usermeta, **kwds) - - -class TopLevelFacetSpec(TopLevelSpec): - """TopLevelFacetSpec schema wrapper - - Mapping(required=[data, facet, spec]) - - Parameters - ---------- - - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - facet : anyOf(:class:`FacetFieldDef`, :class:`FacetMapping`) - Definition for how to facet the data. One of: 1) `a field definition for faceting - the plot by one field - `__ 2) `An object that - maps row and column channels to their field definitions - `__ - spec : anyOf(:class:`LayerSpec`, :class:`UnitSpecWithFrame`) - A specification of the view that gets faceted. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - autosize : anyOf(:class:`AutosizeType`, :class:`AutoSizeParams`) - How the visualization size should be determined. If a string, should be one of - ``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify - parameters for content sizing and automatic resizing. - - **Default value** : ``pad`` - background : anyOf(:class:`Color`, :class:`ExprRef`) - CSS color property to use as the background of the entire view. - - **Default value:** ``"white"`` - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - columns : float - The number of columns to include in the view composition layout. - - **Default value** : ``undefined`` -- An infinite number of columns (a single row) - will be assumed. This is equivalent to ``hconcat`` (for ``concat`` ) and to using - the ``column`` channel (for ``facet`` and ``repeat`` ). - - **Note** : - - 1) This property is only for: - - - * the general (wrappable) ``concat`` operator (not ``hconcat`` / ``vconcat`` ) - * the ``facet`` and ``repeat`` operator with one field/repetition definition - (without row/column nesting) - - 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat`` ) - and to using the ``row`` channel (for ``facet`` and ``repeat`` ). - config : :class:`Config` - Vega-Lite configuration object. This property can only be defined at the top-level - of a specification. - datasets : :class:`Datasets` - A global data store for named datasets. This is a mapping from names to inline - datasets. This can be an array of objects or primitive values or a string. Arrays of - primitive values are ingested as objects with a ``data`` property. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - padding : anyOf(:class:`Padding`, :class:`ExprRef`) - The default visualization padding, in pixels, from the edge of the visualization - canvas to the data rectangle. If a number, specifies padding for all sides. If an - object, the value should have the format ``{"left": 5, "top": 5, "right": 5, - "bottom": 5}`` to specify padding for each side of the visualization. - - **Default value** : ``5`` - params : List(:class:`TopLevelParameter`) - Dynamic variables or selections that parameterize a visualization. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - usermeta : :class:`Dict` - Optional metadata that will be passed to Vega. This object is completely ignored by - Vega and Vega-Lite and can be used for custom metadata. - $schema : string - URL to `JSON schema `__ for a Vega-Lite specification. - Unless you have a reason to change this, use - ``https://vega.github.io/schema/vega-lite/v5.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelFacetSpec'} - - def __init__(self, data=Undefined, facet=Undefined, spec=Undefined, align=Undefined, - autosize=Undefined, background=Undefined, bounds=Undefined, center=Undefined, - columns=Undefined, config=Undefined, datasets=Undefined, description=Undefined, - name=Undefined, padding=Undefined, params=Undefined, resolve=Undefined, - spacing=Undefined, title=Undefined, transform=Undefined, usermeta=Undefined, **kwds): - super(TopLevelFacetSpec, self).__init__(data=data, facet=facet, spec=spec, align=align, - autosize=autosize, background=background, bounds=bounds, - center=center, columns=columns, config=config, - datasets=datasets, description=description, name=name, - padding=padding, params=params, resolve=resolve, - spacing=spacing, title=title, transform=transform, - usermeta=usermeta, **kwds) - - -class TopLevelHConcatSpec(TopLevelSpec): - """TopLevelHConcatSpec schema wrapper - - Mapping(required=[hconcat]) - - Parameters - ---------- - - hconcat : List(:class:`NonNormalizedSpec`) - A list of views to be concatenated and put into a row. - autosize : anyOf(:class:`AutosizeType`, :class:`AutoSizeParams`) - How the visualization size should be determined. If a string, should be one of - ``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify - parameters for content sizing and automatic resizing. - - **Default value** : ``pad`` - background : anyOf(:class:`Color`, :class:`ExprRef`) - CSS color property to use as the background of the entire view. - - **Default value:** ``"white"`` - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : boolean - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - **Default value:** ``false`` - config : :class:`Config` - Vega-Lite configuration object. This property can only be defined at the top-level - of a specification. - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - datasets : :class:`Datasets` - A global data store for named datasets. This is a mapping from names to inline - datasets. This can be an array of objects or primitive values or a string. Arrays of - primitive values are ingested as objects with a ``data`` property. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - padding : anyOf(:class:`Padding`, :class:`ExprRef`) - The default visualization padding, in pixels, from the edge of the visualization - canvas to the data rectangle. If a number, specifies padding for all sides. If an - object, the value should have the format ``{"left": 5, "top": 5, "right": 5, - "bottom": 5}`` to specify padding for each side of the visualization. - - **Default value** : ``5`` - params : List(:class:`TopLevelParameter`) - Dynamic variables or selections that parameterize a visualization. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : float - The spacing in pixels between sub-views of the concat operator. - - **Default value** : ``10`` - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - usermeta : :class:`Dict` - Optional metadata that will be passed to Vega. This object is completely ignored by - Vega and Vega-Lite and can be used for custom metadata. - $schema : string - URL to `JSON schema `__ for a Vega-Lite specification. - Unless you have a reason to change this, use - ``https://vega.github.io/schema/vega-lite/v5.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelHConcatSpec'} - - def __init__(self, hconcat=Undefined, autosize=Undefined, background=Undefined, bounds=Undefined, - center=Undefined, config=Undefined, data=Undefined, datasets=Undefined, - description=Undefined, name=Undefined, padding=Undefined, params=Undefined, - resolve=Undefined, spacing=Undefined, title=Undefined, transform=Undefined, - usermeta=Undefined, **kwds): - super(TopLevelHConcatSpec, self).__init__(hconcat=hconcat, autosize=autosize, - background=background, bounds=bounds, center=center, - config=config, data=data, datasets=datasets, - description=description, name=name, padding=padding, - params=params, resolve=resolve, spacing=spacing, - title=title, transform=transform, usermeta=usermeta, - **kwds) - - -class TopLevelLayerSpec(TopLevelSpec): - """TopLevelLayerSpec schema wrapper - - Mapping(required=[layer]) - - Parameters - ---------- - - layer : List(anyOf(:class:`LayerSpec`, :class:`UnitSpec`)) - Layer or single view specifications to be layered. - - **Note** : Specifications inside ``layer`` cannot use ``row`` and ``column`` - channels as layering facet specifications is not allowed. Instead, use the `facet - operator `__ and place a layer - inside a facet. - autosize : anyOf(:class:`AutosizeType`, :class:`AutoSizeParams`) - How the visualization size should be determined. If a string, should be one of - ``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify - parameters for content sizing and automatic resizing. - - **Default value** : ``pad`` - background : anyOf(:class:`Color`, :class:`ExprRef`) - CSS color property to use as the background of the entire view. - - **Default value:** ``"white"`` - config : :class:`Config` - Vega-Lite configuration object. This property can only be defined at the top-level - of a specification. - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - datasets : :class:`Datasets` - A global data store for named datasets. This is a mapping from names to inline - datasets. This can be an array of objects or primitive values or a string. Arrays of - primitive values are ingested as objects with a ``data`` property. - description : string - Description of this mark for commenting purpose. - encoding : :class:`SharedEncoding` - A shared key-value mapping between encoding channels and definition of fields in the - underlying layers. - height : anyOf(float, string, :class:`Step`) - The height of a visualization. - - - * For a plot with a continuous y-field, height should be a number. - * For a plot with either a discrete y-field or no y-field, height can be either a - number indicating a fixed height or an object in the form of ``{step: number}`` - defining the height per discrete step. (No y-field is equivalent to having one - discrete step.) - * To enable responsive sizing on height, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousHeight`` for a plot with a - continuous y-field and ``config.view.discreteHeight`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - height of a single view and the ``"container"`` option cannot be used. - - **See also:** `height `__ - documentation. - name : string - Name of the visualization for later reference. - padding : anyOf(:class:`Padding`, :class:`ExprRef`) - The default visualization padding, in pixels, from the edge of the visualization - canvas to the data rectangle. If a number, specifies padding for all sides. If an - object, the value should have the format ``{"left": 5, "top": 5, "right": 5, - "bottom": 5}`` to specify padding for each side of the visualization. - - **Default value** : ``5`` - params : List(:class:`TopLevelParameter`) - Dynamic variables or selections that parameterize a visualization. - projection : :class:`Projection` - An object defining properties of the geographic projection shared by underlying - layers. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - usermeta : :class:`Dict` - Optional metadata that will be passed to Vega. This object is completely ignored by - Vega and Vega-Lite and can be used for custom metadata. - view : :class:`ViewBackground` - An object defining the view background's fill and stroke. - - **Default value:** none (transparent) - width : anyOf(float, string, :class:`Step`) - The width of a visualization. - - - * For a plot with a continuous x-field, width should be a number. - * For a plot with either a discrete x-field or no x-field, width can be either a - number indicating a fixed width or an object in the form of ``{step: number}`` - defining the width per discrete step. (No x-field is equivalent to having one - discrete step.) - * To enable responsive sizing on width, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousWidth`` for a plot with a - continuous x-field and ``config.view.discreteWidth`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - width of a single view and the ``"container"`` option cannot be used. - - **See also:** `width `__ - documentation. - $schema : string - URL to `JSON schema `__ for a Vega-Lite specification. - Unless you have a reason to change this, use - ``https://vega.github.io/schema/vega-lite/v5.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelLayerSpec'} - - def __init__(self, layer=Undefined, autosize=Undefined, background=Undefined, config=Undefined, - data=Undefined, datasets=Undefined, description=Undefined, encoding=Undefined, - height=Undefined, name=Undefined, padding=Undefined, params=Undefined, - projection=Undefined, resolve=Undefined, title=Undefined, transform=Undefined, - usermeta=Undefined, view=Undefined, width=Undefined, **kwds): - super(TopLevelLayerSpec, self).__init__(layer=layer, autosize=autosize, background=background, - config=config, data=data, datasets=datasets, - description=description, encoding=encoding, - height=height, name=name, padding=padding, - params=params, projection=projection, resolve=resolve, - title=title, transform=transform, usermeta=usermeta, - view=view, width=width, **kwds) - - -class TopLevelRepeatSpec(TopLevelSpec): - """TopLevelRepeatSpec schema wrapper - - anyOf(Mapping(required=[repeat, spec]), Mapping(required=[repeat, spec])) - """ - _schema = {'$ref': '#/definitions/TopLevelRepeatSpec'} - - def __init__(self, *args, **kwds): - super(TopLevelRepeatSpec, self).__init__(*args, **kwds) - - -class TopLevelUnitSpec(TopLevelSpec): - """TopLevelUnitSpec schema wrapper - - Mapping(required=[data, mark]) - - Parameters - ---------- - - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - mark : :class:`AnyMark` - A string describing the mark type (one of ``"bar"``, ``"circle"``, ``"square"``, - ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"rule"``, ``"geoshape"``, and - ``"text"`` ) or a `mark definition object - `__. - align : anyOf(:class:`LayoutAlign`, :class:`RowColLayoutAlign`) - The alignment to apply to grid rows and columns. The supported string values are - ``"all"``, ``"each"``, and ``"none"``. - - - * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply - placed one after the other. - * For ``"each"``, subviews will be aligned into a clean grid structure, but each row - or column may be of variable size. - * For ``"all"``, subviews will be aligned and each row or column will be sized - identically based on the maximum observed size. String values for this property - will be applied to both grid rows and columns. - - Alternatively, an object value of the form ``{"row": string, "column": string}`` can - be used to supply different alignments for rows and columns. - - **Default value:** ``"all"``. - autosize : anyOf(:class:`AutosizeType`, :class:`AutoSizeParams`) - How the visualization size should be determined. If a string, should be one of - ``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify - parameters for content sizing and automatic resizing. - - **Default value** : ``pad`` - background : anyOf(:class:`Color`, :class:`ExprRef`) - CSS color property to use as the background of the entire view. - - **Default value:** ``"white"`` - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : anyOf(boolean, :class:`RowColboolean`) - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - An object value of the form ``{"row": boolean, "column": boolean}`` can be used to - supply different centering values for rows and columns. - - **Default value:** ``false`` - config : :class:`Config` - Vega-Lite configuration object. This property can only be defined at the top-level - of a specification. - datasets : :class:`Datasets` - A global data store for named datasets. This is a mapping from names to inline - datasets. This can be an array of objects or primitive values or a string. Arrays of - primitive values are ingested as objects with a ``data`` property. - description : string - Description of this mark for commenting purpose. - encoding : :class:`FacetedEncoding` - A key-value mapping between encoding channels and definition of fields. - height : anyOf(float, string, :class:`Step`) - The height of a visualization. - - - * For a plot with a continuous y-field, height should be a number. - * For a plot with either a discrete y-field or no y-field, height can be either a - number indicating a fixed height or an object in the form of ``{step: number}`` - defining the height per discrete step. (No y-field is equivalent to having one - discrete step.) - * To enable responsive sizing on height, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousHeight`` for a plot with a - continuous y-field and ``config.view.discreteHeight`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - height of a single view and the ``"container"`` option cannot be used. - - **See also:** `height `__ - documentation. - name : string - Name of the visualization for later reference. - padding : anyOf(:class:`Padding`, :class:`ExprRef`) - The default visualization padding, in pixels, from the edge of the visualization - canvas to the data rectangle. If a number, specifies padding for all sides. If an - object, the value should have the format ``{"left": 5, "top": 5, "right": 5, - "bottom": 5}`` to specify padding for each side of the visualization. - - **Default value** : ``5`` - params : List(:class:`TopLevelParameter`) - An array of parameters that may either be simple variables, or more complex - selections that map user input to data queries. - projection : :class:`Projection` - An object defining properties of geographic projection, which will be applied to - ``shape`` path for ``"geoshape"`` marks and to ``latitude`` and ``"longitude"`` - channels for other marks. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : anyOf(float, :class:`RowColnumber`) - The spacing in pixels between sub-views of the composition operator. An object of - the form ``{"row": number, "column": number}`` can be used to set different spacing - values for rows and columns. - - **Default value** : Depends on ``"spacing"`` property of `the view composition - configuration `__ ( - ``20`` by default) - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - usermeta : :class:`Dict` - Optional metadata that will be passed to Vega. This object is completely ignored by - Vega and Vega-Lite and can be used for custom metadata. - view : :class:`ViewBackground` - An object defining the view background's fill and stroke. - - **Default value:** none (transparent) - width : anyOf(float, string, :class:`Step`) - The width of a visualization. - - - * For a plot with a continuous x-field, width should be a number. - * For a plot with either a discrete x-field or no x-field, width can be either a - number indicating a fixed width or an object in the form of ``{step: number}`` - defining the width per discrete step. (No x-field is equivalent to having one - discrete step.) - * To enable responsive sizing on width, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousWidth`` for a plot with a - continuous x-field and ``config.view.discreteWidth`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - width of a single view and the ``"container"`` option cannot be used. - - **See also:** `width `__ - documentation. - $schema : string - URL to `JSON schema `__ for a Vega-Lite specification. - Unless you have a reason to change this, use - ``https://vega.github.io/schema/vega-lite/v5.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelUnitSpec'} - - def __init__(self, data=Undefined, mark=Undefined, align=Undefined, autosize=Undefined, - background=Undefined, bounds=Undefined, center=Undefined, config=Undefined, - datasets=Undefined, description=Undefined, encoding=Undefined, height=Undefined, - name=Undefined, padding=Undefined, params=Undefined, projection=Undefined, - resolve=Undefined, spacing=Undefined, title=Undefined, transform=Undefined, - usermeta=Undefined, view=Undefined, width=Undefined, **kwds): - super(TopLevelUnitSpec, self).__init__(data=data, mark=mark, align=align, autosize=autosize, - background=background, bounds=bounds, center=center, - config=config, datasets=datasets, - description=description, encoding=encoding, - height=height, name=name, padding=padding, params=params, - projection=projection, resolve=resolve, spacing=spacing, - title=title, transform=transform, usermeta=usermeta, - view=view, width=width, **kwds) - - -class TopLevelVConcatSpec(TopLevelSpec): - """TopLevelVConcatSpec schema wrapper - - Mapping(required=[vconcat]) - - Parameters - ---------- - - vconcat : List(:class:`NonNormalizedSpec`) - A list of views to be concatenated and put into a column. - autosize : anyOf(:class:`AutosizeType`, :class:`AutoSizeParams`) - How the visualization size should be determined. If a string, should be one of - ``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify - parameters for content sizing and automatic resizing. - - **Default value** : ``pad`` - background : anyOf(:class:`Color`, :class:`ExprRef`) - CSS color property to use as the background of the entire view. - - **Default value:** ``"white"`` - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : boolean - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - **Default value:** ``false`` - config : :class:`Config` - Vega-Lite configuration object. This property can only be defined at the top-level - of a specification. - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - datasets : :class:`Datasets` - A global data store for named datasets. This is a mapping from names to inline - datasets. This can be an array of objects or primitive values or a string. Arrays of - primitive values are ingested as objects with a ``data`` property. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - padding : anyOf(:class:`Padding`, :class:`ExprRef`) - The default visualization padding, in pixels, from the edge of the visualization - canvas to the data rectangle. If a number, specifies padding for all sides. If an - object, the value should have the format ``{"left": 5, "top": 5, "right": 5, - "bottom": 5}`` to specify padding for each side of the visualization. - - **Default value** : ``5`` - params : List(:class:`TopLevelParameter`) - Dynamic variables or selections that parameterize a visualization. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : float - The spacing in pixels between sub-views of the concat operator. - - **Default value** : ``10`` - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - usermeta : :class:`Dict` - Optional metadata that will be passed to Vega. This object is completely ignored by - Vega and Vega-Lite and can be used for custom metadata. - $schema : string - URL to `JSON schema `__ for a Vega-Lite specification. - Unless you have a reason to change this, use - ``https://vega.github.io/schema/vega-lite/v5.json``. Setting the ``$schema`` - property allows automatic validation and autocomplete in editors that support JSON - schema. - """ - _schema = {'$ref': '#/definitions/TopLevelVConcatSpec'} - - def __init__(self, vconcat=Undefined, autosize=Undefined, background=Undefined, bounds=Undefined, - center=Undefined, config=Undefined, data=Undefined, datasets=Undefined, - description=Undefined, name=Undefined, padding=Undefined, params=Undefined, - resolve=Undefined, spacing=Undefined, title=Undefined, transform=Undefined, - usermeta=Undefined, **kwds): - super(TopLevelVConcatSpec, self).__init__(vconcat=vconcat, autosize=autosize, - background=background, bounds=bounds, center=center, - config=config, data=data, datasets=datasets, - description=description, name=name, padding=padding, - params=params, resolve=resolve, spacing=spacing, - title=title, transform=transform, usermeta=usermeta, - **kwds) - - -class TopoDataFormat(DataFormat): - """TopoDataFormat schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - feature : string - The name of the TopoJSON object set to convert to a GeoJSON feature collection. For - example, in a map of the world, there may be an object set named ``"countries"``. - Using the feature property, we can extract this set and generate a GeoJSON feature - object for each country. - mesh : string - The name of the TopoJSON object set to convert to mesh. Similar to the ``feature`` - option, ``mesh`` extracts a named TopoJSON object set. Unlike the ``feature`` - option, the corresponding geo data is returned as a single, unified mesh instance, - not as individual GeoJSON features. Extracting a mesh is useful for more efficiently - drawing borders or other geographic elements that you do not need to associate with - specific regions such as individual countries, states or counties. - parse : anyOf(:class:`Parse`, None) - If set to ``null``, disable type inference based on the spec and only use type - inference based on the data. Alternatively, a parsing directive object can be - provided for explicit data types. Each property of the object corresponds to a field - name, and the value to the desired data type (one of ``"number"``, ``"boolean"``, - ``"date"``, or null (do not parse the field)). For example, ``"parse": - {"modified_on": "date"}`` parses the ``modified_on`` field in each input record a - Date value. - - For ``"date"``, we parse data based using JavaScript's `Date.parse() - `__. - For Specific date formats can be provided (e.g., ``{foo: "date:'%m%d%Y'"}`` ), using - the `d3-time-format syntax `__. - UTC date format parsing is supported similarly (e.g., ``{foo: "utc:'%m%d%Y'"}`` ). - See more about `UTC time - `__ - type : string - Type of input data: ``"json"``, ``"csv"``, ``"tsv"``, ``"dsv"``. - - **Default value:** The default format type is determined by the extension of the - file URL. If no extension is detected, ``"json"`` will be used by default. - """ - _schema = {'$ref': '#/definitions/TopoDataFormat'} - - def __init__(self, feature=Undefined, mesh=Undefined, parse=Undefined, type=Undefined, **kwds): - super(TopoDataFormat, self).__init__(feature=feature, mesh=mesh, parse=parse, type=type, **kwds) - - -class Transform(VegaLiteSchema): - """Transform schema wrapper - - anyOf(:class:`AggregateTransform`, :class:`BinTransform`, :class:`CalculateTransform`, - :class:`DensityTransform`, :class:`FilterTransform`, :class:`FlattenTransform`, - :class:`FoldTransform`, :class:`ImputeTransform`, :class:`JoinAggregateTransform`, - :class:`LoessTransform`, :class:`LookupTransform`, :class:`QuantileTransform`, - :class:`RegressionTransform`, :class:`TimeUnitTransform`, :class:`SampleTransform`, - :class:`StackTransform`, :class:`WindowTransform`, :class:`PivotTransform`) - """ - _schema = {'$ref': '#/definitions/Transform'} - - def __init__(self, *args, **kwds): - super(Transform, self).__init__(*args, **kwds) - - -class AggregateTransform(Transform): - """AggregateTransform schema wrapper - - Mapping(required=[aggregate]) - - Parameters - ---------- - - aggregate : List(:class:`AggregatedFieldDef`) - Array of objects that define fields to aggregate. - groupby : List(:class:`FieldName`) - The data fields to group by. If not specified, a single group containing all data - objects will be used. - """ - _schema = {'$ref': '#/definitions/AggregateTransform'} - - def __init__(self, aggregate=Undefined, groupby=Undefined, **kwds): - super(AggregateTransform, self).__init__(aggregate=aggregate, groupby=groupby, **kwds) - - -class BinTransform(Transform): - """BinTransform schema wrapper - - Mapping(required=[bin, field, as]) - - Parameters - ---------- - - bin : anyOf(boolean, :class:`BinParams`) - An object indicating bin properties, or simply ``true`` for using default bin - parameters. - field : :class:`FieldName` - The data field to bin. - as : anyOf(:class:`FieldName`, List(:class:`FieldName`)) - The output fields at which to write the start and end bin values. This can be either - a string or an array of strings with two elements denoting the name for the fields - for bin start and bin end respectively. If a single string (e.g., ``"val"`` ) is - provided, the end field will be ``"val_end"``. - """ - _schema = {'$ref': '#/definitions/BinTransform'} - - def __init__(self, bin=Undefined, field=Undefined, **kwds): - super(BinTransform, self).__init__(bin=bin, field=field, **kwds) - - -class CalculateTransform(Transform): - """CalculateTransform schema wrapper - - Mapping(required=[calculate, as]) - - Parameters - ---------- - - calculate : string - A `expression `__ - string. Use the variable ``datum`` to refer to the current data object. - as : :class:`FieldName` - The field for storing the computed formula value. - """ - _schema = {'$ref': '#/definitions/CalculateTransform'} - - def __init__(self, calculate=Undefined, **kwds): - super(CalculateTransform, self).__init__(calculate=calculate, **kwds) - - -class DensityTransform(Transform): - """DensityTransform schema wrapper - - Mapping(required=[density]) - - Parameters - ---------- - - density : :class:`FieldName` - The data field for which to perform density estimation. - bandwidth : float - The bandwidth (standard deviation) of the Gaussian kernel. If unspecified or set to - zero, the bandwidth value is automatically estimated from the input data using - Scott’s rule. - counts : boolean - A boolean flag indicating if the output values should be probability estimates - (false) or smoothed counts (true). - - **Default value:** ``false`` - cumulative : boolean - A boolean flag indicating whether to produce density estimates (false) or cumulative - density estimates (true). - - **Default value:** ``false`` - extent : List(float) - A [min, max] domain from which to sample the distribution. If unspecified, the - extent will be determined by the observed minimum and maximum values of the density - value field. - groupby : List(:class:`FieldName`) - The data fields to group by. If not specified, a single group containing all data - objects will be used. - maxsteps : float - The maximum number of samples to take along the extent domain for plotting the - density. - - **Default value:** ``200`` - minsteps : float - The minimum number of samples to take along the extent domain for plotting the - density. - - **Default value:** ``25`` - steps : float - The exact number of samples to take along the extent domain for plotting the - density. If specified, overrides both minsteps and maxsteps to set an exact number - of uniform samples. Potentially useful in conjunction with a fixed extent to ensure - consistent sample points for stacked densities. - as : List(:class:`FieldName`) - The output fields for the sample value and corresponding density estimate. - - **Default value:** ``["value", "density"]`` - """ - _schema = {'$ref': '#/definitions/DensityTransform'} - - def __init__(self, density=Undefined, bandwidth=Undefined, counts=Undefined, cumulative=Undefined, - extent=Undefined, groupby=Undefined, maxsteps=Undefined, minsteps=Undefined, - steps=Undefined, **kwds): - super(DensityTransform, self).__init__(density=density, bandwidth=bandwidth, counts=counts, - cumulative=cumulative, extent=extent, groupby=groupby, - maxsteps=maxsteps, minsteps=minsteps, steps=steps, **kwds) - - -class FilterTransform(Transform): - """FilterTransform schema wrapper - - Mapping(required=[filter]) - - Parameters - ---------- - - filter : :class:`PredicateComposition` - The ``filter`` property must be a predication definition, which can take one of the - following forms: - - 1) an `expression `__ - string, where ``datum`` can be used to refer to the current data object. For - example, ``{filter: "datum.b2 > 60"}`` would make the output data includes only - items that have values in the field ``b2`` over 60. - - 2) one of the `field predicates - `__ : `equal - `__, `lt - `__, `lte - `__, `gt - `__, `gte - `__, `range - `__, `oneOf - `__, or - `valid `__, - - 3) a `selection predicate - `__, which - define the names of a selection that the data point should belong to (or a logical - composition of selections). - - 4) a `logical composition - `__ of (1), (2), - or (3). - """ - _schema = {'$ref': '#/definitions/FilterTransform'} - - def __init__(self, filter=Undefined, **kwds): - super(FilterTransform, self).__init__(filter=filter, **kwds) - - -class FlattenTransform(Transform): - """FlattenTransform schema wrapper - - Mapping(required=[flatten]) - - Parameters - ---------- - - flatten : List(:class:`FieldName`) - An array of one or more data fields containing arrays to flatten. If multiple fields - are specified, their array values should have a parallel structure, ideally with the - same length. If the lengths of parallel arrays do not match, the longest array will - be used with ``null`` values added for missing entries. - as : List(:class:`FieldName`) - The output field names for extracted array values. - - **Default value:** The field name of the corresponding array field - """ - _schema = {'$ref': '#/definitions/FlattenTransform'} - - def __init__(self, flatten=Undefined, **kwds): - super(FlattenTransform, self).__init__(flatten=flatten, **kwds) - - -class FoldTransform(Transform): - """FoldTransform schema wrapper - - Mapping(required=[fold]) - - Parameters - ---------- - - fold : List(:class:`FieldName`) - An array of data fields indicating the properties to fold. - as : List(:class:`FieldName`) - The output field names for the key and value properties produced by the fold - transform. **Default value:** ``["key", "value"]`` - """ - _schema = {'$ref': '#/definitions/FoldTransform'} - - def __init__(self, fold=Undefined, **kwds): - super(FoldTransform, self).__init__(fold=fold, **kwds) - - -class ImputeTransform(Transform): - """ImputeTransform schema wrapper - - Mapping(required=[impute, key]) - - Parameters - ---------- - - impute : :class:`FieldName` - The data field for which the missing values should be imputed. - key : :class:`FieldName` - A key field that uniquely identifies data objects within a group. Missing key values - (those occurring in the data but not in the current group) will be imputed. - frame : List(anyOf(None, float)) - A frame specification as a two-element array used to control the window over which - the specified method is applied. The array entries should either be a number - indicating the offset from the current data object, or null to indicate unbounded - rows preceding or following the current data object. For example, the value ``[-5, - 5]`` indicates that the window should include five objects preceding and five - objects following the current object. - - **Default value:** : ``[null, null]`` indicating that the window includes all - objects. - groupby : List(:class:`FieldName`) - An optional array of fields by which to group the values. Imputation will then be - performed on a per-group basis. - keyvals : anyOf(List(Any), :class:`ImputeSequence`) - Defines the key values that should be considered for imputation. An array of key - values or an object defining a `number sequence - `__. - - If provided, this will be used in addition to the key values observed within the - input data. If not provided, the values will be derived from all unique values of - the ``key`` field. For ``impute`` in ``encoding``, the key field is the x-field if - the y-field is imputed, or vice versa. - - If there is no impute grouping, this property *must* be specified. - method : :class:`ImputeMethod` - The imputation method to use for the field value of imputed data objects. One of - ``"value"``, ``"mean"``, ``"median"``, ``"max"`` or ``"min"``. - - **Default value:** ``"value"`` - value : Any - The field value to use when the imputation ``method`` is ``"value"``. - """ - _schema = {'$ref': '#/definitions/ImputeTransform'} - - def __init__(self, impute=Undefined, key=Undefined, frame=Undefined, groupby=Undefined, - keyvals=Undefined, method=Undefined, value=Undefined, **kwds): - super(ImputeTransform, self).__init__(impute=impute, key=key, frame=frame, groupby=groupby, - keyvals=keyvals, method=method, value=value, **kwds) - - -class JoinAggregateTransform(Transform): - """JoinAggregateTransform schema wrapper - - Mapping(required=[joinaggregate]) - - Parameters - ---------- - - joinaggregate : List(:class:`JoinAggregateFieldDef`) - The definition of the fields in the join aggregate, and what calculations to use. - groupby : List(:class:`FieldName`) - The data fields for partitioning the data objects into separate groups. If - unspecified, all data points will be in a single group. - """ - _schema = {'$ref': '#/definitions/JoinAggregateTransform'} - - def __init__(self, joinaggregate=Undefined, groupby=Undefined, **kwds): - super(JoinAggregateTransform, self).__init__(joinaggregate=joinaggregate, groupby=groupby, - **kwds) - - -class LoessTransform(Transform): - """LoessTransform schema wrapper - - Mapping(required=[loess, on]) - - Parameters - ---------- - - loess : :class:`FieldName` - The data field of the dependent variable to smooth. - on : :class:`FieldName` - The data field of the independent variable to use a predictor. - bandwidth : float - A bandwidth parameter in the range ``[0, 1]`` that determines the amount of - smoothing. - - **Default value:** ``0.3`` - groupby : List(:class:`FieldName`) - The data fields to group by. If not specified, a single group containing all data - objects will be used. - as : List(:class:`FieldName`) - The output field names for the smoothed points generated by the loess transform. - - **Default value:** The field names of the input x and y values. - """ - _schema = {'$ref': '#/definitions/LoessTransform'} - - def __init__(self, loess=Undefined, on=Undefined, bandwidth=Undefined, groupby=Undefined, **kwds): - super(LoessTransform, self).__init__(loess=loess, on=on, bandwidth=bandwidth, groupby=groupby, - **kwds) - - -class LookupTransform(Transform): - """LookupTransform schema wrapper - - Mapping(required=[lookup, from]) - - Parameters - ---------- - - lookup : string - Key in primary data source. - default : Any - The default value to use if lookup fails. - - **Default value:** ``null`` - as : anyOf(:class:`FieldName`, List(:class:`FieldName`)) - The output fields on which to store the looked up data values. - - For data lookups, this property may be left blank if ``from.fields`` has been - specified (those field names will be used); if ``from.fields`` has not been - specified, ``as`` must be a string. - - For selection lookups, this property is optional: if unspecified, looked up values - will be stored under a property named for the selection; and if specified, it must - correspond to ``from.fields``. - from : anyOf(:class:`LookupData`, :class:`LookupSelection`) - Data source or selection for secondary data reference. - """ - _schema = {'$ref': '#/definitions/LookupTransform'} - - def __init__(self, lookup=Undefined, default=Undefined, **kwds): - super(LookupTransform, self).__init__(lookup=lookup, default=default, **kwds) - - -class PivotTransform(Transform): - """PivotTransform schema wrapper - - Mapping(required=[pivot, value]) - - Parameters - ---------- - - pivot : :class:`FieldName` - The data field to pivot on. The unique values of this field become new field names - in the output stream. - value : :class:`FieldName` - The data field to populate pivoted fields. The aggregate values of this field become - the values of the new pivoted fields. - groupby : List(:class:`FieldName`) - The optional data fields to group by. If not specified, a single group containing - all data objects will be used. - limit : float - An optional parameter indicating the maximum number of pivoted fields to generate. - The default ( ``0`` ) applies no limit. The pivoted ``pivot`` names are sorted in - ascending order prior to enforcing the limit. **Default value:** ``0`` - op : :class:`AggregateOp` - The aggregation operation to apply to grouped ``value`` field values. **Default - value:** ``sum`` - """ - _schema = {'$ref': '#/definitions/PivotTransform'} - - def __init__(self, pivot=Undefined, value=Undefined, groupby=Undefined, limit=Undefined, - op=Undefined, **kwds): - super(PivotTransform, self).__init__(pivot=pivot, value=value, groupby=groupby, limit=limit, - op=op, **kwds) - - -class QuantileTransform(Transform): - """QuantileTransform schema wrapper - - Mapping(required=[quantile]) - - Parameters - ---------- - - quantile : :class:`FieldName` - The data field for which to perform quantile estimation. - groupby : List(:class:`FieldName`) - The data fields to group by. If not specified, a single group containing all data - objects will be used. - probs : List(float) - An array of probabilities in the range (0, 1) for which to compute quantile values. - If not specified, the *step* parameter will be used. - step : float - A probability step size (default 0.01) for sampling quantile values. All values from - one-half the step size up to 1 (exclusive) will be sampled. This parameter is only - used if the *probs* parameter is not provided. - as : List(:class:`FieldName`) - The output field names for the probability and quantile values. - - **Default value:** ``["prob", "value"]`` - """ - _schema = {'$ref': '#/definitions/QuantileTransform'} - - def __init__(self, quantile=Undefined, groupby=Undefined, probs=Undefined, step=Undefined, **kwds): - super(QuantileTransform, self).__init__(quantile=quantile, groupby=groupby, probs=probs, - step=step, **kwds) - - -class RegressionTransform(Transform): - """RegressionTransform schema wrapper - - Mapping(required=[regression, on]) - - Parameters - ---------- - - on : :class:`FieldName` - The data field of the independent variable to use a predictor. - regression : :class:`FieldName` - The data field of the dependent variable to predict. - extent : List(float) - A [min, max] domain over the independent (x) field for the starting and ending - points of the generated trend line. - groupby : List(:class:`FieldName`) - The data fields to group by. If not specified, a single group containing all data - objects will be used. - method : enum('linear', 'log', 'exp', 'pow', 'quad', 'poly') - The functional form of the regression model. One of ``"linear"``, ``"log"``, - ``"exp"``, ``"pow"``, ``"quad"``, or ``"poly"``. - - **Default value:** ``"linear"`` - order : float - The polynomial order (number of coefficients) for the 'poly' method. - - **Default value:** ``3`` - params : boolean - A boolean flag indicating if the transform should return the regression model - parameters (one object per group), rather than trend line points. The resulting - objects include a ``coef`` array of fitted coefficient values (starting with the - intercept term and then including terms of increasing order) and an ``rSquared`` - value (indicating the total variance explained by the model). - - **Default value:** ``false`` - as : List(:class:`FieldName`) - The output field names for the smoothed points generated by the regression - transform. - - **Default value:** The field names of the input x and y values. - """ - _schema = {'$ref': '#/definitions/RegressionTransform'} - - def __init__(self, on=Undefined, regression=Undefined, extent=Undefined, groupby=Undefined, - method=Undefined, order=Undefined, params=Undefined, **kwds): - super(RegressionTransform, self).__init__(on=on, regression=regression, extent=extent, - groupby=groupby, method=method, order=order, - params=params, **kwds) - - -class SampleTransform(Transform): - """SampleTransform schema wrapper - - Mapping(required=[sample]) - - Parameters - ---------- - - sample : float - The maximum number of data objects to include in the sample. - - **Default value:** ``1000`` - """ - _schema = {'$ref': '#/definitions/SampleTransform'} - - def __init__(self, sample=Undefined, **kwds): - super(SampleTransform, self).__init__(sample=sample, **kwds) - - -class StackTransform(Transform): - """StackTransform schema wrapper - - Mapping(required=[stack, groupby, as]) - - Parameters - ---------- - - groupby : List(:class:`FieldName`) - The data fields to group by. - stack : :class:`FieldName` - The field which is stacked. - offset : enum('zero', 'center', 'normalize') - Mode for stacking marks. One of ``"zero"`` (default), ``"center"``, or - ``"normalize"``. The ``"zero"`` offset will stack starting at ``0``. The - ``"center"`` offset will center the stacks. The ``"normalize"`` offset will compute - percentage values for each stack point, with output values in the range ``[0,1]``. - - **Default value:** ``"zero"`` - sort : List(:class:`SortField`) - Field that determines the order of leaves in the stacked charts. - as : anyOf(:class:`FieldName`, List(:class:`FieldName`)) - Output field names. This can be either a string or an array of strings with two - elements denoting the name for the fields for stack start and stack end - respectively. If a single string(e.g., ``"val"`` ) is provided, the end field will - be ``"val_end"``. - """ - _schema = {'$ref': '#/definitions/StackTransform'} - - def __init__(self, groupby=Undefined, stack=Undefined, offset=Undefined, sort=Undefined, **kwds): - super(StackTransform, self).__init__(groupby=groupby, stack=stack, offset=offset, sort=sort, - **kwds) - - -class TimeUnitTransform(Transform): - """TimeUnitTransform schema wrapper - - Mapping(required=[timeUnit, field, as]) - - Parameters - ---------- - - field : :class:`FieldName` - The data field to apply time unit. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - The timeUnit. - as : :class:`FieldName` - The output field to write the timeUnit value. - """ - _schema = {'$ref': '#/definitions/TimeUnitTransform'} - - def __init__(self, field=Undefined, timeUnit=Undefined, **kwds): - super(TimeUnitTransform, self).__init__(field=field, timeUnit=timeUnit, **kwds) - - -class Type(VegaLiteSchema): - """Type schema wrapper - - enum('quantitative', 'ordinal', 'temporal', 'nominal', 'geojson') - Data type based on level of measurement - """ - _schema = {'$ref': '#/definitions/Type'} - - def __init__(self, *args): - super(Type, self).__init__(*args) - - -class TypeForShape(VegaLiteSchema): - """TypeForShape schema wrapper - - enum('nominal', 'ordinal', 'geojson') - """ - _schema = {'$ref': '#/definitions/TypeForShape'} - - def __init__(self, *args): - super(TypeForShape, self).__init__(*args) - - -class TypedFieldDef(VegaLiteSchema): - """TypedFieldDef schema wrapper - - Mapping(required=[]) - Definition object for a data field, its type and transformation of an encoding channel. - - Parameters - ---------- - - aggregate : :class:`Aggregate` - Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, - ``"min"``, ``"max"``, ``"count"`` ). - - **Default value:** ``undefined`` (None) - - **See also:** `aggregate `__ - documentation. - bandPosition : float - Relative position on a band of a stacked, binned, time unit, or band scale. For - example, the marks will be positioned at the beginning of the band if set to ``0``, - and at the middle of the band if set to ``0.5``. - bin : anyOf(boolean, :class:`BinParams`, string, None) - A flag for binning a ``quantitative`` field, `an object defining binning parameters - `__, or indicating - that the data for ``x`` or ``y`` channel are binned before they are imported into - Vega-Lite ( ``"binned"`` ). - - - If ``true``, default `binning parameters - `__ will be applied. - - If ``"binned"``, this indicates that the data for the ``x`` (or ``y`` ) channel are - already binned. You can map the bin-start field to ``x`` (or ``y`` ) and the bin-end - field to ``x2`` (or ``y2`` ). The scale and axis will be formatted similar to - binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also - set the axis's `tickMinStep - `__ property. - - **Default value:** ``false`` - - **See also:** `bin `__ - documentation. - field : :class:`Field` - **Required.** A string defining the name of the field from which to pull a data - value or an object defining iterated values from the `repeat - `__ operator. - - **See also:** `field `__ - documentation. - - **Notes:** 1) Dots ( ``.`` ) and brackets ( ``[`` and ``]`` ) can be used to access - nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"`` ). If - field names contain dots or brackets but are not nested, you can use ``\\`` to - escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"`` ). See more details - about escaping in the `field documentation - `__. 2) ``field`` is not required - if ``aggregate`` is ``count``. - timeUnit : anyOf(:class:`TimeUnit`, :class:`TimeUnitParams`) - Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours`` ) for a temporal - field. or `a temporal field that gets casted as ordinal - `__. - - **Default value:** ``undefined`` (None) - - **See also:** `timeUnit `__ - documentation. - title : anyOf(:class:`Text`, None) - A title for the field. If ``null``, the title will be removed. - - **Default value:** derived from the field's name and transformation function ( - ``aggregate``, ``bin`` and ``timeUnit`` ). If the field has an aggregate function, - the function is displayed as part of the title (e.g., ``"Sum of Profit"`` ). If the - field is binned or has a time unit applied, the applied function is shown in - parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"`` ). - Otherwise, the title is simply the field name. - - **Notes** : - - 1) You can customize the default field title format by providing the `fieldTitle - `__ property in - the `config `__ or `fieldTitle - function via the compile function's options - `__. - - 2) If both field definition's ``title`` and axis, header, or legend ``title`` are - defined, axis/header/legend title will be used. - type : :class:`StandardType` - The type of measurement ( ``"quantitative"``, ``"temporal"``, ``"ordinal"``, or - ``"nominal"`` ) for the encoded field or constant value ( ``datum`` ). It can also - be a ``"geojson"`` type for encoding `'geoshape' - `__. - - Vega-Lite automatically infers data types in many cases as discussed below. However, - type is required for a field if: (1) the field is not nominal and the field encoding - has no specified ``aggregate`` (except ``argmin`` and ``argmax`` ), ``bin``, scale - type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal - scale for a field with ``bin`` or ``timeUnit``. - - **Default value:** - - 1) For a data ``field``, ``"nominal"`` is the default data type unless the field - encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or - ``timeUnit`` that satisfies the following criteria: - - - * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` - or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is - ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a - quantitative scale `__. - * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` - or (2) the specified scale type is a time or utc scale - * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort - order - `__, - (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding - channel is ``order``. - - 2) For a constant value in data domain ( ``datum`` ): - - - * ``"quantitative"`` if the datum is a number - * ``"nominal"`` if the datum is a string - * ``"temporal"`` if the datum is `a date time object - `__ - - **Note:** - - - * Data ``type`` describes the semantics of the data rather than the primitive data - types (number, string, etc.). The same primitive data type can have different - types of measurement. For example, numeric data can represent quantitative, - ordinal, or nominal data. - * Data values for a temporal field can be either a date-time string (e.g., - ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"`` ) or a - timestamp number (e.g., ``1552199579097`` ). - * When using with `bin `__, the - ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) - or `"ordinal" (for using an ordinal bin scale) - `__. - * When using with `timeUnit - `__, the ``type`` property - can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" - (for using an ordinal scale) - `__. - * When using with `aggregate - `__, the ``type`` property - refers to the post-aggregation data type. For example, we can calculate count - ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", - "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. - * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError`` ) do not have - ``type`` as they must have exactly the same type as their primary channels (e.g., - ``x``, ``y`` ). - - **See also:** `type `__ - documentation. - """ - _schema = {'$ref': '#/definitions/TypedFieldDef'} - - def __init__(self, aggregate=Undefined, bandPosition=Undefined, bin=Undefined, field=Undefined, - timeUnit=Undefined, title=Undefined, type=Undefined, **kwds): - super(TypedFieldDef, self).__init__(aggregate=aggregate, bandPosition=bandPosition, bin=bin, - field=field, timeUnit=timeUnit, title=title, type=type, - **kwds) - - -class URI(VegaLiteSchema): - """URI schema wrapper - - string - """ - _schema = {'$ref': '#/definitions/URI'} - - def __init__(self, *args): - super(URI, self).__init__(*args) - - -class UnitSpec(VegaLiteSchema): - """UnitSpec schema wrapper - - Mapping(required=[mark]) - Base interface for a unit (single-view) specification. - - Parameters - ---------- - - mark : :class:`AnyMark` - A string describing the mark type (one of ``"bar"``, ``"circle"``, ``"square"``, - ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"rule"``, ``"geoshape"``, and - ``"text"`` ) or a `mark definition object - `__. - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - encoding : :class:`Encoding` - A key-value mapping between encoding channels and definition of fields. - name : string - Name of the visualization for later reference. - params : List(:class:`SelectionParameter`) - An array of parameters that may either be simple variables, or more complex - selections that map user input to data queries. - projection : :class:`Projection` - An object defining properties of geographic projection, which will be applied to - ``shape`` path for ``"geoshape"`` marks and to ``latitude`` and ``"longitude"`` - channels for other marks. - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - """ - _schema = {'$ref': '#/definitions/UnitSpec'} - - def __init__(self, mark=Undefined, data=Undefined, description=Undefined, encoding=Undefined, - name=Undefined, params=Undefined, projection=Undefined, title=Undefined, - transform=Undefined, **kwds): - super(UnitSpec, self).__init__(mark=mark, data=data, description=description, encoding=encoding, - name=name, params=params, projection=projection, title=title, - transform=transform, **kwds) - - -class UnitSpecWithFrame(VegaLiteSchema): - """UnitSpecWithFrame schema wrapper - - Mapping(required=[mark]) - - Parameters - ---------- - - mark : :class:`AnyMark` - A string describing the mark type (one of ``"bar"``, ``"circle"``, ``"square"``, - ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"rule"``, ``"geoshape"``, and - ``"text"`` ) or a `mark definition object - `__. - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - encoding : :class:`Encoding` - A key-value mapping between encoding channels and definition of fields. - height : anyOf(float, string, :class:`Step`) - The height of a visualization. - - - * For a plot with a continuous y-field, height should be a number. - * For a plot with either a discrete y-field or no y-field, height can be either a - number indicating a fixed height or an object in the form of ``{step: number}`` - defining the height per discrete step. (No y-field is equivalent to having one - discrete step.) - * To enable responsive sizing on height, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousHeight`` for a plot with a - continuous y-field and ``config.view.discreteHeight`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - height of a single view and the ``"container"`` option cannot be used. - - **See also:** `height `__ - documentation. - name : string - Name of the visualization for later reference. - params : List(:class:`SelectionParameter`) - An array of parameters that may either be simple variables, or more complex - selections that map user input to data queries. - projection : :class:`Projection` - An object defining properties of geographic projection, which will be applied to - ``shape`` path for ``"geoshape"`` marks and to ``latitude`` and ``"longitude"`` - channels for other marks. - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - view : :class:`ViewBackground` - An object defining the view background's fill and stroke. - - **Default value:** none (transparent) - width : anyOf(float, string, :class:`Step`) - The width of a visualization. - - - * For a plot with a continuous x-field, width should be a number. - * For a plot with either a discrete x-field or no x-field, width can be either a - number indicating a fixed width or an object in the form of ``{step: number}`` - defining the width per discrete step. (No x-field is equivalent to having one - discrete step.) - * To enable responsive sizing on width, it should be set to ``"container"``. - - **Default value:** Based on ``config.view.continuousWidth`` for a plot with a - continuous x-field and ``config.view.discreteWidth`` otherwise. - - **Note:** For plots with `row and column channels - `__, this represents the - width of a single view and the ``"container"`` option cannot be used. - - **See also:** `width `__ - documentation. - """ - _schema = {'$ref': '#/definitions/UnitSpecWithFrame'} - - def __init__(self, mark=Undefined, data=Undefined, description=Undefined, encoding=Undefined, - height=Undefined, name=Undefined, params=Undefined, projection=Undefined, - title=Undefined, transform=Undefined, view=Undefined, width=Undefined, **kwds): - super(UnitSpecWithFrame, self).__init__(mark=mark, data=data, description=description, - encoding=encoding, height=height, name=name, - params=params, projection=projection, title=title, - transform=transform, view=view, width=width, **kwds) - - -class UrlData(DataSource): - """UrlData schema wrapper - - Mapping(required=[url]) - - Parameters - ---------- - - url : string - An URL from which to load the data set. Use the ``format.type`` property to ensure - the loaded data is correctly parsed. - format : :class:`DataFormat` - An object that specifies the format for parsing the data. - name : string - Provide a placeholder name and bind data at runtime. - """ - _schema = {'$ref': '#/definitions/UrlData'} - - def __init__(self, url=Undefined, format=Undefined, name=Undefined, **kwds): - super(UrlData, self).__init__(url=url, format=format, name=name, **kwds) - - -class UtcMultiTimeUnit(MultiTimeUnit): - """UtcMultiTimeUnit schema wrapper - - enum('utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', - 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', - 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', - 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', - 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', - 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', - 'utcweeksdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', - 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', - 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds') - """ - _schema = {'$ref': '#/definitions/UtcMultiTimeUnit'} - - def __init__(self, *args): - super(UtcMultiTimeUnit, self).__init__(*args) - - -class UtcSingleTimeUnit(SingleTimeUnit): - """UtcSingleTimeUnit schema wrapper - - enum('utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', - 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds') - """ - _schema = {'$ref': '#/definitions/UtcSingleTimeUnit'} - - def __init__(self, *args): - super(UtcSingleTimeUnit, self).__init__(*args) - - -class VConcatSpecGenericSpec(Spec, NonNormalizedSpec): - """VConcatSpecGenericSpec schema wrapper - - Mapping(required=[vconcat]) - Base interface for a vertical concatenation specification. - - Parameters - ---------- - - vconcat : List(:class:`Spec`) - A list of views to be concatenated and put into a column. - bounds : enum('full', 'flush') - The bounds calculation method to use for determining the extent of a sub-plot. One - of ``full`` (the default) or ``flush``. - - - * If set to ``full``, the entire calculated bounds (including axes, title, and - legend) will be used. - * If set to ``flush``, only the specified width and height values for the sub-view - will be used. The ``flush`` setting can be useful when attempting to place - sub-plots without axes or legends into a uniform grid structure. - - **Default value:** ``"full"`` - center : boolean - Boolean flag indicating if subviews should be centered relative to their respective - rows or columns. - - **Default value:** ``false`` - data : anyOf(:class:`Data`, None) - An object describing the data source. Set to ``null`` to ignore the parent's data - source. If no data is set, it is derived from the parent. - description : string - Description of this mark for commenting purpose. - name : string - Name of the visualization for later reference. - resolve : :class:`Resolve` - Scale, axis, and legend resolutions for view composition specifications. - spacing : float - The spacing in pixels between sub-views of the concat operator. - - **Default value** : ``10`` - title : anyOf(:class:`Text`, :class:`TitleParams`) - Title for the plot. - transform : List(:class:`Transform`) - An array of data transformations such as filter and new field calculation. - """ - _schema = {'$ref': '#/definitions/VConcatSpec'} - - def __init__(self, vconcat=Undefined, bounds=Undefined, center=Undefined, data=Undefined, - description=Undefined, name=Undefined, resolve=Undefined, spacing=Undefined, - title=Undefined, transform=Undefined, **kwds): - super(VConcatSpecGenericSpec, self).__init__(vconcat=vconcat, bounds=bounds, center=center, - data=data, description=description, name=name, - resolve=resolve, spacing=spacing, title=title, - transform=transform, **kwds) - - -class ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull(ColorDef, MarkPropDefGradientstringnull): - """ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalValueDefGradientstringnullExprRef`, List(:class:`ConditionalValueDefGradientstringnullExprRef`)) - A field definition or one or more value definition(s) with a parameter predicate. - value : anyOf(:class:`Gradient`, string, None, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ValueDefWithCondition'} - - def __init__(self, condition=Undefined, value=Undefined, **kwds): - super(ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull, self).__init__(condition=condition, - value=value, - **kwds) - - -class ValueDefWithConditionMarkPropFieldOrDatumDefTypeForShapestringnull(MarkPropDefstringnullTypeForShape, ShapeDef): - """ValueDefWithConditionMarkPropFieldOrDatumDefTypeForShapestringnull schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDefTypeForShape`, :class:`ConditionalValueDefstringnullExprRef`, List(:class:`ConditionalValueDefstringnullExprRef`)) - A field definition or one or more value definition(s) with a parameter predicate. - value : anyOf(string, None, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ValueDefWithCondition,(string|null)>'} - - def __init__(self, condition=Undefined, value=Undefined, **kwds): - super(ValueDefWithConditionMarkPropFieldOrDatumDefTypeForShapestringnull, self).__init__(condition=condition, - value=value, - **kwds) - - -class ValueDefWithConditionMarkPropFieldOrDatumDefnumber(MarkPropDefnumber, NumericMarkPropDef): - """ValueDefWithConditionMarkPropFieldOrDatumDefnumber schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalValueDefnumberExprRef`, List(:class:`ConditionalValueDefnumberExprRef`)) - A field definition or one or more value definition(s) with a parameter predicate. - value : anyOf(float, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ValueDefWithCondition'} - - def __init__(self, condition=Undefined, value=Undefined, **kwds): - super(ValueDefWithConditionMarkPropFieldOrDatumDefnumber, self).__init__(condition=condition, - value=value, **kwds) - - -class ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray(MarkPropDefnumberArray, NumericArrayMarkPropDef): - """ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalValueDefnumberArrayExprRef`, List(:class:`ConditionalValueDefnumberArrayExprRef`)) - A field definition or one or more value definition(s) with a parameter predicate. - value : anyOf(List(float), :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ValueDefWithCondition'} - - def __init__(self, condition=Undefined, value=Undefined, **kwds): - super(ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray, self).__init__(condition=condition, - value=value, - **kwds) - - -class ValueDefWithConditionMarkPropFieldOrDatumDefstringnull(VegaLiteSchema): - """ValueDefWithConditionMarkPropFieldOrDatumDefstringnull schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - condition : anyOf(:class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalValueDefstringnullExprRef`, List(:class:`ConditionalValueDefstringnullExprRef`)) - A field definition or one or more value definition(s) with a parameter predicate. - value : anyOf(string, None, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ValueDefWithCondition'} - - def __init__(self, condition=Undefined, value=Undefined, **kwds): - super(ValueDefWithConditionMarkPropFieldOrDatumDefstringnull, self).__init__(condition=condition, - value=value, **kwds) - - -class ValueDefWithConditionStringFieldDefText(TextDef): - """ValueDefWithConditionStringFieldDefText schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - condition : anyOf(:class:`ConditionalStringFieldDef`, :class:`ConditionalValueDefTextExprRef`, List(:class:`ConditionalValueDefTextExprRef`)) - A field definition or one or more value definition(s) with a parameter predicate. - value : anyOf(:class:`Text`, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ValueDefWithCondition'} - - def __init__(self, condition=Undefined, value=Undefined, **kwds): - super(ValueDefWithConditionStringFieldDefText, self).__init__(condition=condition, value=value, - **kwds) - - -class ValueDefnumber(OffsetDef): - """ValueDefnumber schema wrapper - - Mapping(required=[value]) - Definition object for a constant value (primitive value or gradient definition) of an - encoding channel. - - Parameters - ---------- - - value : float - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ValueDef'} - - def __init__(self, value=Undefined, **kwds): - super(ValueDefnumber, self).__init__(value=value, **kwds) - - -class ValueDefnumberwidthheightExprRef(VegaLiteSchema): - """ValueDefnumberwidthheightExprRef schema wrapper - - Mapping(required=[value]) - Definition object for a constant value (primitive value or gradient definition) of an - encoding channel. - - Parameters - ---------- - - value : anyOf(float, string, string, :class:`ExprRef`) - A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient - definition `__ for color, - values between ``0`` to ``1`` for opacity). - """ - _schema = {'$ref': '#/definitions/ValueDef<(number|"width"|"height"|ExprRef)>'} - - def __init__(self, value=Undefined, **kwds): - super(ValueDefnumberwidthheightExprRef, self).__init__(value=value, **kwds) - - -class VariableParameter(TopLevelParameter): - """VariableParameter schema wrapper - - Mapping(required=[name]) - - Parameters - ---------- - - name : :class:`ParameterName` - A unique name for the variable parameter. Parameter names should be valid JavaScript - identifiers: they should contain only alphanumeric characters (or "$", or "_") and - may not start with a digit. Reserved keywords that may not be used as parameter - names are "datum", "event", "item", and "parent". - bind : :class:`Binding` - Binds the parameter to an external input element such as a slider, selection list or - radio button group. - expr : :class:`Expr` - An expression for the value of the parameter. This expression may include other - parameters, in which case the parameter will automatically update in response to - upstream parameter changes. - value : Any - The `initial value `__ of the - parameter. - - **Default value:** ``undefined`` - """ - _schema = {'$ref': '#/definitions/VariableParameter'} - - def __init__(self, name=Undefined, bind=Undefined, expr=Undefined, value=Undefined, **kwds): - super(VariableParameter, self).__init__(name=name, bind=bind, expr=expr, value=value, **kwds) - - -class Vector10string(VegaLiteSchema): - """Vector10string schema wrapper - - List(string) - """ - _schema = {'$ref': '#/definitions/Vector10'} - - def __init__(self, *args): - super(Vector10string, self).__init__(*args) - - -class Vector12string(VegaLiteSchema): - """Vector12string schema wrapper - - List(string) - """ - _schema = {'$ref': '#/definitions/Vector12'} - - def __init__(self, *args): - super(Vector12string, self).__init__(*args) - - -class Vector2DateTime(SelectionInitInterval): - """Vector2DateTime schema wrapper - - List(:class:`DateTime`) - """ - _schema = {'$ref': '#/definitions/Vector2'} - - def __init__(self, *args): - super(Vector2DateTime, self).__init__(*args) - - -class Vector2Vector2number(VegaLiteSchema): - """Vector2Vector2number schema wrapper - - List(:class:`Vector2number`) - """ - _schema = {'$ref': '#/definitions/Vector2>'} - - def __init__(self, *args): - super(Vector2Vector2number, self).__init__(*args) - - -class Vector2boolean(SelectionInitInterval): - """Vector2boolean schema wrapper - - List(boolean) - """ - _schema = {'$ref': '#/definitions/Vector2'} - - def __init__(self, *args): - super(Vector2boolean, self).__init__(*args) - - -class Vector2number(SelectionInitInterval): - """Vector2number schema wrapper - - List(float) - """ - _schema = {'$ref': '#/definitions/Vector2'} - - def __init__(self, *args): - super(Vector2number, self).__init__(*args) - - -class Vector2string(SelectionInitInterval): - """Vector2string schema wrapper - - List(string) - """ - _schema = {'$ref': '#/definitions/Vector2'} - - def __init__(self, *args): - super(Vector2string, self).__init__(*args) - - -class Vector3number(VegaLiteSchema): - """Vector3number schema wrapper - - List(float) - """ - _schema = {'$ref': '#/definitions/Vector3'} - - def __init__(self, *args): - super(Vector3number, self).__init__(*args) - - -class Vector7string(VegaLiteSchema): - """Vector7string schema wrapper - - List(string) - """ - _schema = {'$ref': '#/definitions/Vector7'} - - def __init__(self, *args): - super(Vector7string, self).__init__(*args) - - -class ViewBackground(VegaLiteSchema): - """ViewBackground schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cursor : :class:`Cursor` - The mouse cursor used over the view. Any valid `CSS cursor type - `__ can be used. - fill : anyOf(:class:`Color`, None, :class:`ExprRef`) - The fill color. - - **Default value:** ``undefined`` - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - stroke : anyOf(:class:`Color`, None, :class:`ExprRef`) - The stroke color. - - **Default value:** ``"#ddd"`` - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - style : anyOf(string, List(string)) - A string or array of strings indicating the name of custom styles to apply to the - view background. A style is a named collection of mark property defaults defined - within the `style configuration - `__. If style is an - array, later styles will override earlier styles. - - **Default value:** ``"cell"`` **Note:** Any specified view background properties - will augment the default style. - """ - _schema = {'$ref': '#/definitions/ViewBackground'} - - def __init__(self, cornerRadius=Undefined, cursor=Undefined, fill=Undefined, fillOpacity=Undefined, - opacity=Undefined, stroke=Undefined, strokeCap=Undefined, strokeDash=Undefined, - strokeDashOffset=Undefined, strokeJoin=Undefined, strokeMiterLimit=Undefined, - strokeOpacity=Undefined, strokeWidth=Undefined, style=Undefined, **kwds): - super(ViewBackground, self).__init__(cornerRadius=cornerRadius, cursor=cursor, fill=fill, - fillOpacity=fillOpacity, opacity=opacity, stroke=stroke, - strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, - strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, - style=style, **kwds) - - -class ViewConfig(VegaLiteSchema): - """ViewConfig schema wrapper - - Mapping(required=[]) - - Parameters - ---------- - - clip : boolean - Whether the view should be clipped. - continuousHeight : float - The default height when the plot has a continuous y-field for x or latitude, or has - arc marks. - - **Default value:** ``200`` - continuousWidth : float - The default width when the plot has a continuous field for x or longitude, or has - arc marks. - - **Default value:** ``200`` - cornerRadius : anyOf(float, :class:`ExprRef`) - The radius in pixels of rounded rectangles or arcs' corners. - - **Default value:** ``0`` - cursor : :class:`Cursor` - The mouse cursor used over the view. Any valid `CSS cursor type - `__ can be used. - discreteHeight : anyOf(float, Mapping(required=[step])) - The default height when the plot has non arc marks and either a discrete y-field or - no y-field. The height can be either a number indicating a fixed height or an object - in the form of ``{step: number}`` defining the height per discrete step. - - **Default value:** a step size based on ``config.view.step``. - discreteWidth : anyOf(float, Mapping(required=[step])) - The default width when the plot has non-arc marks and either a discrete x-field or - no x-field. The width can be either a number indicating a fixed width or an object - in the form of ``{step: number}`` defining the width per discrete step. - - **Default value:** a step size based on ``config.view.step``. - fill : anyOf(:class:`Color`, None, :class:`ExprRef`) - The fill color. - - **Default value:** ``undefined`` - fillOpacity : anyOf(float, :class:`ExprRef`) - The fill opacity (value between [0,1]). - - **Default value:** ``1`` - opacity : anyOf(float, :class:`ExprRef`) - The overall opacity (value between [0,1]). - - **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, - ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. - step : float - Default step size for x-/y- discrete fields. - stroke : anyOf(:class:`Color`, None, :class:`ExprRef`) - The stroke color. - - **Default value:** ``"#ddd"`` - strokeCap : anyOf(:class:`StrokeCap`, :class:`ExprRef`) - The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or - ``"square"``. - - **Default value:** ``"butt"`` - strokeDash : anyOf(List(float), :class:`ExprRef`) - An array of alternating stroke, space lengths for creating dashed or dotted lines. - strokeDashOffset : anyOf(float, :class:`ExprRef`) - The offset (in pixels) into which to begin drawing with the stroke dash array. - strokeJoin : anyOf(:class:`StrokeJoin`, :class:`ExprRef`) - The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. - - **Default value:** ``"miter"`` - strokeMiterLimit : anyOf(float, :class:`ExprRef`) - The miter limit at which to bevel a line join. - strokeOpacity : anyOf(float, :class:`ExprRef`) - The stroke opacity (value between [0,1]). - - **Default value:** ``1`` - strokeWidth : anyOf(float, :class:`ExprRef`) - The stroke width, in pixels. - """ - _schema = {'$ref': '#/definitions/ViewConfig'} - - def __init__(self, clip=Undefined, continuousHeight=Undefined, continuousWidth=Undefined, - cornerRadius=Undefined, cursor=Undefined, discreteHeight=Undefined, - discreteWidth=Undefined, fill=Undefined, fillOpacity=Undefined, opacity=Undefined, - step=Undefined, stroke=Undefined, strokeCap=Undefined, strokeDash=Undefined, - strokeDashOffset=Undefined, strokeJoin=Undefined, strokeMiterLimit=Undefined, - strokeOpacity=Undefined, strokeWidth=Undefined, **kwds): - super(ViewConfig, self).__init__(clip=clip, continuousHeight=continuousHeight, - continuousWidth=continuousWidth, cornerRadius=cornerRadius, - cursor=cursor, discreteHeight=discreteHeight, - discreteWidth=discreteWidth, fill=fill, - fillOpacity=fillOpacity, opacity=opacity, step=step, - stroke=stroke, strokeCap=strokeCap, strokeDash=strokeDash, - strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, - strokeMiterLimit=strokeMiterLimit, strokeOpacity=strokeOpacity, - strokeWidth=strokeWidth, **kwds) - - -class WindowEventType(VegaLiteSchema): - """WindowEventType schema wrapper - - anyOf(:class:`EventType`, string) - """ - _schema = {'$ref': '#/definitions/WindowEventType'} - - def __init__(self, *args, **kwds): - super(WindowEventType, self).__init__(*args, **kwds) - - -class EventType(WindowEventType): - """EventType schema wrapper - - enum('click', 'dblclick', 'dragenter', 'dragleave', 'dragover', 'keydown', 'keypress', - 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'mousewheel', - 'timer', 'touchend', 'touchmove', 'touchstart', 'wheel') - """ - _schema = {'$ref': '#/definitions/EventType'} - - def __init__(self, *args): - super(EventType, self).__init__(*args) - - -class WindowFieldDef(VegaLiteSchema): - """WindowFieldDef schema wrapper - - Mapping(required=[op, as]) - - Parameters - ---------- - - op : anyOf(:class:`AggregateOp`, :class:`WindowOnlyOp`) - The window or aggregation operation to apply within a window (e.g., ``"rank"``, - ``"lead"``, ``"sum"``, ``"average"`` or ``"count"`` ). See the list of all supported - operations `here `__. - field : :class:`FieldName` - The data field for which to compute the aggregate or window function. This can be - omitted for window functions that do not operate over a field such as ``"count"``, - ``"rank"``, ``"dense_rank"``. - param : float - Parameter values for the window functions. Parameter values can be omitted for - operations that do not accept a parameter. - - See the list of all supported operations and their parameters `here - `__. - as : :class:`FieldName` - The output name for the window operation. - """ - _schema = {'$ref': '#/definitions/WindowFieldDef'} - - def __init__(self, op=Undefined, field=Undefined, param=Undefined, **kwds): - super(WindowFieldDef, self).__init__(op=op, field=field, param=param, **kwds) - - -class WindowOnlyOp(VegaLiteSchema): - """WindowOnlyOp schema wrapper - - enum('row_number', 'rank', 'dense_rank', 'percent_rank', 'cume_dist', 'ntile', 'lag', - 'lead', 'first_value', 'last_value', 'nth_value') - """ - _schema = {'$ref': '#/definitions/WindowOnlyOp'} - - def __init__(self, *args): - super(WindowOnlyOp, self).__init__(*args) - - -class WindowTransform(Transform): - """WindowTransform schema wrapper - - Mapping(required=[window]) - - Parameters - ---------- - - window : List(:class:`WindowFieldDef`) - The definition of the fields in the window, and what calculations to use. - frame : List(anyOf(None, float)) - A frame specification as a two-element array indicating how the sliding window - should proceed. The array entries should either be a number indicating the offset - from the current data object, or null to indicate unbounded rows preceding or - following the current data object. The default value is ``[null, 0]``, indicating - that the sliding window includes the current object and all preceding objects. The - value ``[-5, 5]`` indicates that the window should include five objects preceding - and five objects following the current object. Finally, ``[null, null]`` indicates - that the window frame should always include all data objects. If you this frame and - want to assign the same value to add objects, you can use the simpler `join - aggregate transform `__. - The only operators affected are the aggregation operations and the ``first_value``, - ``last_value``, and ``nth_value`` window operations. The other window operations are - not affected by this. - - **Default value:** : ``[null, 0]`` (includes the current object and all preceding - objects) - groupby : List(:class:`FieldName`) - The data fields for partitioning the data objects into separate windows. If - unspecified, all data points will be in a single window. - ignorePeers : boolean - Indicates if the sliding window frame should ignore peer values (data that are - considered identical by the sort criteria). The default is false, causing the window - frame to expand to include all peer values. If set to true, the window frame will be - defined by offset values only. This setting only affects those operations that - depend on the window frame, namely aggregation operations and the first_value, - last_value, and nth_value window operations. - - **Default value:** ``false`` - sort : List(:class:`SortField`) - A sort field definition for sorting data objects within a window. If two data - objects are considered equal by the comparator, they are considered "peer" values of - equal rank. If sort is not specified, the order is undefined: data objects are - processed in the order they are observed and none are considered peers (the - ignorePeers parameter is ignored and treated as if set to ``true`` ). - """ - _schema = {'$ref': '#/definitions/WindowTransform'} - - def __init__(self, window=Undefined, frame=Undefined, groupby=Undefined, ignorePeers=Undefined, - sort=Undefined, **kwds): - super(WindowTransform, self).__init__(window=window, frame=frame, groupby=groupby, - ignorePeers=ignorePeers, sort=sort, **kwds) - diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fastapi/middleware/__init__.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fastapi/middleware/__init__.py deleted file mode 100644 index 620296d5ad6ca2cc49eb5d0dc140bcbc3204e9b4..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/fastapi/middleware/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from starlette.middleware import Middleware as Middleware diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/markdown_it/common/html_re.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/markdown_it/common/html_re.py deleted file mode 100644 index f0c336d23816db1376d0c779fc3de718181e4c9f..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/markdown_it/common/html_re.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Regexps to match html elements -""" - -import re - -attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*" - -unquoted = "[^\"'=<>`\\x00-\\x20]+" -single_quoted = "'[^']*'" -double_quoted = '"[^"]*"' - -attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")" - -attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)" - -open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>" - -close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>" -comment = "|" -processing = "<[?][\\s\\S]*?[?]>" -declaration = "]*>" -cdata = "" - -HTML_TAG_RE = re.compile( - "^(?:" - + open_tag - + "|" - + close_tag - + "|" - + comment - + "|" - + processing - + "|" - + declaration - + "|" - + cdata - + ")" -) -HTML_OPEN_CLOSE_TAG_STR = "^(?:" + open_tag + "|" + close_tag + ")" -HTML_OPEN_CLOSE_TAG_RE = re.compile(HTML_OPEN_CLOSE_TAG_STR) diff --git a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/matplotlib/_enums.py b/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/matplotlib/_enums.py deleted file mode 100644 index c8c50f7c3028ee70aff2ee3073d7dad3e5260ec5..0000000000000000000000000000000000000000 --- a/spaces/dcarpintero/nlp-summarizer-pegasus/.venv/lib/python3.9/site-packages/matplotlib/_enums.py +++ /dev/null @@ -1,185 +0,0 @@ -""" -Enums representing sets of strings that Matplotlib uses as input parameters. - -Matplotlib often uses simple data types like strings or tuples to define a -concept; e.g. the line capstyle can be specified as one of 'butt', 'round', -or 'projecting'. The classes in this module are used internally and serve to -document these concepts formally. - -As an end-user you will not use these classes directly, but only the values -they define. -""" - -from enum import Enum, auto -from matplotlib import _docstring - - -class _AutoStringNameEnum(Enum): - """Automate the ``name = 'name'`` part of making a (str, Enum).""" - - def _generate_next_value_(name, start, count, last_values): - return name - - def __hash__(self): - return str(self).__hash__() - - -class JoinStyle(str, _AutoStringNameEnum): - """ - Define how the connection between two line segments is drawn. - - For a visual impression of each *JoinStyle*, `view these docs online - `, or run `JoinStyle.demo`. - - Lines in Matplotlib are typically defined by a 1D `~.path.Path` and a - finite ``linewidth``, where the underlying 1D `~.path.Path` represents the - center of the stroked line. - - By default, `~.backend_bases.GraphicsContextBase` defines the boundaries of - a stroked line to simply be every point within some radius, - ``linewidth/2``, away from any point of the center line. However, this - results in corners appearing "rounded", which may not be the desired - behavior if you are drawing, for example, a polygon or pointed star. - - **Supported values:** - - .. rst-class:: value-list - - 'miter' - the "arrow-tip" style. Each boundary of the filled-in area will - extend in a straight line parallel to the tangent vector of the - centerline at the point it meets the corner, until they meet in a - sharp point. - 'round' - stokes every point within a radius of ``linewidth/2`` of the center - lines. - 'bevel' - the "squared-off" style. It can be thought of as a rounded corner - where the "circular" part of the corner has been cut off. - - .. note:: - - Very long miter tips are cut off (to form a *bevel*) after a - backend-dependent limit called the "miter limit", which specifies the - maximum allowed ratio of miter length to line width. For example, the - PDF backend uses the default value of 10 specified by the PDF standard, - while the SVG backend does not even specify the miter limit, resulting - in a default value of 4 per the SVG specification. Matplotlib does not - currently allow the user to adjust this parameter. - - A more detailed description of the effect of a miter limit can be found - in the `Mozilla Developer Docs - `_ - - .. plot:: - :alt: Demo of possible JoinStyle's - - from matplotlib._enums import JoinStyle - JoinStyle.demo() - - """ - - miter = auto() - round = auto() - bevel = auto() - - @staticmethod - def demo(): - """Demonstrate how each JoinStyle looks for various join angles.""" - import numpy as np - import matplotlib.pyplot as plt - - def plot_angle(ax, x, y, angle, style): - phi = np.radians(angle) - xx = [x + .5, x, x + .5*np.cos(phi)] - yy = [y, y, y + .5*np.sin(phi)] - ax.plot(xx, yy, lw=12, color='tab:blue', solid_joinstyle=style) - ax.plot(xx, yy, lw=1, color='black') - ax.plot(xx[1], yy[1], 'o', color='tab:red', markersize=3) - - fig, ax = plt.subplots(figsize=(5, 4), constrained_layout=True) - ax.set_title('Join style') - for x, style in enumerate(['miter', 'round', 'bevel']): - ax.text(x, 5, style) - for y, angle in enumerate([20, 45, 60, 90, 120]): - plot_angle(ax, x, y, angle, style) - if x == 0: - ax.text(-1.3, y, f'{angle} degrees') - ax.set_xlim(-1.5, 2.75) - ax.set_ylim(-.5, 5.5) - ax.set_axis_off() - fig.show() - - -JoinStyle.input_description = "{" \ - + ", ".join([f"'{js.name}'" for js in JoinStyle]) \ - + "}" - - -class CapStyle(str, _AutoStringNameEnum): - r""" - Define how the two endpoints (caps) of an unclosed line are drawn. - - How to draw the start and end points of lines that represent a closed curve - (i.e. that end in a `~.path.Path.CLOSEPOLY`) is controlled by the line's - `JoinStyle`. For all other lines, how the start and end points are drawn is - controlled by the *CapStyle*. - - For a visual impression of each *CapStyle*, `view these docs online - ` or run `CapStyle.demo`. - - By default, `~.backend_bases.GraphicsContextBase` draws a stroked line as - squared off at its endpoints. - - **Supported values:** - - .. rst-class:: value-list - - 'butt' - the line is squared off at its endpoint. - 'projecting' - the line is squared off as in *butt*, but the filled in area - extends beyond the endpoint a distance of ``linewidth/2``. - 'round' - like *butt*, but a semicircular cap is added to the end of the - line, of radius ``linewidth/2``. - - .. plot:: - :alt: Demo of possible CapStyle's - - from matplotlib._enums import CapStyle - CapStyle.demo() - - """ - butt = auto() - projecting = auto() - round = auto() - - @staticmethod - def demo(): - """Demonstrate how each CapStyle looks for a thick line segment.""" - import matplotlib.pyplot as plt - - fig = plt.figure(figsize=(4, 1.2)) - ax = fig.add_axes([0, 0, 1, 0.8]) - ax.set_title('Cap style') - - for x, style in enumerate(['butt', 'round', 'projecting']): - ax.text(x+0.25, 0.85, style, ha='center') - xx = [x, x+0.5] - yy = [0, 0] - ax.plot(xx, yy, lw=12, color='tab:blue', solid_capstyle=style) - ax.plot(xx, yy, lw=1, color='black') - ax.plot(xx, yy, 'o', color='tab:red', markersize=3) - - ax.set_ylim(-.5, 1.5) - ax.set_axis_off() - fig.show() - - -CapStyle.input_description = "{" \ - + ", ".join([f"'{cs.name}'" for cs in CapStyle]) \ - + "}" - -_docstring.interpd.update({'JoinStyle': JoinStyle.input_description, - 'CapStyle': CapStyle.input_description}) diff --git a/spaces/deepkyu/multilingual-font-style-transfer/trainer.py b/spaces/deepkyu/multilingual-font-style-transfer/trainer.py deleted file mode 100644 index cc7062ce9d27f9777847732ffeff44abb5f6c426..0000000000000000000000000000000000000000 --- a/spaces/deepkyu/multilingual-font-style-transfer/trainer.py +++ /dev/null @@ -1,88 +0,0 @@ -import argparse -import glob -from pathlib import Path - -from omegaconf import OmegaConf -import pytorch_lightning as pl -from pytorch_lightning.callbacks import ModelCheckpoint -from pytorch_lightning.loggers import TensorBoardLogger - -from lightning import FontLightningModule -from utils import save_files - - -def load_configuration(path_config): - setting = OmegaConf.load(path_config) - - # load hyperparameter - hp = OmegaConf.load(setting.config.dataset) - hp = OmegaConf.merge(hp, OmegaConf.load(setting.config.model)) - hp = OmegaConf.merge(hp, OmegaConf.load(setting.config.logging)) - - # with lightning setting - if hasattr(setting.config, 'lightning'): - pl_config = OmegaConf.load(setting.config.lightning) - if hasattr(pl_config, 'pl_config'): - return hp, pl_config.pl_config - return hp, pl_config - - # without lightning setting - return hp - - -def parse_args(): - parser = argparse.ArgumentParser(description='Code to train font style transfer') - - parser.add_argument("--config", type=str, default="./config/setting.yaml", - help="Config file for training") - parser.add_argument('-g', '--gpus', type=str, default='0,1', - help="Number of gpus to use (e.g. '0,1,2,3'). Will use all if not given.") - parser.add_argument('-p', '--resume_checkpoint_path', type=str, default=None, - help="path of checkpoint for resuming") - - args = parser.parse_args() - return args - - -def main(): - args = parse_args() - hp, pl_config = load_configuration(args.config) - - logging_dir = Path(hp.logging.log_dir) - - # call lightning module - font_pl = FontLightningModule(hp) - - # set logging - hp.logging['log_dir'] = logging_dir / 'tensorboard' - savefiles = [] - for reg in hp.logging.savefiles: - savefiles += glob.glob(reg) - hp.logging['log_dir'].mkdir(exist_ok=True) - save_files(str(logging_dir), savefiles) - - # set tensorboard logger - logger = TensorBoardLogger(str(logging_dir), name=str(hp.logging.seed)) - - # set checkpoing callback - weights_save_path = logging_dir / 'checkpoint' / str(hp.logging.seed) - weights_save_path.mkdir(exist_ok=True) - checkpoint_callback = ModelCheckpoint( - dirpath=str(weights_save_path), - **pl_config.checkpoint.callback - ) - - # set lightning trainer - trainer = pl.Trainer( - logger=logger, - gpus=-1 if args.gpus is None else args.gpus, - callbacks=[checkpoint_callback], - **pl_config.trainer - ) - - # let's train - trainer.fit(font_pl) - - -if __name__ == "__main__": - main() diff --git a/spaces/deepskyreal/ai-mixer-hotchpotch/sad_talker/src/face3d/models/arcface_torch/docs/speed_benchmark.md b/spaces/deepskyreal/ai-mixer-hotchpotch/sad_talker/src/face3d/models/arcface_torch/docs/speed_benchmark.md deleted file mode 100644 index 055aee0defe2c43a523ced48260242f0f99b7cea..0000000000000000000000000000000000000000 --- a/spaces/deepskyreal/ai-mixer-hotchpotch/sad_talker/src/face3d/models/arcface_torch/docs/speed_benchmark.md +++ /dev/null @@ -1,93 +0,0 @@ -## Test Training Speed - -- Test Commands - -You need to use the following two commands to test the Partial FC training performance. -The number of identites is **3 millions** (synthetic data), turn mixed precision training on, backbone is resnet50, -batch size is 1024. -```shell -# Model Parallel -python -m torch.distributed.launch --nproc_per_node=8 --nnodes=1 --node_rank=0 --master_addr="127.0.0.1" --master_port=1234 train.py configs/3millions -# Partial FC 0.1 -python -m torch.distributed.launch --nproc_per_node=8 --nnodes=1 --node_rank=0 --master_addr="127.0.0.1" --master_port=1234 train.py configs/3millions_pfc -``` - -- GPU Memory - -``` -# (Model Parallel) gpustat -i -[0] Tesla V100-SXM2-32GB | 64'C, 94 % | 30338 / 32510 MB -[1] Tesla V100-SXM2-32GB | 60'C, 99 % | 28876 / 32510 MB -[2] Tesla V100-SXM2-32GB | 60'C, 99 % | 28872 / 32510 MB -[3] Tesla V100-SXM2-32GB | 69'C, 99 % | 28872 / 32510 MB -[4] Tesla V100-SXM2-32GB | 66'C, 99 % | 28888 / 32510 MB -[5] Tesla V100-SXM2-32GB | 60'C, 99 % | 28932 / 32510 MB -[6] Tesla V100-SXM2-32GB | 68'C, 100 % | 28916 / 32510 MB -[7] Tesla V100-SXM2-32GB | 65'C, 99 % | 28860 / 32510 MB - -# (Partial FC 0.1) gpustat -i -[0] Tesla V100-SXM2-32GB | 60'C, 95 % | 10488 / 32510 MB │······················· -[1] Tesla V100-SXM2-32GB | 60'C, 97 % | 10344 / 32510 MB │······················· -[2] Tesla V100-SXM2-32GB | 61'C, 95 % | 10340 / 32510 MB │······················· -[3] Tesla V100-SXM2-32GB | 66'C, 95 % | 10340 / 32510 MB │······················· -[4] Tesla V100-SXM2-32GB | 65'C, 94 % | 10356 / 32510 MB │······················· -[5] Tesla V100-SXM2-32GB | 61'C, 95 % | 10400 / 32510 MB │······················· -[6] Tesla V100-SXM2-32GB | 68'C, 96 % | 10384 / 32510 MB │······················· -[7] Tesla V100-SXM2-32GB | 64'C, 95 % | 10328 / 32510 MB │······················· -``` - -- Training Speed - -```python -# (Model Parallel) trainging.log -Training: Speed 2271.33 samples/sec Loss 1.1624 LearningRate 0.2000 Epoch: 0 Global Step: 100 -Training: Speed 2269.94 samples/sec Loss 0.0000 LearningRate 0.2000 Epoch: 0 Global Step: 150 -Training: Speed 2272.67 samples/sec Loss 0.0000 LearningRate 0.2000 Epoch: 0 Global Step: 200 -Training: Speed 2266.55 samples/sec Loss 0.0000 LearningRate 0.2000 Epoch: 0 Global Step: 250 -Training: Speed 2272.54 samples/sec Loss 0.0000 LearningRate 0.2000 Epoch: 0 Global Step: 300 - -# (Partial FC 0.1) trainging.log -Training: Speed 5299.56 samples/sec Loss 1.0965 LearningRate 0.2000 Epoch: 0 Global Step: 100 -Training: Speed 5296.37 samples/sec Loss 0.0000 LearningRate 0.2000 Epoch: 0 Global Step: 150 -Training: Speed 5304.37 samples/sec Loss 0.0000 LearningRate 0.2000 Epoch: 0 Global Step: 200 -Training: Speed 5274.43 samples/sec Loss 0.0000 LearningRate 0.2000 Epoch: 0 Global Step: 250 -Training: Speed 5300.10 samples/sec Loss 0.0000 LearningRate 0.2000 Epoch: 0 Global Step: 300 -``` - -In this test case, Partial FC 0.1 only use1 1/3 of the GPU memory of the model parallel, -and the training speed is 2.5 times faster than the model parallel. - - -## Speed Benchmark - -1. Training speed of different parallel methods (samples/second), Tesla V100 32GB * 8. (Larger is better) - -| Number of Identities in Dataset | Data Parallel | Model Parallel | Partial FC 0.1 | -| :--- | :--- | :--- | :--- | -|125000 | 4681 | 4824 | 5004 | -|250000 | 4047 | 4521 | 4976 | -|500000 | 3087 | 4013 | 4900 | -|1000000 | 2090 | 3449 | 4803 | -|1400000 | 1672 | 3043 | 4738 | -|2000000 | - | 2593 | 4626 | -|4000000 | - | 1748 | 4208 | -|5500000 | - | 1389 | 3975 | -|8000000 | - | - | 3565 | -|16000000 | - | - | 2679 | -|29000000 | - | - | 1855 | - -2. GPU memory cost of different parallel methods (GB per GPU), Tesla V100 32GB * 8. (Smaller is better) - -| Number of Identities in Dataset | Data Parallel | Model Parallel | Partial FC 0.1 | -| :--- | :--- | :--- | :--- | -|125000 | 7358 | 5306 | 4868 | -|250000 | 9940 | 5826 | 5004 | -|500000 | 14220 | 7114 | 5202 | -|1000000 | 23708 | 9966 | 5620 | -|1400000 | 32252 | 11178 | 6056 | -|2000000 | - | 13978 | 6472 | -|4000000 | - | 23238 | 8284 | -|5500000 | - | 32188 | 9854 | -|8000000 | - | - | 12310 | -|16000000 | - | - | 19950 | -|29000000 | - | - | 32324 | diff --git a/spaces/deepwisdom/MetaGPT/metagpt/prompts/generate_skill.md b/spaces/deepwisdom/MetaGPT/metagpt/prompts/generate_skill.md deleted file mode 100644 index fd950c1439866572b5b65b68399f8e06bde18783..0000000000000000000000000000000000000000 --- a/spaces/deepwisdom/MetaGPT/metagpt/prompts/generate_skill.md +++ /dev/null @@ -1,76 +0,0 @@ -你是一个富有帮助的助理,可以帮助撰写、抽象、注释、摘要Python代码 - -1. 不要提到类/函数名 -2. 不要提到除了系统库与公共库以外的类/函数 -3. 试着将类/函数总结为不超过6句话 -4. 你的回答应该是一行文本 - -举例,如果上下文是: - -```python -from typing import Optional -from abc import ABC -from metagpt.llm import LLM # 大语言模型,类似GPT - -class Action(ABC): - def __init__(self, name='', context=None, llm: LLM = LLM()): - self.name = name - self.llm = llm - self.context = context - self.prefix = "" - self.desc = "" - - def set_prefix(self, prefix): - """设置前缀以供后续使用""" - self.prefix = prefix - - async def _aask(self, prompt: str, system_msgs: Optional[list[str]] = None): - """加上默认的prefix来使用prompt""" - if not system_msgs: - system_msgs = [] - system_msgs.append(self.prefix) - return await self.llm.aask(prompt, system_msgs) - - async def run(self, *args, **kwargs): - """运行动作""" - raise NotImplementedError("The run method should be implemented in a subclass.") - -PROMPT_TEMPLATE = """ -# 需求 -{requirements} - -# PRD -根据需求创建一个产品需求文档(PRD),填补以下空缺 - -产品/功能介绍: - -目标: - -用户和使用场景: - -需求: - -约束与限制: - -性能指标: - -""" - - -class WritePRD(Action): - def __init__(self, name="", context=None, llm=None): - super().__init__(name, context, llm) - - async def run(self, requirements, *args, **kwargs): - prompt = PROMPT_TEMPLATE.format(requirements=requirements) - prd = await self._aask(prompt) - return prd -``` - - -主类/函数是 `WritePRD`。 - -那么你应该写: - -这个类用来根据输入需求生成PRD。首先注意到有一个提示词模板,其中有产品、功能、目标、用户和使用场景、需求、约束与限制、性能指标,这个模板会以输入需求填充,然后调用接口询问大语言模型,让大语言模型返回具体的PRD。 - diff --git a/spaces/dengmouren/minlik-chinese-alpaca-pro-33b-merged/README.md b/spaces/dengmouren/minlik-chinese-alpaca-pro-33b-merged/README.md deleted file mode 100644 index 4520ec156cd1e04dafa9bfc0929cafde94db21a1..0000000000000000000000000000000000000000 --- a/spaces/dengmouren/minlik-chinese-alpaca-pro-33b-merged/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Minlik Chinese Alpaca Pro 33b Merged -emoji: 🐢 -colorFrom: green -colorTo: indigo -sdk: gradio -sdk_version: 3.39.0 -app_file: app.py -pinned: false -license: llama2 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/descript/vampnet/vampnet/modules/layers.py b/spaces/descript/vampnet/vampnet/modules/layers.py deleted file mode 100644 index 0c7df97be3b1726ac210da762c83a25dbd3434c7..0000000000000000000000000000000000000000 --- a/spaces/descript/vampnet/vampnet/modules/layers.py +++ /dev/null @@ -1,164 +0,0 @@ -import time -from typing import Optional -from typing import Tuple - -import torch -import torch.nn as nn -import torch.nn.functional as F -from einops import rearrange -from torch.nn.utils import weight_norm - -# Scripting this brings model speed up 1.4x -@torch.jit.script -def snake(x, alpha): - shape = x.shape - x = x.reshape(shape[0], shape[1], -1) - x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2) - x = x.reshape(shape) - return x - - -class Snake1d(nn.Module): - def __init__(self, channels): - super().__init__() - self.alpha = nn.Parameter(torch.ones(1, channels, 1)) - - def forward(self, x): - return snake(x, self.alpha) - - -def num_params(model): - return sum(p.numel() for p in model.parameters() if p.requires_grad) - - -def recurse_children(module, fn): - for child in module.children(): - if isinstance(child, nn.ModuleList): - for c in child: - yield recurse_children(c, fn) - if isinstance(child, nn.ModuleDict): - for c in child.values(): - yield recurse_children(c, fn) - - yield recurse_children(child, fn) - yield fn(child) - - -def WNConv1d(*args, **kwargs): - return weight_norm(nn.Conv1d(*args, **kwargs)) - - -def WNConvTranspose1d(*args, **kwargs): - return weight_norm(nn.ConvTranspose1d(*args, **kwargs)) - - -class SequentialWithFiLM(nn.Module): - """ - handy wrapper for nn.Sequential that allows FiLM layers to be - inserted in between other layers. - """ - - def __init__(self, *layers): - super().__init__() - self.layers = nn.ModuleList(layers) - - @staticmethod - def has_film(module): - mod_has_film = any( - [res for res in recurse_children(module, lambda c: isinstance(c, FiLM))] - ) - return mod_has_film - - def forward(self, x, cond): - for layer in self.layers: - if self.has_film(layer): - x = layer(x, cond) - else: - x = layer(x) - return x - - -class FiLM(nn.Module): - def __init__(self, input_dim: int, output_dim: int): - super().__init__() - - self.input_dim = input_dim - self.output_dim = output_dim - - if input_dim > 0: - self.beta = nn.Linear(input_dim, output_dim) - self.gamma = nn.Linear(input_dim, output_dim) - - def forward(self, x, r): - if self.input_dim == 0: - return x - else: - beta, gamma = self.beta(r), self.gamma(r) - beta, gamma = ( - beta.view(x.size(0), self.output_dim, 1), - gamma.view(x.size(0), self.output_dim, 1), - ) - x = x * (gamma + 1) + beta - return x - - -class CodebookEmbedding(nn.Module): - def __init__( - self, - vocab_size: int, - latent_dim: int, - n_codebooks: int, - emb_dim: int, - special_tokens: Optional[Tuple[str]] = None, - ): - super().__init__() - self.n_codebooks = n_codebooks - self.emb_dim = emb_dim - self.latent_dim = latent_dim - self.vocab_size = vocab_size - - if special_tokens is not None: - for tkn in special_tokens: - self.special = nn.ParameterDict( - { - tkn: nn.Parameter(torch.randn(n_codebooks, self.latent_dim)) - for tkn in special_tokens - } - ) - self.special_idxs = { - tkn: i + vocab_size for i, tkn in enumerate(special_tokens) - } - - self.out_proj = nn.Conv1d(n_codebooks * self.latent_dim, self.emb_dim, 1) - - def from_codes(self, codes: torch.Tensor, codec): - """ - get a sequence of continuous embeddings from a sequence of discrete codes. - unlike it's counterpart in the original VQ-VAE, this function adds for any special tokens - necessary for the language model, like . - """ - n_codebooks = codes.shape[1] - latent = [] - for i in range(n_codebooks): - c = codes[:, i, :] - - lookup_table = codec.quantizer.quantizers[i].codebook.weight - if hasattr(self, "special"): - special_lookup = torch.cat( - [self.special[tkn][i : i + 1] for tkn in self.special], dim=0 - ) - lookup_table = torch.cat([lookup_table, special_lookup], dim=0) - - l = F.embedding(c, lookup_table).transpose(1, 2) - latent.append(l) - - latent = torch.cat(latent, dim=1) - return latent - - def forward(self, latents: torch.Tensor): - """ - project a sequence of latents to a sequence of embeddings - """ - x = self.out_proj(latents) - return x - diff --git a/spaces/dgnk007/dgnk007-heat/app.py b/spaces/dgnk007/dgnk007-heat/app.py deleted file mode 100644 index d6d82d78db2d361164064631f4c5ec3cfa7fb0e8..0000000000000000000000000000000000000000 --- a/spaces/dgnk007/dgnk007-heat/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/dgnk007/heat",api_key='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',share=True).launch() \ No newline at end of file diff --git a/spaces/diacanFperku/AutoGPT/DJSoft-RadioBOSS-Advanced-V5331-Serial-Key-Keygen.md b/spaces/diacanFperku/AutoGPT/DJSoft-RadioBOSS-Advanced-V5331-Serial-Key-Keygen.md deleted file mode 100644 index 5c055e848652a379f0d6d62577abf7e4629f3b42..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/DJSoft-RadioBOSS-Advanced-V5331-Serial-Key-Keygen.md +++ /dev/null @@ -1,77 +0,0 @@ -## DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen - - - -**Download File ->>> [https://conttooperting.blogspot.com/?l=2twNTF](https://conttooperting.blogspot.com/?l=2twNTF)** - - - -# DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen - - - -If you are looking for a powerful and reliable software to manage your radio station, DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen is the perfect choice for you. This software allows you to create and schedule playlists, broadcast live or recorded audio, insert ads and jingles, apply effects and filters, and much more. With DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen, you can turn your computer into a professional radio station with ease. - - - -DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen is the latest version of the software that comes with many new features and improvements. Some of the highlights include: - - - -- Improved support for streaming formats such as AAC, OGG, OPUS, FLAC, etc. - -- Added support for Icecast 2.4.x and Shoutcast 2.x servers. - -- Added support for remote control via web interface or API. - -- Added support for automatic silence detection and removal. - -- Added support for crossfade settings for each track or playlist. - -- Added support for custom tags and metadata. - -- Added support for multiple sound cards and devices. - -- Fixed various bugs and errors. - - - -To use DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen, you need to download the software from the official website and install it on your computer. Then, you need to use the serial key provided in the keygen file to activate the software. After that, you can enjoy all the features and benefits of DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen without any limitations. - - - -DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen is a must-have software for anyone who wants to run a successful radio station with minimal effort and cost. It is easy to use, flexible, and reliable. It can handle any type of audio content and format, and it can work with any type of broadcasting server or device. It can also automate your radio station operations and save you time and money. - - - -Don't miss this opportunity to get DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen for free and start your own radio station today! - - - -How to use DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen? - - - -Using DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen is very simple and intuitive. Here are the basic steps to get started: - - - -1. Download and install DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen from the link below. - -2. Run the keygen file and generate a serial key. - -3. Launch the software and enter the serial key when prompted. - -4. Create a new playlist or open an existing one. - -5. Add tracks, ads, jingles, effects, etc. to your playlist. - -6. Configure the broadcasting settings and choose your streaming server or device. - -7. Start the broadcasting and enjoy your radio station. - - - -You can also use the software to record your audio, edit your tracks, schedule your playlists, monitor your listeners, and more. For more detailed instructions and tutorials, you can check the help file or the online documentation of DJSoft RadioBOSS Advanced v5.3.3.1 Serial Key keygen. - - dfd1c89656 \ No newline at end of file diff --git a/spaces/digitalxingtong/Azuma-Bert-VITS2/start.bat b/spaces/digitalxingtong/Azuma-Bert-VITS2/start.bat deleted file mode 100644 index 418d21233dbf720b0dd09821904d9d6a31b123a2..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Azuma-Bert-VITS2/start.bat +++ /dev/null @@ -1,2 +0,0 @@ -set PYTHON=venv\python.exe -start cmd /k "set PYTHON=%PYTHON%" \ No newline at end of file diff --git a/spaces/digitalxingtong/Eileen-Bert-Vits2/text/english.py b/spaces/digitalxingtong/Eileen-Bert-Vits2/text/english.py deleted file mode 100644 index 781d0a56cef71f66fc67db51d76538be90d3ddd2..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Eileen-Bert-Vits2/text/english.py +++ /dev/null @@ -1,138 +0,0 @@ -import pickle -import os -import re -from g2p_en import G2p -from string import punctuation - -from text import symbols - -current_file_path = os.path.dirname(__file__) -CMU_DICT_PATH = os.path.join(current_file_path, 'cmudict.rep') -CACHE_PATH = os.path.join(current_file_path, 'cmudict_cache.pickle') -_g2p = G2p() - -arpa = {'AH0', 'S', 'AH1', 'EY2', 'AE2', 'EH0', 'OW2', 'UH0', 'NG', 'B', 'G', 'AY0', 'M', 'AA0', 'F', 'AO0', 'ER2', 'UH1', 'IY1', 'AH2', 'DH', 'IY0', 'EY1', 'IH0', 'K', 'N', 'W', 'IY2', 'T', 'AA1', 'ER1', 'EH2', 'OY0', 'UH2', 'UW1', 'Z', 'AW2', 'AW1', 'V', 'UW2', 'AA2', 'ER', 'AW0', 'UW0', 'R', 'OW1', 'EH1', 'ZH', 'AE0', 'IH2', 'IH', 'Y', 'JH', 'P', 'AY1', 'EY0', 'OY2', 'TH', 'HH', 'D', 'ER0', 'CH', 'AO1', 'AE1', 'AO2', 'OY1', 'AY2', 'IH1', 'OW0', 'L', 'SH'} - - -def post_replace_ph(ph): - rep_map = { - ':': ',', - ';': ',', - ',': ',', - '。': '.', - '!': '!', - '?': '?', - '\n': '.', - "·": ",", - '、': ",", - '...': '…', - 'v': "V" - } - if ph in rep_map.keys(): - ph = rep_map[ph] - if ph in symbols: - return ph - if ph not in symbols: - ph = 'UNK' - return ph - -def read_dict(): - g2p_dict = {} - start_line = 49 - with open(CMU_DICT_PATH) as f: - line = f.readline() - line_index = 1 - while line: - if line_index >= start_line: - line = line.strip() - word_split = line.split(' ') - word = word_split[0] - - syllable_split = word_split[1].split(' - ') - g2p_dict[word] = [] - for syllable in syllable_split: - phone_split = syllable.split(' ') - g2p_dict[word].append(phone_split) - - line_index = line_index + 1 - line = f.readline() - - return g2p_dict - - -def cache_dict(g2p_dict, file_path): - with open(file_path, 'wb') as pickle_file: - pickle.dump(g2p_dict, pickle_file) - - -def get_dict(): - if os.path.exists(CACHE_PATH): - with open(CACHE_PATH, 'rb') as pickle_file: - g2p_dict = pickle.load(pickle_file) - else: - g2p_dict = read_dict() - cache_dict(g2p_dict, CACHE_PATH) - - return g2p_dict - -eng_dict = get_dict() - -def refine_ph(phn): - tone = 0 - if re.search(r'\d$', phn): - tone = int(phn[-1]) + 1 - phn = phn[:-1] - return phn.lower(), tone - -def refine_syllables(syllables): - tones = [] - phonemes = [] - for phn_list in syllables: - for i in range(len(phn_list)): - phn = phn_list[i] - phn, tone = refine_ph(phn) - phonemes.append(phn) - tones.append(tone) - return phonemes, tones - - -def text_normalize(text): - # todo: eng text normalize - return text - -def g2p(text): - - phones = [] - tones = [] - words = re.split(r"([,;.\-\?\!\s+])", text) - for w in words: - if w.upper() in eng_dict: - phns, tns = refine_syllables(eng_dict[w.upper()]) - phones += phns - tones += tns - else: - phone_list = list(filter(lambda p: p != " ", _g2p(w))) - for ph in phone_list: - if ph in arpa: - ph, tn = refine_ph(ph) - phones.append(ph) - tones.append(tn) - else: - phones.append(ph) - tones.append(0) - # todo: implement word2ph - word2ph = [1 for i in phones] - - phones = [post_replace_ph(i) for i in phones] - return phones, tones, word2ph - -if __name__ == "__main__": - # print(get_dict()) - # print(eng_word_to_phoneme("hello")) - print(g2p("In this paper, we propose 1 DSPGAN, a GAN-based universal vocoder.")) - # all_phones = set() - # for k, syllables in eng_dict.items(): - # for group in syllables: - # for ph in group: - # all_phones.add(ph) - # print(all_phones) \ No newline at end of file diff --git a/spaces/digitalxingtong/Taffy-Bert-VITS2/text/symbols.py b/spaces/digitalxingtong/Taffy-Bert-VITS2/text/symbols.py deleted file mode 100644 index 9dfae4e633829f20c4fd767b1c7a9198911ed801..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Taffy-Bert-VITS2/text/symbols.py +++ /dev/null @@ -1,51 +0,0 @@ -punctuation = ['!', '?', '…', ",", ".", "'", '-'] -pu_symbols = punctuation + ["SP", "UNK"] -pad = '_' - -# chinese -zh_symbols = ['E', 'En', 'a', 'ai', 'an', 'ang', 'ao', 'b', 'c', 'ch', 'd', 'e', 'ei', 'en', 'eng', 'er', 'f', 'g', 'h', - 'i', 'i0', 'ia', 'ian', 'iang', 'iao', 'ie', 'in', 'ing', 'iong', 'ir', 'iu', 'j', 'k', 'l', 'm', 'n', 'o', - 'ong', - 'ou', 'p', 'q', 'r', 's', 'sh', 't', 'u', 'ua', 'uai', 'uan', 'uang', 'ui', 'un', 'uo', 'v', 'van', 've', 'vn', - 'w', 'x', 'y', 'z', 'zh', - "AA", "EE", "OO"] -num_zh_tones = 6 - -# japanese -ja_symbols = ['I', 'N', 'U', 'a', 'b', 'by', 'ch', 'cl', 'd', 'dy', 'e', 'f', 'g', 'gy', 'h', 'hy', 'i', 'j', 'k', 'ky', - 'm', 'my', 'n', 'ny', 'o', 'p', 'py', 'r', 'ry', 's', 'sh', 't', 'ts', 'u', 'V', 'w', 'y', 'z'] -num_ja_tones = 1 - -# English -en_symbols = ['aa', 'ae', 'ah', 'ao', 'aw', 'ay', 'b', 'ch', 'd', 'dh', 'eh', 'er', 'ey', 'f', 'g', 'hh', 'ih', 'iy', - 'jh', 'k', 'l', 'm', 'n', 'ng', 'ow', 'oy', 'p', 'r', 's', - 'sh', 't', 'th', 'uh', 'uw', 'V', 'w', 'y', 'z', 'zh'] -num_en_tones = 4 - -# combine all symbols -normal_symbols = sorted(set(zh_symbols + ja_symbols + en_symbols)) -symbols = [pad] + normal_symbols + pu_symbols -sil_phonemes_ids = [symbols.index(i) for i in pu_symbols] - -# combine all tones -num_tones = num_zh_tones + num_ja_tones + num_en_tones - -# language maps -language_id_map = { - 'ZH': 0, - "JA": 1, - "EN": 2 -} -num_languages = len(language_id_map.keys()) - -language_tone_start_map = { - 'ZH': 0, - "JA": num_zh_tones, - "EN": num_zh_tones + num_ja_tones -} - -if __name__ == '__main__': - a = set(zh_symbols) - b = set(en_symbols) - print(sorted(a&b)) - diff --git a/spaces/docparser/Text_Captcha_breaker/README.md b/spaces/docparser/Text_Captcha_breaker/README.md deleted file mode 100644 index b3504bb40a85c4f2387ba14ce4040060d2721dc2..0000000000000000000000000000000000000000 --- a/spaces/docparser/Text_Captcha_breaker/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Text Captcha Breaker -emoji: 🏃 -colorFrom: indigo -colorTo: gray -sdk: gradio -sdk_version: 3.37.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/docs-demos/xprophetnet-large-wiki100-cased-xglue-ntg/README.md b/spaces/docs-demos/xprophetnet-large-wiki100-cased-xglue-ntg/README.md deleted file mode 100644 index e52c3402f33f84387c172bc12ce5118457104660..0000000000000000000000000000000000000000 --- a/spaces/docs-demos/xprophetnet-large-wiki100-cased-xglue-ntg/README.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: XLM-ProphetNet -emoji: 📚 -colorFrom: blue -colorTo: pink -sdk: gradio -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`, `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. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/dolceschokolade/chatbot-mini/components/Promptbar/components/Prompts.tsx b/spaces/dolceschokolade/chatbot-mini/components/Promptbar/components/Prompts.tsx deleted file mode 100644 index b84f250c9ad5ac79a8f3ae893ff6f050e2846ebe..0000000000000000000000000000000000000000 --- a/spaces/dolceschokolade/chatbot-mini/components/Promptbar/components/Prompts.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { FC } from 'react'; - -import { Prompt } from '@/types/prompt'; - -import { PromptComponent } from './Prompt'; - -interface Props { - prompts: Prompt[]; -} - -export const Prompts: FC = ({ prompts }) => { - return ( -
    - {prompts - .slice() - .reverse() - .map((prompt, index) => ( - - ))} -
    - ); -}; diff --git a/spaces/dorkai/ChatUIPro/app/api/parameters/route.ts b/spaces/dorkai/ChatUIPro/app/api/parameters/route.ts deleted file mode 100644 index 1c1d917a30c08139a47dbe5a0fac9b80f680ecb0..0000000000000000000000000000000000000000 --- a/spaces/dorkai/ChatUIPro/app/api/parameters/route.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { type NextRequest } from 'next/server' -import { NextResponse } from 'next/server' -import { getInfo, setSession, client } from '@/app/api/utils/common' - -export async function GET(request: NextRequest) { - const { sessionId, user } = getInfo(request); - const { data } = await client.getApplicationParameters(user); - return NextResponse.json(data as object, { - headers: setSession(sessionId) - }) -} \ No newline at end of file diff --git a/spaces/dorkai/SINGPT-Temporary/modules/chat.py b/spaces/dorkai/SINGPT-Temporary/modules/chat.py deleted file mode 100644 index bd45b879f92f366255c6f2308ccf135dd61bda1d..0000000000000000000000000000000000000000 --- a/spaces/dorkai/SINGPT-Temporary/modules/chat.py +++ /dev/null @@ -1,398 +0,0 @@ -import base64 -import copy -import io -import json -import re -from datetime import datetime -from pathlib import Path - -from PIL import Image - -import modules.extensions as extensions_module -import modules.shared as shared -from modules.extensions import apply_extensions -from modules.html_generator import generate_chat_html -from modules.text_generation import encode, generate_reply, get_max_prompt_length - - -# This gets the new line characters right. -def clean_chat_message(text): - text = text.replace('\n', '\n\n') - text = re.sub(r"\n{3,}", "\n\n", text) - text = text.strip() - return text - -def generate_chat_output(history, name1, name2, character): - if shared.args.cai_chat: - return generate_chat_html(history, name1, name2, character) - else: - return history - -def generate_chat_prompt(user_input, max_new_tokens, name1, name2, context, chat_prompt_size, impersonate=False): - user_input = clean_chat_message(user_input) - rows = [f"{context.strip()}\n"] - - if shared.soft_prompt: - chat_prompt_size -= shared.soft_prompt_tensor.shape[1] - max_length = min(get_max_prompt_length(max_new_tokens), chat_prompt_size) - - i = len(shared.history['internal'])-1 - while i >= 0 and len(encode(''.join(rows), max_new_tokens)[0]) < max_length: - rows.insert(1, f"{name2}: {shared.history['internal'][i][1].strip()}\n") - if not (shared.history['internal'][i][0] == '<|BEGIN-VISIBLE-CHAT|>'): - rows.insert(1, f"{name1}: {shared.history['internal'][i][0].strip()}\n") - i -= 1 - - if not impersonate: - rows.append(f"{name1}: {user_input}\n") - rows.append(apply_extensions(f"{name2}:", "bot_prefix")) - limit = 3 - else: - rows.append(f"{name1}:") - limit = 2 - - while len(rows) > limit and len(encode(''.join(rows), max_new_tokens)[0]) >= max_length: - rows.pop(1) - - prompt = ''.join(rows) - return prompt - -def extract_message_from_reply(question, reply, name1, name2, check, impersonate=False): - next_character_found = False - - asker = name1 if not impersonate else name2 - replier = name2 if not impersonate else name1 - - previous_idx = [m.start() for m in re.finditer(f"(^|\n){re.escape(replier)}:", question)] - idx = [m.start() for m in re.finditer(f"(^|\n){re.escape(replier)}:", reply)] - idx = idx[max(len(previous_idx)-1, 0)] - - if not impersonate: - reply = reply[idx + 1 + len(apply_extensions(f"{replier}:", "bot_prefix")):] - else: - reply = reply[idx + 1 + len(f"{replier}:"):] - - if check: - lines = reply.split('\n') - reply = lines[0].strip() - if len(lines) > 1: - next_character_found = True - else: - idx = reply.find(f"\n{asker}:") - if idx != -1: - reply = reply[:idx] - next_character_found = True - reply = clean_chat_message(reply) - - # If something like "\nYo" is generated just before "\nYou:" - # is completed, trim it - next_turn = f"\n{asker}:" - for j in range(len(next_turn)-1, 0, -1): - if reply[-j:] == next_turn[:j]: - reply = reply[:-j] - break - - return reply, next_character_found - -def stop_everything_event(): - shared.stop_everything = True - -def chatbot_wrapper(text, max_new_tokens, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, chat_generation_attempts=1, regenerate=False): - shared.stop_everything = False - just_started = True - eos_token = '\n' if check else None - name1_original = name1 - if 'pygmalion' in shared.model_name.lower(): - name1 = "You" - - # Check if any extension wants to hijack this function call - visible_text = None - custom_generate_chat_prompt = None - for extension, _ in extensions_module.iterator(): - if hasattr(extension, 'input_hijack') and extension.input_hijack['state'] == True: - extension.input_hijack['state'] = False - text, visible_text = extension.input_hijack['value'] - if custom_generate_chat_prompt is None and hasattr(extension, 'custom_generate_chat_prompt'): - custom_generate_chat_prompt = extension.custom_generate_chat_prompt - - if visible_text is None: - visible_text = text - if shared.args.chat: - visible_text = visible_text.replace('\n', '
    ') - text = apply_extensions(text, "input") - - if custom_generate_chat_prompt is None: - prompt = generate_chat_prompt(text, max_new_tokens, name1, name2, context, chat_prompt_size) - else: - prompt = custom_generate_chat_prompt(text, max_new_tokens, name1, name2, context, chat_prompt_size) - - # Yield *Is typing...* - if not regenerate: - yield shared.history['visible']+[[visible_text, shared.processing_message]] - - # Generate - reply = '' - for i in range(chat_generation_attempts): - for reply in generate_reply(f"{prompt}{' ' if len(reply) > 0 else ''}{reply}", max_new_tokens, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, eos_token=eos_token, stopping_string=f"\n{name1}:"): - - # Extracting the reply - reply, next_character_found = extract_message_from_reply(prompt, reply, name1, name2, check) - visible_reply = re.sub("(||{{user}})", name1_original, reply) - visible_reply = apply_extensions(visible_reply, "output") - if shared.args.chat: - visible_reply = visible_reply.replace('\n', '
    ') - - # We need this global variable to handle the Stop event, - # otherwise gradio gets confused - if shared.stop_everything: - return shared.history['visible'] - if just_started: - just_started = False - shared.history['internal'].append(['', '']) - shared.history['visible'].append(['', '']) - - shared.history['internal'][-1] = [text, reply] - shared.history['visible'][-1] = [visible_text, visible_reply] - if not shared.args.no_stream: - yield shared.history['visible'] - if next_character_found: - break - - yield shared.history['visible'] - -def impersonate_wrapper(text, max_new_tokens, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, chat_generation_attempts=1): - eos_token = '\n' if check else None - - if 'pygmalion' in shared.model_name.lower(): - name1 = "You" - - prompt = generate_chat_prompt(text, max_new_tokens, name1, name2, context, chat_prompt_size, impersonate=True) - - reply = '' - # Yield *Is typing...* - yield shared.processing_message - for i in range(chat_generation_attempts): - for reply in generate_reply(prompt+reply, max_new_tokens, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, eos_token=eos_token, stopping_string=f"\n{name2}:"): - reply, next_character_found = extract_message_from_reply(prompt, reply, name1, name2, check, impersonate=True) - yield reply - if next_character_found: - break - yield reply - -def cai_chatbot_wrapper(text, max_new_tokens, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, chat_generation_attempts=1): - for _history in chatbot_wrapper(text, max_new_tokens, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, chat_generation_attempts): - yield generate_chat_html(_history, name1, name2, shared.character) - -def regenerate_wrapper(text, max_new_tokens, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, chat_generation_attempts=1): - if (shared.character != 'None' and len(shared.history['visible']) == 1) or len(shared.history['internal']) == 0: - yield generate_chat_output(shared.history['visible'], name1, name2, shared.character) - else: - last_visible = shared.history['visible'].pop() - last_internal = shared.history['internal'].pop() - # Yield '*Is typing...*' - yield generate_chat_output(shared.history['visible']+[[last_visible[0], shared.processing_message]], name1, name2, shared.character) - for _history in chatbot_wrapper(last_internal[0], max_new_tokens, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, chat_generation_attempts, regenerate=True): - if shared.args.cai_chat: - shared.history['visible'][-1] = [last_visible[0], _history[-1][1]] - else: - shared.history['visible'][-1] = (last_visible[0], _history[-1][1]) - yield generate_chat_output(shared.history['visible'], name1, name2, shared.character) - -def remove_last_message(name1, name2): - if len(shared.history['visible']) > 0 and not shared.history['internal'][-1][0] == '<|BEGIN-VISIBLE-CHAT|>': - last = shared.history['visible'].pop() - shared.history['internal'].pop() - else: - last = ['', ''] - - if shared.args.cai_chat: - return generate_chat_html(shared.history['visible'], name1, name2, shared.character), last[0] - else: - return shared.history['visible'], last[0] - -def send_last_reply_to_input(): - if len(shared.history['internal']) > 0: - return shared.history['internal'][-1][1] - else: - return '' - -def replace_last_reply(text, name1, name2): - if len(shared.history['visible']) > 0: - if shared.args.cai_chat: - shared.history['visible'][-1][1] = text - else: - shared.history['visible'][-1] = (shared.history['visible'][-1][0], text) - shared.history['internal'][-1][1] = apply_extensions(text, "input") - - return generate_chat_output(shared.history['visible'], name1, name2, shared.character) - -def clear_html(): - return generate_chat_html([], "", "", shared.character) - -def clear_chat_log(name1, name2): - if shared.character != 'None': - found = False - for i in range(len(shared.history['internal'])): - if '<|BEGIN-VISIBLE-CHAT|>' in shared.history['internal'][i][0]: - shared.history['visible'] = [['', apply_extensions(shared.history['internal'][i][1], "output")]] - shared.history['internal'] = [shared.history['internal'][i]] - found = True - break - if not found: - shared.history['visible'] = [] - shared.history['internal'] = [] - else: - shared.history['internal'] = [] - shared.history['visible'] = [] - - return generate_chat_output(shared.history['visible'], name1, name2, shared.character) - -def redraw_html(name1, name2): - return generate_chat_html(shared.history['visible'], name1, name2, shared.character) - -def tokenize_dialogue(dialogue, name1, name2): - _history = [] - - dialogue = re.sub('', '', dialogue) - dialogue = re.sub('', '', dialogue) - dialogue = re.sub('(\n|^)[Aa]non:', '\\1You:', dialogue) - dialogue = re.sub('(\n|^)\[CHARACTER\]:', f'\\g<1>{name2}:', dialogue) - idx = [m.start() for m in re.finditer(f"(^|\n)({re.escape(name1)}|{re.escape(name2)}):", dialogue)] - if len(idx) == 0: - return _history - - messages = [] - for i in range(len(idx)-1): - messages.append(dialogue[idx[i]:idx[i+1]].strip()) - messages.append(dialogue[idx[-1]:].strip()) - - entry = ['', ''] - for i in messages: - if i.startswith(f'{name1}:'): - entry[0] = i[len(f'{name1}:'):].strip() - elif i.startswith(f'{name2}:'): - entry[1] = i[len(f'{name2}:'):].strip() - if not (len(entry[0]) == 0 and len(entry[1]) == 0): - _history.append(entry) - entry = ['', ''] - - print("\033[1;32;1m\nDialogue tokenized to:\033[0;37;0m\n", end='') - for row in _history: - for column in row: - print("\n") - for line in column.strip().split('\n'): - print("| "+line+"\n") - print("|\n") - print("------------------------------") - - return _history - -def save_history(timestamp=True): - prefix = '' if shared.character == 'None' else f"{shared.character}_" - if timestamp: - fname = f"{prefix}{datetime.now().strftime('%Y%m%d-%H%M%S')}.json" - else: - fname = f"{prefix}persistent.json" - if not Path('logs').exists(): - Path('logs').mkdir() - with open(Path(f'logs/{fname}'), 'w', encoding='utf-8') as f: - f.write(json.dumps({'data': shared.history['internal'], 'data_visible': shared.history['visible']}, indent=2)) - return Path(f'logs/{fname}') - -def load_history(file, name1, name2): - file = file.decode('utf-8') - try: - j = json.loads(file) - if 'data' in j: - shared.history['internal'] = j['data'] - if 'data_visible' in j: - shared.history['visible'] = j['data_visible'] - else: - shared.history['visible'] = copy.deepcopy(shared.history['internal']) - # Compatibility with Pygmalion AI's official web UI - elif 'chat' in j: - shared.history['internal'] = [':'.join(x.split(':')[1:]).strip() for x in j['chat']] - if len(j['chat']) > 0 and j['chat'][0].startswith(f'{name2}:'): - shared.history['internal'] = [['<|BEGIN-VISIBLE-CHAT|>', shared.history['internal'][0]]] + [[shared.history['internal'][i], shared.history['internal'][i+1]] for i in range(1, len(shared.history['internal'])-1, 2)] - shared.history['visible'] = copy.deepcopy(shared.history['internal']) - shared.history['visible'][0][0] = '' - else: - shared.history['internal'] = [[shared.history['internal'][i], shared.history['internal'][i+1]] for i in range(0, len(shared.history['internal'])-1, 2)] - shared.history['visible'] = copy.deepcopy(shared.history['internal']) - except: - shared.history['internal'] = tokenize_dialogue(file, name1, name2) - shared.history['visible'] = copy.deepcopy(shared.history['internal']) - -def load_default_history(name1, name2): - if Path('logs/persistent.json').exists(): - load_history(open(Path('logs/persistent.json'), 'rb').read(), name1, name2) - else: - shared.history['internal'] = [] - shared.history['visible'] = [] - -def load_character(_character, name1, name2): - context = "" - shared.history['internal'] = [] - shared.history['visible'] = [] - if _character != 'None': - shared.character = _character - data = json.loads(open(Path(f'characters/{_character}.json'), 'r', encoding='utf-8').read()) - name2 = data['char_name'] - if 'char_persona' in data and data['char_persona'] != '': - context += f"{data['char_name']}'s Persona: {data['char_persona']}\n" - if 'world_scenario' in data and data['world_scenario'] != '': - context += f"Scenario: {data['world_scenario']}\n" - context = f"{context.strip()}\n\n" - if 'example_dialogue' in data and data['example_dialogue'] != '': - data['example_dialogue'] = data['example_dialogue'].replace('{{user}}', name1).replace('{{char}}', name2) - data['example_dialogue'] = data['example_dialogue'].replace('', name1).replace('', name2) - context += f"{data['example_dialogue'].strip()}\n" - if 'char_greeting' in data and len(data['char_greeting'].strip()) > 0: - shared.history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', data['char_greeting']]] - shared.history['visible'] += [['', apply_extensions(data['char_greeting'], "output")]] - else: - shared.history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', "Hello there!"]] - shared.history['visible'] += [['', "Hello there!"]] - else: - shared.character = None - context = shared.settings['context_pygmalion'] - name2 = shared.settings['name2_pygmalion'] - - if Path(f'logs/{shared.character}_persistent.json').exists(): - load_history(open(Path(f'logs/{shared.character}_persistent.json'), 'rb').read(), name1, name2) - - if shared.args.cai_chat: - return name2, context, generate_chat_html(shared.history['visible'], name1, name2, shared.character) - else: - return name2, context, shared.history['visible'] - -def upload_character(json_file, img, tavern=False): - json_file = json_file if type(json_file) == str else json_file.decode('utf-8') - data = json.loads(json_file) - outfile_name = data["char_name"] - i = 1 - while Path(f'characters/{outfile_name}.json').exists(): - outfile_name = f'{data["char_name"]}_{i:03d}' - i += 1 - if tavern: - outfile_name = f'TavernAI-{outfile_name}' - with open(Path(f'characters/{outfile_name}.json'), 'w', encoding='utf-8') as f: - f.write(json_file) - if img is not None: - img = Image.open(io.BytesIO(img)) - img.save(Path(f'characters/{outfile_name}.png')) - print(f'New character saved to "characters/{outfile_name}.json".') - return outfile_name - -def upload_tavern_character(img, name1, name2): - _img = Image.open(io.BytesIO(img)) - _img.getexif() - decoded_string = base64.b64decode(_img.info['chara']) - _json = json.loads(decoded_string) - _json = {"char_name": _json['name'], "char_persona": _json['description'], "char_greeting": _json["first_mes"], "example_dialogue": _json['mes_example'], "world_scenario": _json['scenario']} - return upload_character(json.dumps(_json), img, tavern=True) - -def upload_your_profile_picture(img): - img = Image.open(io.BytesIO(img)) - img.save(Path('img_me.png')) - print('Profile picture saved to "img_me.png"') diff --git a/spaces/editing-images/ledtisplusplus/style.css b/spaces/editing-images/ledtisplusplus/style.css deleted file mode 100644 index d6e239670847d751aa7aa5f7dda3e87fbd2f63a9..0000000000000000000000000000000000000000 --- a/spaces/editing-images/ledtisplusplus/style.css +++ /dev/null @@ -1,83 +0,0 @@ -/* -This CSS file is modified from: -https://huggingface.co/spaces/DeepFloyd/IF/blob/main/style.css -*/ - -h1 { - text-align: center; -} - -.gradio-container { - font-family: 'IBM Plex Sans', sans-serif; -} - -.gr-button { - color: white; - border-color: black; - background: black; -} - -input[type='range'] { - accent-color: black; -} - -.dark input[type='range'] { - accent-color: #dfdfdf; -} - -.container { - max-width: 730px; - margin: auto; -} - - -.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; -} - -.gr-form { - flex: 1 1 50%; - border-top-right-radius: 0; - border-bottom-right-radius: 0; -} - -#prompt-container { - gap: 0; -} - -#prompt-text-input, -#negative-prompt-text-input { - padding: .45rem 0.625rem -} - -/* #component-16 { - border-top-width: 1px !important; - margin-top: 1em -} */ - -.image_duplication { - position: absolute; - width: 100px; - left: 50px -} - -#component-0 { - max-width: 730px; - margin: auto; - padding-top: 1.5rem; -} -#share-btn-container{padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; max-width: 13rem; margin-left: auto;margin-top: 0.35em;} -div#share-btn-container > div {flex-direction: row;background: black;align-items: center} -#share-btn-container:hover {background-color: #060606} -#share-btn {all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.5rem !important; padding-bottom: 0.5rem !important;right:0;font-size: 15px;} -#share-btn * {all: unset} -#share-btn-container div:nth-child(-n+2){width: auto !important;min-height: 0px !important;} -#share-btn-container .wrap {display: none !important} -#share-btn-container.hidden {display: none!important} \ No newline at end of file diff --git a/spaces/eldoraboo/zero-shot/app.py b/spaces/eldoraboo/zero-shot/app.py deleted file mode 100644 index e0f7c6f90b5b0623998f7c663b443fd1cb5c2868..0000000000000000000000000000000000000000 --- a/spaces/eldoraboo/zero-shot/app.py +++ /dev/null @@ -1,40 +0,0 @@ -import gradio as gr -from transformers import pipeline - -title = "Zero-Shot Text Classification with Hugging Face" -description = "bart-large-mnli" - -classifier = pipeline("zero-shot-classification", - model="facebook/bart-large-mnli") - -#define a function to process your input and output -def zero_shot(doc, candidates): - given_labels = candidates.split(", ") - dictionary = classifier(doc, given_labels) - labels = dictionary['labels'] - scores = dictionary['scores'] - return dict(zip(labels, scores)) - -#create input and output objects -#input object1 -input1 = gr.Textbox(label="Text") -#input object 2 -input2 = gr.Textbox(label="Labels") -#output object -output = gr.Label(label="Output") -#example object -examples = [ - ["TDC A/S provides communications and entertainment solutions in Denmark. It operates through Nuuday and TDC NET segments. The company designs, builds, and operates broadband and mobile networks; and provides technical support to customers and networks. It offers services, such as landline voice, TV and streaming, broadband, Internet and network, mobility, and other services. The company provides its products and services under the YouSee, Hiper, Telmore, Blockbuster, TDC Business, TDC Erhverv, Fullrate, NetDesign, and Relatel brands. It serves consumer and business customers. The company was founded in 1882 and is based in Copenhagen, Denmark. TDC A/S is a subsidiary of DK Telekommunikation ApS.", "Diversified Telecommunication Services, Wireless Telecommunication Services, Media, Entertainment, Interactive Media and Services"], - ["Giddy Inc., doing business as Boxed Wholesale, offers online wholesale and retailing services. The company provides cleaning and laundry, kitchen, paper, skin care, hair care, and grocery products. Additionally, it offers diapers and organic products. Giddy Inc. was founded in 2013 and is based in Edison, New Jersey.", "Food and Staples Retailing, Beverages, Food Products, Household Products, Personal Products, Tobacco"], - ["United Iron And Steel Manufacturing Company (P.L.C.) produces and sells iron and steel products in Jordan. It is also involved in trading scrap iron. The company was incorporated in 1992 and is headquartered in Amman, Jordan. United Iron And Steel Manufacturing Company (P.L.C.) is a subsidiary of Manaseer Group Corporation.", "Chemicals, Construction Materials, Containers and Packaging, Metals and Mining, Paper and Forest Products"] - ] -#create interface -gui = gr.Interface(title=title, - description=description, - fn=zero_shot, - inputs=[input1, input2], - outputs=[output], - examples=examples) - -#display the interface -gui.launch() \ No newline at end of file diff --git a/spaces/elkraken/Video-Object-Detection/deploy/triton-inference-server/boundingbox.py b/spaces/elkraken/Video-Object-Detection/deploy/triton-inference-server/boundingbox.py deleted file mode 100644 index 8b95330b8a669e7df300066aa9b31723e055b031..0000000000000000000000000000000000000000 --- a/spaces/elkraken/Video-Object-Detection/deploy/triton-inference-server/boundingbox.py +++ /dev/null @@ -1,33 +0,0 @@ -class BoundingBox: - def __init__(self, classID, confidence, x1, x2, y1, y2, image_width, image_height): - self.classID = classID - self.confidence = confidence - self.x1 = x1 - self.x2 = x2 - self.y1 = y1 - self.y2 = y2 - self.u1 = x1 / image_width - self.u2 = x2 / image_width - self.v1 = y1 / image_height - self.v2 = y2 / image_height - - def box(self): - return (self.x1, self.y1, self.x2, self.y2) - - def width(self): - return self.x2 - self.x1 - - def height(self): - return self.y2 - self.y1 - - def center_absolute(self): - return (0.5 * (self.x1 + self.x2), 0.5 * (self.y1 + self.y2)) - - def center_normalized(self): - return (0.5 * (self.u1 + self.u2), 0.5 * (self.v1 + self.v2)) - - def size_absolute(self): - return (self.x2 - self.x1, self.y2 - self.y1) - - def size_normalized(self): - return (self.u2 - self.u1, self.v2 - self.v1) diff --git a/spaces/emrecan/zero-shot-turkish/app.py b/spaces/emrecan/zero-shot-turkish/app.py deleted file mode 100644 index baca7de682e6553cd3c480da23e865c1af90b8c4..0000000000000000000000000000000000000000 --- a/spaces/emrecan/zero-shot-turkish/app.py +++ /dev/null @@ -1,135 +0,0 @@ -from __future__ import annotations -import psutil -import pandas as pd -import streamlit as st -import plotly.express as px -from models import NLI_MODEL_OPTIONS, NSP_MODEL_OPTIONS, METHOD_OPTIONS -from zeroshot_classification.classifiers import NSPZeroshotClassifier, NLIZeroshotClassifier - -print(f"Total mem: {psutil.virtual_memory().total}") - -def init_state(key: str): - if key not in st.session_state: - st.session_state[key] = None - - -for k in [ - "current_model", - "current_model_option", - "current_method_option", - "current_prediction", - "current_chart", -]: - init_state(k) - - -def load_model(model_option: str, method_option: str, random_state: int = 0): - with st.spinner("Loading selected model..."): - if method_option == "Natural Language Inference": - st.session_state.current_model = NLIZeroshotClassifier( - model_name=model_option, random_state=random_state - ) - else: - st.session_state.current_model = NSPZeroshotClassifier( - model_name=model_option, random_state=random_state - ) - st.success("Model loaded!") - - -def visualize_output(labels: list[str], probabilities: list[float]): - data = pd.DataFrame({"labels": labels, "probability": probabilities}).sort_values( - by="probability", ascending=False - ) - chart = px.bar( - data, - x="probability", - y="labels", - color="labels", - orientation="h", - height=290, - width=500, - ).update_layout( - { - "xaxis": {"title": "probability", "visible": True, "showticklabels": True}, - "yaxis": {"title": None, "visible": True, "showticklabels": True}, - "margin": dict( - l=10, # left - r=10, # right - t=50, # top - b=10, # bottom - ), - "showlegend": False, - } - ) - return chart - - -st.title("Zero-shot Turkish Text Classification") -method_option = st.radio( - "Select a zero-shot classification method.", - [ - METHOD_OPTIONS["nli"], - METHOD_OPTIONS["nsp"], - ], -) -if method_option == METHOD_OPTIONS["nli"]: - model_option = st.selectbox( - "Select a natural language inference model.", NLI_MODEL_OPTIONS, index=3 - ) -if method_option == METHOD_OPTIONS["nsp"]: - model_option = st.selectbox( - "Select a BERT model for next sentence prediction.", NSP_MODEL_OPTIONS, index=0 - ) - -if model_option != st.session_state.current_model_option: - st.session_state.current_model_option = model_option - st.session_state.current_method_option = method_option - load_model( - st.session_state.current_model_option, st.session_state.current_method_option - ) - - -st.header("Configure prompts and labels") -col1, col2 = st.columns(2) -col1.subheader("Candidate labels") -labels = col1.text_area( - label="These are the labels that the model will try to predict for the given text input. Your input labels should be comma separated and meaningful.", - value="spor,dünya,siyaset,ekonomi,sanat", - key="current_labels", -) - -col1.header("Make predictions") -text = col1.text_area( - "Enter a sentence or a paragraph to classify.", - value="Ian Anderson, Jethro Tull konserinde yan flüt çalarak zeybek oynadı.", - key="current_text", -) -col2.subheader("Prompt template") -prompt_template = col2.text_area( - label="Prompt template is used to transform NLI and NSP tasks into a general-use zero-shot classifier. Models replace {} with the labels that you have given.", - value="Bu metin {} kategorisine aittir", - key="current_template", -) -col2.header("") - - -make_pred = col1.button("Predict") -if make_pred: - st.session_state.current_prediction = ( - st.session_state.current_model.predict_on_texts( - [st.session_state.current_text], - candidate_labels=st.session_state.current_labels.split(","), - prompt_template=st.session_state.current_template, - ) - ) - if "scores" in st.session_state.current_prediction[0]: - st.session_state.current_chart = visualize_output( - st.session_state.current_prediction[0]["labels"], - st.session_state.current_prediction[0]["scores"], - ) - elif "probabilities" in st.session_state.current_prediction[0]: - st.session_state.current_chart = visualize_output( - st.session_state.current_prediction[0]["labels"], - st.session_state.current_prediction[0]["probabilities"], - ) - col2.plotly_chart(st.session_state.current_chart, use_container_width=True) diff --git a/spaces/falterWliame/Face_Mask_Detection/Beautify Tool 4 Keygen UPDATED Or Crack Free.md b/spaces/falterWliame/Face_Mask_Detection/Beautify Tool 4 Keygen UPDATED Or Crack Free.md deleted file mode 100644 index 849d57ddbac33b9ff8c2f099f4ef6c61bcdc9235..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/Beautify Tool 4 Keygen UPDATED Or Crack Free.md +++ /dev/null @@ -1,9 +0,0 @@ - -

    most modern operating systems contain a built-in tool called disk management that supports creating, deleting, and resizing partitions on internal and external hard drives, hdd/ssd, usbs, and even sd cards. however, some windows beginners report that disk management is somehow a bit complex to run and may cause data loss issues without a warning notice. so is there a disk management alternative tool that works the same or even better in disk partitioning yes, here is a list of free windows 10 disk management tools that you can apply to execute disk partitioning tasks with ease and effectively.

    -

    Beautify tool 4 keygen or crack free


    DOWNLOAD ☆☆☆☆☆ https://urlca.com/2uDdSB



    -

    most modern operating systems contain a built-in tool called disk management that supports creating, deleting, and resizing partitions on internal and external hard drives, hdd/ssd, usbs, and even sd cards.

    -

    if you are an ms windows user you might already be familiar with the yumi and grub tools. these tools have been used for many years to create bootable media for linux and other unix based systems. but did you know that you can use yumi to create bootable windows media, and grub to create bootable linux media?

    -

    active@ disk imager is a windows utility to create bootable media with a variety of different operating systems. this tool is useful for both linux and windows users. you can create a bootable disk with any version of linux such as ubuntu, fedora, mint, or debian. the active@ disk imager also works with windows. this is a free tool for linux and windows users. however, it's not a free tool for creating windows bootable media. you need to purchase it for this purpose.

    -

    899543212b
    -
    -
    \ No newline at end of file diff --git a/spaces/falterWliame/Face_Mask_Detection/HD Online Player (Auto Poweron And Shutdown 283 Serial).md b/spaces/falterWliame/Face_Mask_Detection/HD Online Player (Auto Poweron And Shutdown 283 Serial).md deleted file mode 100644 index 2fe4fd8e7301f64e4c1631e824c85395bf85afe7..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/HD Online Player (Auto Poweron And Shutdown 283 Serial).md +++ /dev/null @@ -1,10 +0,0 @@ -

    HD Online Player (Auto Poweron And Shutdown 283 Serial)


    DOWNLOAD ☆☆☆ https://urlca.com/2uDc18



    - -Epson Instant Off and Direct Power On functions for quick setup and shutdown. • Built-in closed caption decoder (NTSC composite input only; Supported file formats: DPOF (direct print), JPEG, XPS, TIFF, BMP, EPS, TXT, PDF, PCX, DCX, GIF, PICT, TIF, PSD, JPS, PNM, WMF, EMF, RAW, PXM, AVI, MOV, MP3, WAV, MP4, M4A, M4B, 3GP, WMV, FLV, RM, RMVB, AAC, AC3, M4A, M4B, FLAC. -Dimensions: 230 x 167 x 114 mm. -Weight: 1.5 kg. -Black color. -Included: - Epson EB-X05 monitor; - software; - power cable; - SCART cable; - DVI-D cable; - remote control; - disks with drivers; - user manual 8a78ff9644
    -
    -
    -

    diff --git a/spaces/falterWliame/Face_Mask_Detection/Playstation 3 Games Download HOT Jailbreak Free.md b/spaces/falterWliame/Face_Mask_Detection/Playstation 3 Games Download HOT Jailbreak Free.md deleted file mode 100644 index 9e099e5b76639256cb1e1c66ec95a4bbd1bc9db3..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/Playstation 3 Games Download HOT Jailbreak Free.md +++ /dev/null @@ -1,46 +0,0 @@ -

    playstation 3 games download jailbreak free


    Download » https://urlca.com/2uDcLF



    - -iphone 6/6s/6s plus iPhone 8/8s/8 Plus/8s Plus iphone SE/SE 2/SE 2 Plus/SE 2 - - JohnSmith: you can't. you have to use a flash drive or similar to carry that around. - - xplorer, free software and free documentation, tell that to canonical - - i have the 256x glw 260 on my macbook pro with windows 7 and it works flawlessly - - OerHeks, i have read it - - rfm, ahh ok, that is a pity, but i guess it is the easiest way - - i have tried it on 3 different hardware - - i also heard that is works for htc and samsung - - JohnSmith: it has been known to work with USB tethering, but I don't know how. - - but i have not tried it on my windows machine - - yet - - theborger: I think you're missing the point of all the "cat /proc/cpuinfo" output I posted. - - OerHeks, i have read it and installed it on ubuntu, but nothing happens - - JohnSmith: some android device might let you tether with the phone, but I don't know of any. - - rfm, i don't know, i just don't have a good feeling about it. i am just curious as to how stable it is to get root access on my galaxy s7 edge phone - - not buying the cat command - - xplorer, i have not answered you, so i will not help you anymore - - OerHeks, what answer - - xplorer, not the one you were waiting for - - how many lines of it do you need - - JohnSmith: I have no idea, I'm only the poor sucker with a ZTE mx3 I have to try to get 3G to work (wifi). (Which of course didn't work the last time I tried.) 4fefd39f24
    -
    -
    -

    diff --git a/spaces/fatiXbelha/sd/Animes Online APK The Best App for Anime Lovers.md b/spaces/fatiXbelha/sd/Animes Online APK The Best App for Anime Lovers.md deleted file mode 100644 index c0e951a2f0cb32aa0cde61a0384b227d5621c8f7..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Animes Online APK The Best App for Anime Lovers.md +++ /dev/null @@ -1,127 +0,0 @@ - -

    How to Watch and Download Animes Online with APKs

    -

    Anime is a form of animation that originated in Japan and has become a global phenomenon. Anime fans love to watch their favorite shows and movies online, but sometimes they face problems such as geo-restrictions, ads, low quality, or limited availability. That's why many anime lovers turn to APKs, which are Android application packages that can be installed on their devices to access anime streaming platforms. In this article, we will explain what animes and APKs are, how to install them, and what are the best anime APKs to watch and download animes online.

    -

    What are Animes and Why are They Popular?

    -

    Definition and History of Animes

    -

    Anime is a term that refers to Japanese animation, which is characterized by colorful graphics, dynamic characters, and diverse genres. Anime can be based on manga (Japanese comics), novels, video games, or original stories. Anime has a long history that dates back to the early 20th century, when the first animated films were produced in Japan. Since then, anime has evolved and expanded into various styles and formats, such as TV series, movies, OVAs (original video animations), ONAs (original net animations), and webtoons.

    -

    animes online download apk


    Download Zip » https://urllie.com/2uNzu6



    -

    Major Genres and Examples of Animes

    -

    Anime has a wide range of genres that cater to different audiences and tastes. Some of the major genres of anime include:

    -
      -
    • Action: This genre features fast-paced scenes, fights, battles, and adventures. Examples are Naruto, Dragon Ball, One Piece, Attack on Titan, and My Hero Academia.
    • -
    • Romance: This genre focuses on the love relationships between the characters, often with drama, comedy, or fantasy elements. Examples are Your Name, Kimi ni Todoke, Toradora, Fruits Basket, and Kaguya-sama: Love is War.
    • -
    • Comedy: This genre aims to make the viewers laugh with humor, satire, parody, or slapstick. Examples are Gintama, One Punch Man, Konosuba, Nichijou, and The Disastrous Life of Saiki K.
    • -
    • Drama: This genre deals with serious and emotional topics, such as death, trauma, loss, or conflict. Examples are Clannad, Anohana, Violet Evergarden, Your Lie in April, and Erased.
    • -
    • Fantasy: This genre involves supernatural or magical elements, such as dragons, wizards, demons, or spirits. Examples are Fullmetal Alchemist: Brotherhood, Re:Zero, The Rising of the Shield Hero, That Time I Got Reincarnated as a Slime, and The Promised Neverland.
    • -
    • Science Fiction: This genre explores the impact of science and technology on society or individuals, such as robots, aliens, time travel, or dystopia. Examples are Steins;Gate, Code Geass, Ghost in the Shell, Psycho-Pass, and Akira.
    • -
    -

    What are APKs and How to Install Them?

    -

    Definition and Benefits of APKs

    -

    APK stands for Android Package Kit, which is a file format that contains all the components of an Android app. APKs can be downloaded from various sources online, such as official websites, third-party app stores, or file-sharing platforms. APKs have some benefits over the apps that are available on the Google Play Store, such as:

    -
      -
    • They can offer more features, functions, or content that are not allowed or restricted by Google's policies.
    • -
    • They can bypass geo-restrictions or censorship that may prevent some users from accessing certain apps or content.
    • -
    • They can provide updates faster or more frequently than the official app versions.
    • -
    • They can be customized or modified according to the user's preferences or needs.
    • -
    -

    Steps to Install APKs on Android Devices

    -

    To install APKs on your Android device, you need to follow these steps:

    -

    watch animes online free download apk
    -best animes online streaming app apk
    -animes online download apk for android
    -how to download animes online legally apk
    -animes online download apk with subtitles
    -animes online download apk without ads
    -animes online download apk latest version
    -animes online download apk for pc
    -top 10 animes online download apk
    -animes online download apk mod
    -animes online download apk for ios
    -animes online download apk no registration
    -animes online download apk hd quality
    -animes online download apk for firestick
    -animes online download apk reddit
    -animes online download apk 2023
    -animes online download apk english dub
    -animes online download apk for smart tv
    -animes online download apk with vpn
    -animes online download apk for mac
    -animes online download apk safe
    -animes online download apk review
    -animes online download apk for chromebook
    -animes online download apk offline mode
    -animes online download apk 4k resolution
    -animes online download apk for windows 10
    -animes online download apk with chromecast support
    -animes online download apk unlimited access
    -animes online download apk for roku
    -animes online download apk with dark mode
    -animes online download apk for linux
    -animes online download apk with manga reader
    -animes online download apk premium features
    -animes online download apk for ps4
    -animes online download apk with anime recommendations
    -animes online download apk for xbox one
    -animes online download apk with voice search
    -animes online download apk with parental control
    -animes online download apk for nintendo switch
    -animes online download apk with anime news and updates

    -
      -
    1. Download the APK file from a trusted source and save it on your device's storage.
    2. -
    3. Go to your device's settings and enable the option to install apps from unknown sources. This may vary depending on your device model and Android version, but you can usually find it under security, privacy, or applications settings.
    4. -
    5. Locate the APK file on your device using a file manager app and tap on it to start the installation process. You may need to grant some permissions or accept some terms and conditions before proceeding.
    6. -
    7. Wait for the installation to finish and then launch the app from your app drawer or home screen.
    8. -
    -

    Best Anime APKs to Watch and Download Animes Online

    -

    Crunchyroll

    -

    Features and Benefits of Crunchyroll

    -

    Crunchyroll is one of the most popular and reputable anime streaming platforms in the world. It has a huge library of anime titles, including the latest and most popular ones, as well as classics and originals. Crunchyroll also offers manga, drama, music, and games related to anime culture. Some of the features and benefits of Crunchyroll are:

    -
      -
    • It has a high-quality video and audio streaming service, with options to adjust the resolution, subtitles, and language.
    • -
    • It supports offline viewing, which allows you to download episodes and watch them later without an internet connection.
    • -
    • It has a user-friendly interface, with categories, genres, recommendations, and favorites to help you find what you want to watch.
    • -
    • It has a premium membership option, which gives you access to more content, ad-free streaming, simulcasts, and exclusive perks.
    • -
    -

    How to Use Crunchyroll

    -

    To use Crunchyroll, you need to download its APK file from its official website or from a reliable third-party source. Then, you need to install it on your device following the steps mentioned above. After that, you can either sign up for a free account or log in with your existing account. You can also opt for a premium membership if you want more benefits. Once you are in the app, you can browse through the anime catalog, select an episode, and start watching or downloading it.

    -

    9Anime

    -

    Features and Benefits of 9Anime

    -

    9Anime is another popular anime streaming platform that offers a wide range of anime titles in various genres and categories. 9Anime is known for its fast updates, high-quality videos, and diverse options. Some of the features and benefits of 9Anime are:

    -
      -
    • It has a large collection of anime shows and movies, including dubbed and subbed versions, as well as original soundtracks.
    • -
    • It has a smooth and fast streaming service, with multiple servers and links to choose from.
    • -
    • It has a simple and elegant interface, with filters, search bars, ratings, and comments to help you find what you want to watch.
    • -
    • It has a download feature, which allows you to save episodes on your device for offline viewing.
    • -
    -

    How to Use 9Anime

    -

    To use 9Anime, you need to download its APK file from its official website or from a trusted third-party source. Then, you need to install it on your device following the steps mentioned above. After that, you can open the app and start browsing through the anime catalog, select an episode, and start watching or downloading it. You don't need to sign up or log in to use 9Anime, but you can do so if you want to create a profile, add favorites, or leave feedback.

    -

    Anime X Stream

    -

    Features and Benefits of Anime X Stream

    -

    Anime X Stream is a relatively new anime streaming platform that aims to provide a simple and convenient way to watch animes online. Anime X Stream has a minimalist design and a smooth and fast streaming service. Anime X Stream has a decent selection of anime titles, mostly from the recent years. Some of the features and benefits of Anime X Stream are:

    -
      -
    • It has a lightweight and easy-to-use app, with no ads, pop-ups, or redirects.
    • -
    • It has a high-quality video and audio streaming service, with options to change the resolution, subtitles, and language.
    • -
    • It has a basic and clear interface, with categories, genres, trending, and latest to help you find what you want to watch.
    • -
    • It has a download feature, which allows you to save episodes on your device for offline viewing.
    • -
    -

    How to Use Anime X Stream

    -

    To use Anime X Stream, you need to download its APK file from its official website or from a reliable third-party source. Then, you need to install it on your device following the steps mentioned above. After that, you can open the app and start browsing through the anime catalog, select an episode, and start watching or downloading it. You don't need to sign up or log in to use Anime X Stream, but you can do so if you want to create a profile, add favorites, or leave feedback.

    -

    Conclusion and FAQs

    -

    Summary of the Main Points

    -

    In conclusion, anime is a popular form of animation that originated in Japan and has various genres and styles. Anime fans can watch and download their favorite animes online using APKs, which are Android application packages that can be installed on their devices. APKs have some advantages over the apps that are available on the Google Play Store, such as more features, content, and options. Some of the best anime APKs to watch and download animes online are Crunchyroll, 9Anime, and Anime X Stream. These APKs offer high-quality streaming services, offline viewing features, user-friendly interfaces, and large collections of anime titles.

    -

    FAQs

    -

    Here are some frequently asked questions about watching and downloading animes online with APKs:

    -
      -
    1. Are APKs safe to use?
      -APKs are generally safe to use if you download them from trusted sources and scan them for viruses or malware before installing them. However, you should always be careful and cautious when downloading any file from the internet, as there may be some risks or dangers involved.
    2. -
    3. Do I need a VPN to use APKs?
      -A VPN (virtual private network) is a service that encrypts your internet traffic and changes your IP address, making you more anonymous and secure online. A VPN can help you access geo-restricted or censored content, such as some anime streaming platforms or titles. A VPN can also protect you from hackers, trackers, or ISPs (internet service providers) that may monitor your online activities. Therefore, using a VPN is recommended when using APKs, especially if you are in a country or region where anime streaming is illegal or restricted.
    4. -
    5. What are some other anime streaming platforms or apps that I can use?
      -Besides the APKs mentioned in this article, there are some other anime streaming platforms or apps that you can use, such as Funimation, Netflix, Hulu, Amazon Prime Video, AnimeLab, VRV, and Tubi TV. However, some of these platforms or apps may require a subscription fee, a registration, or a VPN to access them.
    6. -
    7. How can I watch anime on my PC or laptop?
      -If you want to watch anime on your PC or laptop, you can either use a web browser to access the official websites of the anime streaming platforms or apps, or use an emulator to run the APKs on your PC or laptop. An emulator is a software that mimics the Android operating system on your PC or laptop, allowing you to install and use Android apps on it. Some of the popular emulators are BlueStacks, NoxPlayer, and LDPlayer.
    8. -
    9. How can I watch anime on my TV?
      -If you want to watch anime on your TV, you can either use a smart TV that has the anime streaming platforms or apps pre-installed or available for download, or use a device that can connect your TV to the internet, such as a Chromecast, a Firestick, a Roku, or an Apple TV. Then, you can either cast or mirror your phone screen to your TV using the device's app, or use a remote control to access the anime streaming platforms or apps on your TV.
    10. -

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Challenge Your Friends in 8 Ball Pool - Free Download from Uptodown.md b/spaces/fatiXbelha/sd/Challenge Your Friends in 8 Ball Pool - Free Download from Uptodown.md deleted file mode 100644 index 96ee250b7ce885374bb272fcb0087795f39c964e..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Challenge Your Friends in 8 Ball Pool - Free Download from Uptodown.md +++ /dev/null @@ -1,222 +0,0 @@ -
    -

    8 Ball Pool Uptodown: A Fun and Challenging Pool Game for Android

    -

    If you love playing pool, you might want to try out 8 Ball Pool Uptodown, a pool game for Android that allows you to play against people from all over the world in turn-based online games. You can also play offline against the computer or with your friends on the same device. In this article, we will tell you everything you need to know about this game, including how to play it, what are its benefits, and what are some tips and tricks to improve your skills. We will also suggest some alternatives to 8 Ball Pool Uptodown in case you want to try something different.

    -

    8 ball pool uptodown


    DOWNLOAD === https://urllie.com/2uNxf3



    -

    What is 8 Ball Pool Uptodown and Why It Is Popular

    -

    8 Ball Pool Uptodown is a pool game for Android that is developed by Miniclip, a leading company in online and mobile games. The game is based on the classic rules of 8-ball pool, which is one of the most popular and widely played cue sports in the world. The game has over 500 million downloads on Google Play Store and has a rating of 4.4 out of 5 stars. It is also available on iOS, Windows Phone, and web browsers.

    -

    One of the reasons why 8 Ball Pool Uptodown is so popular is that it offers a realistic and immersive experience of playing pool on your mobile device. The game has stunning graphics, smooth animations, accurate physics, and easy-to-use controls. You can also customize your cue and table with various designs and colors. The game also has a social aspect, as you can chat with your opponents, join clubs, compete in tournaments, and earn coins and cash that you can use to buy new items.

    -

    Another reason why 8 Ball Pool Uptodown is popular is that it has many benefits for your mental and physical health. Playing pool can help you:

    -
      -
    • Improve your focus: Playing pool requires you to concentrate on your targets, angles, power, and spin. This can help you improve your attention span, memory, and problem-solving skills.
    • -
    • Better your hand-eye coordination: Playing pool involves coordinating your eyes, hands, and body movements. This can help you enhance your motor skills, reflexes, and reaction time.
    • -
    • Strategy building skills: Playing pool requires you to plan ahead, anticipate your opponent's moves, and adapt to different situations. This can help you develop your strategic thinking, creativity, and decision-making skills.
    • -
    • Relax and relieve stress: Playing pool can be a fun and enjoyable way to relax and unwind after a long day. It can also help you release tension, anxiety, and negative emotions.
    • -
    • Heighten cognition: Playing pool involves performing mental mathematical calculations, such as basic geometry and physics. This can help you sharpen your mind, logic, and reasoning skills.
    • -
    • Develop presence of mind: Playing pool requires you to be aware of your surroundings, such as the position of the balls, the cue ball, the pockets, and the rails. This can help you improve your spatial awareness, perception, and observation skills.
    • -
    • Burn calories: Playing pool can also be a good form of physical exercise. According to Health Fitness Revolution, a typical two-hour session of 8-ball or 9-ball pool can provide about - 238 calories, which is equivalent to jogging for 30 minutes or cycling for 40 minutes.
    • -
    -

    How to Play 8 Ball Pool Uptodown

    -

    Now that you know what 8 Ball Pool Uptodown is and why it is beneficial, you might be wondering how to play it. Here are the basic steps to get started:

    -

    How to Download and Install the Game from Uptodown

    -

    Uptodown is a website that offers free and safe downloads of Android apps and games. You can download 8 Ball Pool Uptodown from this link. To install the game, follow these instructions:

    -
      -
    1. Open the downloaded file and tap on Install.
    2. -
    3. Allow the app to access your device's storage, location, and contacts.
    4. -
    5. Wait for the installation to complete and tap on Open.
    6. -
    7. Sign in with your Facebook, Google, or Miniclip account, or play as a guest.
    8. -
    -

    How to Choose Your Game Mode and Table

    -

    Once you have installed the game, you can choose from four game modes: Play Online, Play with Friends, Play Offline, and Practice Offline. Each mode has different options and features:

    - - - - - - - - - - - - - - - - - - - - - -
    Game ModeDescription
    Play OnlineThis mode allows you to play against other players from around the world in real-time. You can choose from three sub-modes: 1 on 1, Tournaments, and 9 Ball Pool. You can also select the table size, entry fee, and prize money. You need coins to enter this mode.
    Play with FriendsThis mode allows you to play with your friends on the same device or online. You can invite your friends via Facebook, WhatsApp, or SMS. You can also create or join a club and chat with other members. You need coins to enter this mode.
    Play OfflineThis mode allows you to play against the computer or with another player on the same device. You can choose from three difficulty levels: Easy, Medium, and Hard. You can also select the table size and rules. You do not need coins to enter this mode.
    Practice OfflineThis mode allows you to practice your skills without any opponent or time limit. You can choose from two sub-modes: Solo or Pass n Play. You can also select the table size and rules. You do not need coins to enter this mode.
    -

    How to Rack the Balls and Break

    -

    After choosing your game mode and table, you are ready to rack the balls and break. Here are the steps to do so:

    -

    8 ball pool uptodown apk download
    -8 ball pool uptodown mod
    -8 ball pool uptodown old version
    -8 ball pool uptodown hack
    -8 ball pool uptodown unlimited coins
    -8 ball pool uptodown android
    -8 ball pool uptodown latest version
    -8 ball pool uptodown ios
    -8 ball pool uptodown pc
    -8 ball pool uptodown online
    -8 ball pool uptodown update
    -8 ball pool uptodown free
    -8 ball pool uptodown app
    -8 ball pool uptodown cheats
    -8 ball pool uptodown game
    -8 ball pool uptodown review
    -8 ball pool uptodown install
    -8 ball pool uptodown play store
    -8 ball pool uptodown tips
    -8 ball pool uptodown tricks
    -8 ball pool uptodown guide
    -8 ball pool uptodown tutorial
    -8 ball pool uptodown multiplayer
    -8 ball pool uptodown offline
    -8 ball pool uptodown best cues
    -8 ball pool uptodown cash generator
    -8 ball pool uptodown rewards
    -8 ball pool uptodown tournaments
    -8 ball pool uptodown challenges
    -8 ball pool uptodown leagues
    -8 ball pool uptodown clubs
    -8 ball pool uptodown pro players
    -8 ball pool uptodown rankings
    -8 ball pool uptodown stats
    -8 ball pool uptodown skins
    -8 ball pool uptodown themes
    -8 ball pool uptodown avatars
    -8 ball pool uptodown stickers
    -8 ball pool uptodown chat packs
    -8 ball pool uptodown spin and win
    -8 ball pool uptodown scratch and win
    -8 ball pool uptodown lucky shot
    -8 ball pool uptodown golden shot
    -8 ball pool uptodown mini games
    -8 ball pool uptodown daily missions
    -8 ball pool uptodown weekly competitions
    -8 ball pool uptodown seasonal events
    -8 ball pool uptodown exclusive offers
    -8 ball pool uptodown vip membership

    -
      -
    1. The game will automatically rack the balls in a triangle shape, with the 8 ball in the center and a solid ball at the apex.
    2. -
    3. The game will randomly decide who will break first. If it is your turn, you can move the cue ball anywhere behind the head string (the line that divides the table into two halves).
    4. -
    5. To break, drag your finger on the screen to aim at the rack of balls. A white line will show you the direction of your shot. You can also adjust the spin of the cue ball by tapping on the cue ball icon on the top left corner of the screen.
    6. -
    7. To shoot, slide the power bar on the right side of the screen up or down to set the power of your shot. Then release your finger to hit the cue ball.
    8. -
    9. If you pocket a ball on the break, you can continue your turn. If you pocket both a solid and a stripe ball on the break, you can choose which type of ball you want to play as. If you do not pocket any ball on the break, your turn ends and your opponent gets to play.
    10. -
    11. If you commit a foul on the break, such as scratching (pocketing the cue ball), jumping (hitting a ball off the table), or not hitting any ball at all, your opponent gets ball in hand (the ability to place the cue ball anywhere on the table).
    12. -
    -

    How to Aim and Shoot the Cue Ball

    -

    After breaking, you need to aim and shoot the cue ball at your target balls (either solids or stripes). Here are some tips on how to do so:

    -
      -
    • To aim, drag your finger on the screen to move the cue stick. A white line will show you where the cue ball will go after hitting your target ball. - A yellow line will show you where your target ball will go after being hit by the cue ball. You can also see the trajectory of the balls on the mini-map on the top right corner of the screen.
    • -
    • To shoot, slide the power bar on the right side of the screen up or down to set the power of your shot. Then release your finger to hit the cue ball.
    • -
    • To use spin, tap on the cue ball icon on the top left corner of the screen. Then drag your finger on the cue ball to apply spin to it. You can use spin to change the direction and speed of the cue ball after hitting a rail or another ball.
    • -
    -

    How to Pocket the Balls and Win the Game

    -

    The objective of 8 Ball Pool Uptodown is to pocket all your balls (either solids or stripes) and then pocket the 8 ball before your opponent does. Here are some rules and tips on how to do so:

    -
      -
    • You must always hit one of your balls first before hitting any other ball. If you hit an opponent's ball or the 8 ball first, you commit a foul and your opponent gets ball in hand.
    • -
    • You must always call your shots before shooting. This means you have to indicate which ball you are going to pocket and in which pocket. If you pocket a ball without calling it, or if you call a wrong shot, you commit a foul and your opponent gets ball in hand.
    • -
    • You can only pocket the 8 ball after pocketing all your balls. If you pocket the 8 ball before clearing your balls, or if you pocket the 8 ball in a wrong pocket, you lose the game.
    • -
    • You can also lose the game if you scratch (pocket the cue ball) while shooting at the 8 ball, or if you jump (hit a ball off the table) while shooting at any ball.
    • -
    • To win the game, you need to pocket the 8 ball in a called pocket without committing any foul or losing condition.
    • -
    -

    Tips and Tricks for 8 Ball Pool Uptodown

    -

    Now that you know how to play 8 Ball Pool Uptodown, you might want to learn some tips and tricks to improve your game and beat your opponents. Here are some of them:

    -

    How to Use Spin and Power Effectively

    -

    Spin and power are two important factors that can affect the outcome of your shots. Here are some tips on how to use them effectively:

    -
      -
    • Use top spin (dragging your finger on the top part of the cue ball) to make the cue ball move forward after hitting a rail or another ball. This can help you position yourself for your next shot or avoid getting snookered (blocked by another ball).
    • -
    • Use back spin (dragging your finger on the bottom part of the cue ball) to make the cue ball move backward after hitting a rail or another ball. This can help you control the distance of your shots or avoid scratching (pocketing the cue ball).
    • -
    • Use left spin (dragging your finger on the left part of the cue ball) to make the cue ball curve to - the left after hitting a rail or another ball. This can help you avoid obstacles or create angles for your shots.
    • -
    • Use right spin (dragging your finger on the right part of the cue ball) to make the cue ball curve to the right after hitting a rail or another ball. This can help you avoid obstacles or create angles for your shots.
    • -
    • Use more power (sliding the power bar higher) to make your shots faster and stronger. This can help you pocket balls more easily or break clusters of balls.
    • -
    • Use less power (sliding the power bar lower) to make your shots slower and softer. This can help you pocket balls more accurately or avoid scratching (pocketing the cue ball).
    • -
    -

    How to Improve Your Focus and Strategy

    -

    Focus and strategy are two essential skills that can help you win more games in 8 Ball Pool Uptodown. Here are some tips on how to improve them:

    -
      -
    • Focus on your aim and shot before shooting. Do not rush or get distracted by your opponent, the chat, or the timer. Take your time to align your cue stick, adjust your spin and power, and visualize the outcome of your shot.
    • -
    • Plan ahead and think several steps ahead. Do not just shoot at the first ball you see. Consider the position of the other balls, the pockets, the rails, and the cue ball. Try to create a sequence of shots that will lead you to pocket all your balls and then the 8 ball.
    • -
    • Analyze your opponent and adapt to their style. Observe how they play, what are their strengths and weaknesses, and what are their tendencies and habits. Try to exploit their mistakes, counter their moves, and surprise them with your shots.
    • -
    • Learn from your mistakes and improve your skills. Do not get frustrated or discouraged by your losses. Instead, review your games, identify what went wrong, and practice how to avoid or correct them. You can also watch replays of other players, especially the ones who are better than you, and learn from their techniques and strategies.
    • -
    -

    How to Avoid Common Mistakes and Fouls

    -

    Mistakes and fouls are inevitable in 8 Ball Pool Uptodown, but they can also cost you the game if you make too many of them. Here are some tips on how to avoid them:

    -
      -
    • Avoid scratching (pocketing the cue ball) by using less power, more spin, or a different angle for your shots. Scratching gives your opponent ball in hand, which means they can place the cue ball anywhere on the table.
    • -
    • Avoid jumping (hitting a ball off the table) by using less power, more spin, or a different angle for your shots. Jumping is considered a foul and gives your opponent ball in hand.
    • -
    • Avoid hitting an opponent's ball or the 8 ball first by aiming carefully, using spin, or changing your target. Hitting an opponent's ball or the 8 ball first is considered a foul and gives your opponent ball in hand.
    • -
    • Avoid pocketing a ball without calling it or calling a wrong shot by paying attention to the rules, being clear about your intentions, and confirming your shots before shooting. Pocketing a ball without calling it or calling a wrong shot is considered a foul and gives your opponent ball in hand.
    • -
    • Avoid pocketing the 8 ball before clearing your balls or in a wrong pocket by being cautious, precise, and patient when shooting at the 8 ball. Pocketing the 8 ball before clearing your balls or in a wrong pocket means you lose the game.
    • -
    -

    Alternatives to 8 Ball Pool Uptodown

    -

    If you want to try something different from 8 Ball Pool Uptodown, there are many other pool games that you can download from Uptodown or other sources. Here are some of them:

    -

    Pool Stars - 3D Online Multiplayer Game

    -

    This game is similar to 8 Ball Pool Uptodown in terms of gameplay, graphics, and features. You can play online against other players in various modes, such as 8-ball pool, 9-ball pool, snooker, carom billiards, and more. You can also customize your cue and table with different styles and colors. The game has over 10 million downloads on Google Play Store and has a rating of 4.2 out of 5 stars.

    -

    Pros

    -
      -
    • The game offers more variety of game modes than 8 Ball Pool Uptodown.
    • -
    • The game has realistic physics and animations that make it more immersive.
    • -
    • The game has daily - challenges and rewards that keep it interesting and rewarding.
    • -
    • The game has a friendly and helpful community that you can chat and interact with.
    • -
    -

    Cons

    -
      -
    • The game requires a stable internet connection to play online.
    • -
    • The game has some bugs and glitches that can affect the gameplay and performance.
    • -
    • The game has some ads and in-app purchases that can be annoying and expensive.
    • -
    -

    Pool Billiards Pro

    -

    This game is a simple and easy-to-play pool game for Android. You can play offline against the computer or with another player on the same device. You can choose from two game modes: 8-ball pool and 9-ball pool. You can also adjust the difficulty level, the table color, and the cue sensitivity. The game has over 100 million downloads on Google Play Store and has a rating of 4.3 out of 5 stars.

    -

    Pros

    -
      -
    • The game is suitable for beginners and casual players who want to play pool without any hassle.
    • -
    • The game does not require an internet connection to play offline.
    • -
    • The game is free to download and play, with no ads or in-app purchases.
    • -
    -

    Cons

    -
      -
    • The game does not offer online multiplayer or social features.
    • -
    • The game has basic graphics and sounds that make it less realistic and immersive.
    • -
    • The game has limited options and features that make it less challenging and varied.
    • -
    -

    Pool Break 3D Billiard Snooker

    -

    This game is a comprehensive and diverse pool game for Android. You can play online or offline in various modes, such as 8-ball pool, 9-ball pool, snooker, carom billiards, crokinole, and more. You can also customize your cue, table, balls, and environment with different options. The game has over 10 million downloads on Google Play Store and has a rating of 4.1 out of 5 stars.

    -

    Pros

    -
      -
    • The game offers a wide range of game modes and options that make it more fun and versatile.
    • -
    • The game has realistic graphics, physics, and sounds that make it more immersive and enjoyable.
    • -
    • The game has online multiplayer and chat features that make it more social and competitive.
    • -
    -

    Cons

    -
      -
    • The game requires a good device and internet connection to run smoothly.
    • -
    • The game has some ads and in-app purchases that can be intrusive and costly.
    • -
    • The game has a steep learning curve and complex controls that make it difficult for some players.
    • -
    -

    Conclusion

    -

    In conclusion, 8 Ball Pool Uptodown is a fun and challenging pool game for Android that you can play online or offline with your friends or strangers. The game has many benefits for your mental and physical health, such as improving your focus, strategy, hand-eye coordination, cognition, presence of mind, and relaxation. The game also has some tips and tricks that you can use to improve your skills and avoid mistakes and fouls. The game also has some alternatives that you can try if you want to experience something different from 8 Ball Pool Uptodown. We hope this article has helped you learn more about this game and how to play it better. Have fun playing pool!

    -

    FAQs

    -

    Here are some frequently asked questions about 8 Ball Pool Uptodown:

    -

    Q: How do I get more coins in 8 Ball Pool Uptodown?

    -

    A: You can get more coins in 8 Ball Pool Uptodown by:

    -
      -
    • Winning games online or offline.
    • -
    • Spinning the wheel of fortune every day.
    • -
    • Watching video ads or completing offers.
    • -
    • Buying coins with real money or cash (the premium currency).
    • -
    -

    Q: How do I level up in 8 Ball Pool Uptodown?

    -

    A: You can level up in 8 Ball Pool Uptodown by earning experience points (XP) from playing games online or offline. The more XP you earn, the higher your level will be. Leveling up will unlock new tables, cues, chat packs, avatars, and achievements.

    -

    Q: How do I join or create a club in 8 Ball Pool Uptodown?

    -

    A: You can join or create a club in 8 Ball Pool Uptodown by tapping on the club icon on the bottom left corner of the screen. Then - you can either search for an existing club to join or create your own club by tapping on the plus icon. To join or create a club, you need to have at least 100 coins. Clubs are groups of players who can chat, play, and compete together. You can also earn club points and rewards by playing games with your club members.

    -

    Q: How do I play 9 Ball Pool in 8 Ball Pool Uptodown?

    -

    A: You can play 9 Ball Pool in 8 Ball Pool Uptodown by selecting the Play Online mode and then tapping on the 9 Ball Pool option. 9 Ball Pool is a game mode where you have to pocket the balls in numerical order, from 1 to 9. The first player to pocket the 9 ball wins the game. You can also call your shots and use the golden break (pocketing the 9 ball on the break) to win instantly.

    -

    Q: How do I contact the support team of 8 Ball Pool Uptodown?

    -

    A: You can contact the support team of 8 Ball Pool Uptodown by tapping on the settings icon on the top right corner of the screen and then tapping on Help and Support. You can also visit this link to access the FAQ, submit a request, or chat with an agent.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download Beach Buggy Racing Mod APK for Free and Get Unlimited Money to Upgrade Your Buggy.md b/spaces/fatiXbelha/sd/Download Beach Buggy Racing Mod APK for Free and Get Unlimited Money to Upgrade Your Buggy.md deleted file mode 100644 index da5946be03d4542a36347d993f64ae199eb8aae6..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download Beach Buggy Racing Mod APK for Free and Get Unlimited Money to Upgrade Your Buggy.md +++ /dev/null @@ -1,81 +0,0 @@ -
    -

    Download Beach Buggy Racing Mod APK Unlimited Money

    -

    Do you love racing games? Do you want to experience the thrill of driving a buggy on a sandy beach? If yes, then you should try Beach Buggy Racing, a fun and addictive racing game for Android devices. In this game, you can choose from a variety of buggies, each with its own unique abilities and power-ups, and compete with other players in different tracks and modes. You can also customize your buggy with paint, stickers, and accessories, and upgrade your engine, tires, suspension, and more.

    -

    But what if you want to enjoy the game without any limitations? What if you want to have unlimited money to buy and upgrade your buggies, unlock all the tracks and modes, and access all the features of the game? Well, there is a way to do that. You can download the Beach Buggy Racing Mod APK, a modified version of the game that gives you unlimited money and other perks. In this article, we will tell you everything you need to know about Beach Buggy Racing Mod APK, including its features, how to download and install it, and some tips and tricks for playing the game. Let's get started!

    -

    download beach buggy racing mod apk unlimited money


    DOWNLOADhttps://urllie.com/2uNzNG



    -

    Features of Beach Buggy Racing Mod APK

    -

    The Beach Buggy Racing Mod APK is not just a regular version of the game. It has some amazing features that make it more enjoyable and exciting. Here are some of them:

    -
      -
    • Unlimited money: With this feature, you can buy and upgrade any buggy you want, without worrying about the cost. You can also unlock all the tracks and modes, and enjoy the game to the fullest.
    • -
    • All buggies unlocked: With this feature, you can choose from over 25 buggies, each with its own unique abilities and power-ups. You can drive a monster truck, a muscle car, a lunar rover, a pirate ship, and more.
    • -
    • All tracks unlocked: With this feature, you can race on over 15 tracks, each with its own challenges and surprises. You can race on beaches, jungles, volcanoes, swamps, caves, and more.
    • -
    • All modes unlocked: With this feature, you can play in different modes, each with its own rules and objectives. You can play in career mode, quick race mode, daily challenge mode, split screen mode, and more.
    • -
    • No ads: With this feature, you can enjoy the game without any interruptions or distractions. You can focus on your racing skills and have fun.
    • -
    -

    How to download and install Beach Buggy Racing Mod APK

    -

    Downloading and installing Beach Buggy Racing Mod APK is very easy. Just follow these simple steps:

    -
      -
    1. Click on this link to download the Beach Buggy Racing Mod APK file.
    2. -
    3. Once the download is complete, go to your device's settings and enable the installation of apps from unknown sources.
    4. -
    5. Locate the downloaded file in your device's file manager and tap on it to start the installation process.
    6. -
    7. Follow the instructions on the screen and wait for the installation to finish.
    8. -
    9. Launch the game from your app drawer and enjoy!
    10. -
    -

    Note: You may need to uninstall the original version of Beach Buggy Racing before installing the mod apk version.

    -

    Tips and tricks for playing Beach Buggy Racing

    -

    Now that you have downloaded and installed Beach Buggy Racing Mod APK, you are ready to play the game. But before you do that, here are some tips and tricks that will help you master the game and win races: - Experiment with different buggies and power-ups: Each buggy has its own strengths and weaknesses, and each power-up has its own effects and duration. Try to find the best combination for each track and mode, and use them wisely. - Collect coins and gems: Coins and gems are the currency of the game, and you can use them to buy and upgrade your buggies, unlock new tracks and modes, and access other features of the game. You can earn coins and gems by winning races, completing challenges, and finding hidden treasures. - Drift and boost: Drifting and boosting are two essential skills for racing. Drifting allows you to turn corners faster and fill up your boost meter, while boosting gives you a burst of speed and helps you overtake your opponents. To drift, tap and hold the brake button while turning, and to boost, tap the boost button when your meter is full. - Use shortcuts and secrets: Some tracks have shortcuts and secrets that can give you an advantage over your rivals. Look for ramps, tunnels, bridges, and other hidden paths that can save you time or help you avoid obstacles. Be careful though, some shortcuts may also have traps or hazards that can slow you down or damage your buggy. - Watch out for hazards and enemies: The tracks are not only filled with shortcuts and secrets, but also with hazards and enemies that can ruin your race. Watch out for rocks, trees, animals, bombs, missiles, and other obstacles that can block your way or damage your buggy. Also, be aware of your opponents' power-ups and attacks, and try to dodge or counter them.

    Conclusion

    -

    Beach Buggy Racing is a fun and addictive racing game that will keep you entertained for hours. You can download the Beach Buggy Racing Mod APK to enjoy the game without any limitations, and have unlimited money and other perks. You can also follow our tips and tricks to master the game and win races. So what are you waiting for? Download Beach Buggy Racing Mod APK now and start racing!

    -

    Download Beach Buggy Racing Mod Apk Free
    -How to Install Beach Buggy Racing Mod Apk with Unlimited Money
    -Beach Buggy Racing Mod Apk Latest Version 2021.10.05
    -Beach Buggy Racing Hack Apk Download for Android
    -Beach Buggy Racing Unlimited Coins and Gems Mod Apk
    -Beach Buggy Racing Mod Apk Offline No Root
    -Beach Buggy Racing Mod Apk All Cars Unlocked
    -Beach Buggy Racing 2 Mod Apk Unlimited Money Download
    -Download Beach Buggy Racing Mod Apk for PC Windows 10/8/7
    -Beach Buggy Racing Mod Apk OBB Data Download
    -Beach Buggy Racing Mod Apk Online Multiplayer
    -Beach Buggy Racing Mod Apk VIP Unlocked
    -Download Beach Buggy Racing Mod Apk from Google Play Store
    -Beach Buggy Racing Mod Apk No Ads
    -Beach Buggy Racing Mod Apk Cheat Codes
    -Beach Buggy Racing Mod Apk Review and Rating
    -Beach Buggy Racing Mod Apk Gameplay and Features
    -Beach Buggy Racing Mod Apk Tips and Tricks
    -Beach Buggy Racing Mod Apk Best Settings
    -Beach Buggy Racing Mod Apk Comparison with Original Game
    -Download Beach Buggy Racing Mod Apk for iOS iPhone/iPad
    -Beach Buggy Racing Mod Apk Requirements and Compatibility
    -Beach Buggy Racing Mod Apk Download Link and QR Code
    -Beach Buggy Racing Mod Apk Update and Patch Notes
    -Beach Buggy Racing Mod Apk Troubleshooting and Support
    -Download Beach Buggy Racing Mod Apk for Mac OS X
    -Beach Buggy Racing Mod Apk Customization and Skins
    -Beach Buggy Racing Mod Apk Achievements and Leaderboards
    -Beach Buggy Racing Mod Apk Fun Facts and Easter Eggs
    -Beach Buggy Racing Mod Apk FAQs and Answers
    -Download Beach Buggy Racing Mod Apk for Linux Ubuntu/Debian/Fedora
    -Beach Buggy Racing Mod Apk Soundtrack and Music
    -Beach Buggy Racing Mod Apk Graphics and Performance Optimization
    -Beach Buggy Racing Mod Apk Mods and Add-ons
    -Beach Buggy Racing Mod Apk Alternatives and Similar Games
    -Download Beach Buggy Racing Mod Apk for Chrome OS/Chromebook
    -Beach Buggy Racing Mod Apk Developer and Publisher Information
    -Beach Buggy Racing Mod Apk License and Terms of Use
    -Beach Buggy Racing Mod Apk Feedback and Suggestions
    -Download Beach Buggy Racing Mod Apk for Kindle Fire/Fire TV/Fire Tablet

    -

    FAQs

    -

    Here are some of the most frequently asked questions about Beach Buggy Racing Mod APK:

    -

    Is Beach Buggy Racing Mod APK safe to download?

    -

    Yes, Beach Buggy Racing Mod APK is safe to download as long as you use a trusted source like . However, you should always scan any file you download with an antivirus software before installing it on your device.

    -

    Do I need to root my device to use Beach Buggy Racing Mod APK?

    -

    No, you do not need to root your device to use Beach Buggy Racing Mod APK. You just need to enable the installation of apps from unknown sources in your device's settings.

    -

    Will Beach Buggy Racing Mod APK work on my device?

    -

    Beach Buggy Racing Mod APK should work on any Android device that meets the minimum requirements of the game. The minimum requirements are Android 4.1 or higher, 1 GB of RAM, and 100 MB of free storage space.

    -

    Can I play Beach Buggy Racing online with other players?

    -

    Yes, you can play Beach Buggy Racing online with other players in split screen mode or multiplayer mode. However, you may not be able to join some servers or matches if they detect that you are using a mod apk version of the game.

    -

    Can I update Beach Buggy Racing Mod APK?

    -

    Yes, you can update Beach Buggy Racing Mod APK whenever a new version of the game is released. However, you may need to uninstall the previous version of the mod apk before installing the new one.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download Summertime Saga 0.17 APK for Android Enjoy the Spicy Visual Novel with Mod APK Features.md b/spaces/fatiXbelha/sd/Download Summertime Saga 0.17 APK for Android Enjoy the Spicy Visual Novel with Mod APK Features.md deleted file mode 100644 index 0c371500a4b58743555fe015fb410b8205835695..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download Summertime Saga 0.17 APK for Android Enjoy the Spicy Visual Novel with Mod APK Features.md +++ /dev/null @@ -1,155 +0,0 @@ - -

    Summertime Saga 0.17 APK Download for Android Mod APK

    -

    If you are looking for a fun and exciting game to spice up your summer, you might want to check out Summertime Saga 0.17 APK for Android Mod APK. This is a popular visual novel game that has been downloaded by millions of players around the world. In this game, you will become a student in a high school full of mysteries, romance, and adventure. You will have to deal with your father's death, your family's debt to the mafia, and your love life. You will also have to make choices that will affect the outcome of the story and your relationships with other characters.

    -

    summertime saga 0.17 apk download for android mod apk


    Download Filehttps://urllie.com/2uNvIE



    -

    In this article, we will tell you everything you need to know about Summertime Saga 0.17 APK for Android Mod APK, including what it is, what's new in this version, how to download and install it, and how to use the mod features. We will also answer some frequently asked questions about the game. So, without further ado, let's get started.

    -

    What is Summertime Saga?

    -

    Summertime Saga is a visual novel game developed by DarkCookie and his team. It is available for Windows, Mac, Linux, Android, and iOS devices. The game is free to play, but you can support the developers by becoming a patron on Patreon.

    -

    Summertime Saga is not your typical visual novel game. It has some elements that make it stand out from the rest, such as:

    -

    A spicy visual novel with a twist

    -

    Summertime Saga is not for the faint of heart. It contains adult themes, sexual content, nudity, violence, and profanity. The game is rated 18+ and is intended for mature audiences only. If you are easily offended or uncomfortable with such content, you might want to skip this game.

    -

    However, if you are looking for a game that can make you laugh, cry, blush, and feel butterflies in your stomach, Summertime Saga might be the perfect choice for you. The game has a lot of humor, drama, suspense, and romance that will keep you hooked until the end.

    -

    A rich and immersive story with multiple endings

    -

    Summertime Saga has a captivating story that will make you feel like you are part of it. The game follows the life of a young man who has just lost his father in a mysterious accident. He inherits his father's debt to the mafia and has to find a way to pay it off. He also has to deal with his school life, his family issues, and his love interests.

    -

    The game has over 65 characters that you can interact with and form relationships with. Each character has their own personality, backstory, and secrets that you can discover by talking to them and doing quests for them. You can also date some of them and experience romantic scenes with them.

    -

    summertime saga 0.17 apk mod android free download
    -download summertime saga 0.17 apk for android modded version
    -summertime saga 0.17 android apk mod unlimited money
    -summertime saga 0.17 mod apk android offline download
    -summertime saga 0.17 apk download mod android latest update
    -summertime saga 0.17 apk mod android unlocked all features
    -summertime saga 0.17 mod apk download for android no root
    -summertime saga 0.17 android apk mod mega cheats
    -summertime saga 0.17 apk mod android full game
    -download summertime saga 0.17 mod apk for android free
    -summertime saga 0.17 apk mod android high graphics
    -summertime saga 0.17 mod apk android easy install
    -summertime saga 0.17 android apk mod premium choices
    -summertime saga 0.17 mod apk download android direct link
    -summertime saga 0.17 apk mod android no ads
    -summertime saga 0.17 android apk mod hack version
    -summertime saga 0.17 mod apk android best visual novel
    -summertime saga 0.17 apk download mod android new characters
    -summertime saga 0.17 apk mod android fast download speed
    -summertime saga 0.17 mod apk android safe and secure
    -summertime saga 0.17 android apk mod low storage requirement
    -summertime saga 0.17 mod apk download for android latest version
    -summertime saga 0.17 apk mod android compatible devices
    -summertime saga 0.17 android apk mod english language
    -summertime saga 0.17 mod apk android gameplay tips and tricks
    -download summertime saga 0.17 apk for android with mod menu
    -summertime saga 0.17 apk mod android unlimited energy and coins
    -summertime saga 0.17 mod apk android online multiplayer mode
    -summertime saga 0.17 android apk mod realistic graphics and sound effects
    -summertime saga 0.17 mod apk download for android with obb data file
    -summertime saga 0.17 apk mod android fun and spicy story
    -summertime saga 0.17 android apk mod unlock all locations and outfits
    -summertime saga 0.17 mod apk android smooth and bug-free performance
    -summertime saga 0.17 apk download mod android with walkthrough guide
    -summertime saga 0.17 apk mod android support all screen resolutions
    -summertime saga 0.17 android apk mod customize your character and romance options
    -summertime saga 0.17 mod apk download for android with unlimited save slots
    -summertime saga 0.17 apk mod android no internet connection required
    -summertime saga 0.17 android apk mod daily rewards and achievements
    -summertime saga 0.17 mod apk download for android from official website [^1^]

    -

    The game has multiple endings depending on your choices and actions throughout the game. You can have a happy ending with your true love, a tragic ending with your enemies, or anything in between.

    -

    A huge variety of characters and locations to explore

    -

    Summertime Saga has a large and detailed world that you can explore at your own pace. The game has over 30 locations that you can visit, such as your home, your school, the beach, the park, the mall, the hospital, the police station, the library, the gym, the cinema, the tattoo parlor, the strip club, and more.

    -

    The game also has over 200 items that you can collect, use , or sell, such as clothes, accessories, gadgets, books, food, drinks, drugs, weapons, and more.

    -

    The game also has many mini-games that you can play to earn money, improve your skills, or have fun, such as fishing, darts, shooting, racing, boxing, basketball, poker, blackjack, and more.

    -

    What's new in Summertime Saga 0.17?

    -

    Summertime Saga 0.17 is the latest version of the game that was released on December 25, 2022. It is a major update that adds a lot of new content and features to the game. Some of the highlights of this update are:

    -

    New features and improvements

    -

    Summertime Saga 0.17 has some new features and improvements that make the game more enjoyable and user-friendly. Some of them are:

    -
      -
    • A new user interface that is more modern and sleek.
    • -
    • A new map system that allows you to fast travel to any location you have visited before.
    • -
    • A new inventory system that lets you sort and filter your items by category.
    • -
    • A new phone system that lets you call and text your contacts, check your messages, take selfies, and access apps.
    • -
    • A new save system that lets you create multiple save files and name them.
    • -
    • A new cheat menu that lets you unlock all the content and features of the game with a single click.
    • -
    • A new gallery system that lets you view all the scenes and animations you have unlocked in the game.
    • -
    • A new settings menu that lets you customize your game preferences, such as sound, language, graphics, and more.
    • -
    -

    New events and quests

    -

    Summertime Saga 0.17 has some new events and quests that add more depth and variety to the game. Some of them are:

    -
      -
    • A new main story event that involves your father's death and the mafia.
    • -
    • A new side story event that involves your aunt Diane and her farm.
    • -
    • A new character event that involves your teacher Miss Bissette and her French lessons.
    • -
    • A new character event that involves your classmate Eve and her punk band.
    • -
    • A new character event that involves your neighbor Jenny and her webcam show.
    • -
    • A new character event that involves your friend Erik and his stepmother Mrs. Johnson.
    • -
    • A new character event that involves your friend Kevin and his sister Mia.
    • -
    -

    New scenes and animations

    -

    Summertime Saga 0.17 has some new scenes and animations that add more spice and excitement to the game. Some of them are:

    -
      -
    • A new scene with Roxxy at the beach.
    • -
    • A new scene with Judith at the locker room.
    • -
    • A new scene with Becca and Missy at the tattoo parlor.
    • -
    • A new scene with Debbie at the shower.
    • -
    • A new scene with Diane at the barn.
    • -
    • A new scene with Miss Bissette at her office.
    • -
    • A new scene with Eve at the garage.
    • -
    • A new scene with Jenny at her room.
    • -
    • A new scene with Mrs. Johnson at her bedroom.
    • -
    • A new scene with Mia at her bathroom.
    • -
    -

    How to download and install Summertime Saga 0.17 APK for Android Mod APK?

    If you want to download and install Summertime Saga 0.17 APK for Android Mod APK, you will need to follow some simple steps. However, before you do that, you should be aware of some requirements and precautions that you need to take.

    -

    Requirements and precautions

    -

    To download and install Summertime Saga 0.17 APK for Android Mod APK, you will need:

    -
      -
    • An Android device that runs on Android 4.4 or higher.
    • -
    • At least 2 GB of free storage space on your device.
    • -
    • A stable internet connection to download the game file.
    • -
    • A file manager app to access the downloaded file.
    • -
    -

    However, before you download and install Summertime Saga 0.17 APK for Android Mod APK, you should also take some precautions, such as:

    -
      -
    • Make sure that your device is fully charged or plugged in to avoid any interruptions during the installation process.
    • -
    • Make sure that you have backed up your data and settings in case something goes wrong during the installation process.
    • -
    • Make sure that you have enabled the installation of apps from unknown sources on your device. To do this, go to Settings > Security > Unknown Sources and toggle it on.
    • -
    • Make sure that you have downloaded the game file from a trusted and reliable source. There are many fake and malicious websites that claim to offer the game file, but they might contain viruses or malware that can harm your device or steal your personal information. We recommend that you download the game file from the official website of Summertime Saga or from a reputable third-party website.
    • -
    -

    Steps to download and install

    -

    Once you have met the requirements and taken the precautions, you can proceed to download and install Summertime Saga 0.17 APK for Android Mod APK by following these steps:

    -
      -
    1. Go to the official website of Summertime Saga or a reputable third-party website that offers the game file. You can use your browser app or any other app that can access the internet.
    2. -
    3. Find and click on the download link for Summertime Saga 0.17 APK for Android Mod APK. The download link should be clearly labeled and easy to find.
    4. -
    5. Wait for the download to complete. The game file is about 800 MB in size, so it might take some time depending on your internet speed and connection quality.
    6. -
    7. Once the download is complete, locate the downloaded file on your device. You can use your file manager app or any other app that can access your storage.
    8. -
    9. Tap on the downloaded file to start the installation process. You might see a pop-up window asking for your permission to install the app. Tap on Install and wait for the installation to finish.
    10. -
    11. Once the installation is complete, you can launch the game by tapping on its icon on your home screen or app drawer. You might see another pop-up window asking for your permission to access your device's storage. Tap on Allow and enjoy the game.
    12. -
    -

    How to use the mod features

    -

    Summertime Saga 0.17 APK for Android Mod APK is a modified version of the original game that offers some extra features and benefits that are not available in the original game. Some of these features are:

    -
      -
    • Unlimited money: You will have unlimited money in the game, which you can use to buy anything you want, such as clothes, items, gifts, etc.
    • -
    • Unlocked content: You will have access to all the content and features of the game, such as characters, locations, events, quests, scenes, animations, etc., without having to unlock them by playing the game.
    • -
    • Cheat menu: You will have access to a cheat menu that lets you manipulate various aspects of the game, such as your stats, skills, inventory, relationships, etc., with a single click.
    • -
    -

    To use these mod features, you will need to do the following:

    -
      -
    1. Launch the game and start a new game or load an existing game.
    2. -
    3. To access the cheat menu, tap on your phone icon on the top right corner of the screen. Then tap on Settings > Cheats and toggle it on.
    4. -
    5. To use unlimited money, tap on your wallet icon on the top left corner of the screen. You will see that you have $999999 in your account.
    6. -
    7. To access unlocked content, tap on your map icon on the top right corner of the screen. You will see that all the locations are available for you to visit. You can also talk to any character and trigger any event or quest without any restrictions.
    8. -
    - Conclusion -

    Summertime Saga 0.17 APK for Android Mod APK is a great game for anyone who loves visual novels, romance, adventure, and adult content. The game has a lot of features and content that will keep you entertained and engaged for hours. You can download and install the game easily and enjoy the mod features that make the game more fun and convenient. However, you should also be careful and responsible when playing the game, as it is not suitable for minors or sensitive people.

    -

    If you are interested in Summertime Saga 0.17 APK for Android Mod APK, you can download it from the link below and start your summer saga today.

    -

    FAQs

    -

    Here are some frequently asked questions about Summertime Saga 0.17 APK for Android Mod APK:

    -

    Q: Is Summertime Saga 0.17 APK for Android Mod APK safe to download and install?

    -

    A: Yes, as long as you download it from a trusted and reliable source, such as the official website of Summertime Saga or a reputable third-party website. However, you should also scan the file with an antivirus app before installing it to make sure it is free of viruses or malware.

    -

    Q: Is Summertime Saga 0.17 APK for Android Mod APK legal to play?

    -

    A: Yes, as long as you are of legal age in your country and you do not violate any laws or regulations regarding the use of such games. However, you should also respect the rights and preferences of other people and do not share or distribute the game or its content without the permission of the developers or the owners.

    -

    Q: How can I update Summertime Saga 0.17 APK for Android Mod APK to the latest version?

    -

    A: You can update Summertime Saga 0.17 APK for Android Mod APK by downloading and installing the latest version of the game file from the same source where you downloaded the previous version. However, you should also backup your save files before updating to avoid losing your progress or data.

    -

    Q: How can I contact the developers or report a bug or a problem with Summertime Saga 0.17 APK for Android Mod APK?

    -

    A: You can contact the developers or report a bug or a problem with Summertime Saga 0.17 APK for Android Mod APK by visiting their official website, their Patreon page, their Discord server, their Reddit page, or their Twitter account. You can also leave a comment or a review on the website where you downloaded the game file.

    -

    Q: How can I support the developers of Summertime Saga 0.17 APK for Android Mod APK?

    -

    A: You can support the developers of Summertime Saga 0.17 APK for Android Mod APK by becoming a patron on their Patreon page, where you can donate money and get access to exclusive content and rewards. You can also support them by sharing and promoting their game on social media, forums, blogs, or other platforms.

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Dragon Ball Raging Blast 2 - Download Now and Unleash Your Power on Xbox 360.md b/spaces/fatiXbelha/sd/Dragon Ball Raging Blast 2 - Download Now and Unleash Your Power on Xbox 360.md deleted file mode 100644 index fd85d7088c7121a33a760b1fce8e658aa8341c9c..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Dragon Ball Raging Blast 2 - Download Now and Unleash Your Power on Xbox 360.md +++ /dev/null @@ -1,24 +0,0 @@ -
    -

    Dragon Ball: Raging Blast 2 Xbox 360 Download

    -

    If you are a fan of the Dragon Ball Z anime and manga series, you might be interested in downloading Dragon Ball: Raging Blast 2 for your Xbox 360 console. This is a fast-paced, hard-hitting, and intense versus battle game that lets you unleash the rage within. In this article, we will tell you what this game is about, why you should download it, what features it offers, and how to download it from different sources.

    -

    Introduction

    -

    What is Dragon Ball: Raging Blast 2?

    -

    Dragon Ball: Raging Blast 2 is a fighting video game developed by Spike and published by Bandai Namco Entertainment. It was released in November 2010 for the Xbox 360 and PlayStation 3 platforms. It is the sequel to Dragon Ball: Raging Blast, which was released in 2009. The game is based on the Dragon Ball Z anime and manga series, which follows the adventures of Goku and his friends as they fight against various enemies and villains.

    -

    dragon ball raging blast 2 xbox 360 download


    Download Ziphttps://urllie.com/2uNBv3



    -

    Why should you download it?

    -

    If you love Dragon Ball Z, you will enjoy playing Dragon Ball: Raging Blast 2. This game allows you to control your favorite characters and transformations from the series, such as Super Saiyan Goku, Kid Buu, Demon King Dabura, or Ultimate Gohan. You can also experience new game modes and online battles, as well as watch an exclusive anime remake that is included in the game. The game has received positive reviews from critics and fans alike, who praised its gameplay, graphics, sound, and content.

    -

    Features of Dragon Ball: Raging Blast 2

    -

    Over 90 playable characters and transformations

    -

    One of the main attractions of Dragon Ball: Raging Blast 2 is its large roster of playable characters and transformations. The game features over 90 characters from the Dragon Ball Z series, each with their own unique moves, abilities, and styles. You can also unlock and use different transformations for your characters, such as Super Saiyan, Super Saiyan 2, Super Saiyan 3, Super Saiyan God, Majin Buu, Golden Frieza, or Broly Legendary Super Saiyan. You can mix and match your characters and transformations to create your own custom teams and combos.

    -

    Enhanced graphics and animations

    -

    Another feature of Dragon Ball: Raging Blast 2 is its improved graphics and animations. The game uses a cel-shaded style that mimics the look of the anime. The characters are detailed and expressive, the environments are colorful and destructible, and the effects are flashy and realistic. The game also uses motion capture technology to make the movements of the characters more fluid and natural. The game runs at a smooth frame rate and supports high-definition resolution.

    -

    New game modes and online battles

    -

    Dragon Ball: Raging Blast 2 also offers new game modes and online battles for more variety and challenge. The game has a story mode called Galaxy Mode, where you can follow the individual stories of each character and unlock new items and abilities. The game also has a Battle Zone mode, where you can fight against different opponents with different rules and conditions. The game also supports online multiplayer mode, where you can compete with other players around the world in ranked or unranked matches. You can also create your own custom matches with your own settings.

    -

    Exclusive anime remake included

    -

    A unique feature of Dragon Ball: Raging Blast 2 thanks to the backward compatibility feature of these consoles. However, you will need to have the game disc or the digital version of the game on your account. -

  • Q: What is the difference between Dragon Ball: Raging Blast and Dragon Ball: Raging Blast 2?
  • -
  • A: Dragon Ball: Raging Blast 2 is the sequel to Dragon Ball: Raging Blast. It has more characters and transformations, better graphics and animations, new game modes and online battles, and an exclusive anime remake. It also has some changes in the gameplay mechanics, such as the removal of the story mode and the addition of the Raging Soul mode.
  • - -

    I hope this article has answered your questions and helped you download Dragon Ball: Raging Blast 2 for your Xbox 360. If you have any feedback or suggestions, please let me know in the comments section below. Thank you for reading and have a great day!

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/fb700/chatglm-fitness-RLHF/request_llm/bridge_stackclaude.py b/spaces/fb700/chatglm-fitness-RLHF/request_llm/bridge_stackclaude.py deleted file mode 100644 index c674a8bfe9d022b6e2b6359e5327b47596a53c68..0000000000000000000000000000000000000000 --- a/spaces/fb700/chatglm-fitness-RLHF/request_llm/bridge_stackclaude.py +++ /dev/null @@ -1,275 +0,0 @@ -from .bridge_newbing import preprocess_newbing_out, preprocess_newbing_out_simple -from multiprocessing import Process, Pipe -from toolbox import update_ui, get_conf, trimmed_format_exc -import threading -import importlib -import logging -import time -from toolbox import get_conf -import asyncio -load_message = "正在加载Claude组件,请稍候..." - -try: - """ - ======================================================================== - 第一部分:Slack API Client - https://github.com/yokonsan/claude-in-slack-api - ======================================================================== - """ - - from slack_sdk.errors import SlackApiError - from slack_sdk.web.async_client import AsyncWebClient - - class SlackClient(AsyncWebClient): - """SlackClient类用于与Slack API进行交互,实现消息发送、接收等功能。 - - 属性: - - CHANNEL_ID:str类型,表示频道ID。 - - 方法: - - open_channel():异步方法。通过调用conversations_open方法打开一个频道,并将返回的频道ID保存在属性CHANNEL_ID中。 - - chat(text: str):异步方法。向已打开的频道发送一条文本消息。 - - get_slack_messages():异步方法。获取已打开频道的最新消息并返回消息列表,目前不支持历史消息查询。 - - get_reply():异步方法。循环监听已打开频道的消息,如果收到"Typing…_"结尾的消息说明Claude还在继续输出,否则结束循环。 - - """ - CHANNEL_ID = None - - async def open_channel(self): - response = await self.conversations_open(users=get_conf('SLACK_CLAUDE_BOT_ID')[0]) - self.CHANNEL_ID = response["channel"]["id"] - - async def chat(self, text): - if not self.CHANNEL_ID: - raise Exception("Channel not found.") - - resp = await self.chat_postMessage(channel=self.CHANNEL_ID, text=text) - self.LAST_TS = resp["ts"] - - async def get_slack_messages(self): - try: - # TODO:暂时不支持历史消息,因为在同一个频道里存在多人使用时历史消息渗透问题 - resp = await self.conversations_history(channel=self.CHANNEL_ID, oldest=self.LAST_TS, limit=1) - msg = [msg for msg in resp["messages"] - if msg.get("user") == get_conf('SLACK_CLAUDE_BOT_ID')[0]] - return msg - except (SlackApiError, KeyError) as e: - raise RuntimeError(f"获取Slack消息失败。") - - async def get_reply(self): - while True: - slack_msgs = await self.get_slack_messages() - if len(slack_msgs) == 0: - await asyncio.sleep(0.5) - continue - - msg = slack_msgs[-1] - if msg["text"].endswith("Typing…_"): - yield False, msg["text"] - else: - yield True, msg["text"] - break -except: - pass - -""" -======================================================================== -第二部分:子进程Worker(调用主体) -======================================================================== -""" - - -class ClaudeHandle(Process): - def __init__(self): - super().__init__(daemon=True) - self.parent, self.child = Pipe() - self.claude_model = None - self.info = "" - self.success = True - self.local_history = [] - self.check_dependency() - if self.success: - self.start() - self.threadLock = threading.Lock() - - def check_dependency(self): - try: - self.success = False - import slack_sdk - self.info = "依赖检测通过,等待Claude响应。注意目前不能多人同时调用Claude接口(有线程锁),否则将导致每个人的Claude问询历史互相渗透。调用Claude时,会自动使用已配置的代理。" - self.success = True - except: - self.info = "缺少的依赖,如果要使用Claude,除了基础的pip依赖以外,您还需要运行`pip install -r request_llm/requirements_slackclaude.txt`安装Claude的依赖,然后重启程序。" - self.success = False - - def ready(self): - return self.claude_model is not None - - async def async_run(self): - await self.claude_model.open_channel() - while True: - # 等待 - kwargs = self.child.recv() - question = kwargs['query'] - history = kwargs['history'] - - # 开始问问题 - prompt = "" - - # 问题 - prompt += question - print('question:', prompt) - - # 提交 - await self.claude_model.chat(prompt) - - # 获取回复 - async for final, response in self.claude_model.get_reply(): - if not final: - print(response) - self.child.send(str(response)) - else: - # 防止丢失最后一条消息 - slack_msgs = await self.claude_model.get_slack_messages() - last_msg = slack_msgs[-1]["text"] if slack_msgs and len(slack_msgs) > 0 else "" - if last_msg: - self.child.send(last_msg) - print('-------- receive final ---------') - self.child.send('[Finish]') - - def run(self): - """ - 这个函数运行在子进程 - """ - # 第一次运行,加载参数 - self.success = False - self.local_history = [] - if (self.claude_model is None) or (not self.success): - # 代理设置 - proxies, = get_conf('proxies') - if proxies is None: - self.proxies_https = None - else: - self.proxies_https = proxies['https'] - - try: - SLACK_CLAUDE_USER_TOKEN, = get_conf('SLACK_CLAUDE_USER_TOKEN') - self.claude_model = SlackClient(token=SLACK_CLAUDE_USER_TOKEN, proxy=self.proxies_https) - print('Claude组件初始化成功。') - except: - self.success = False - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] 不能加载Claude组件。{tb_str}') - self.child.send('[Fail]') - self.child.send('[Finish]') - raise RuntimeError(f"不能加载Claude组件。") - - self.success = True - try: - # 进入任务等待状态 - asyncio.run(self.async_run()) - except Exception: - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] Claude失败 {tb_str}.') - self.child.send('[Fail]') - self.child.send('[Finish]') - - def stream_chat(self, **kwargs): - """ - 这个函数运行在主进程 - """ - self.threadLock.acquire() - self.parent.send(kwargs) # 发送请求到子进程 - while True: - res = self.parent.recv() # 等待Claude回复的片段 - if res == '[Finish]': - break # 结束 - elif res == '[Fail]': - self.success = False - break - else: - yield res # Claude回复的片段 - self.threadLock.release() - - -""" -======================================================================== -第三部分:主进程统一调用函数接口 -======================================================================== -""" -global claude_handle -claude_handle = None - - -def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False): - """ - 多线程方法 - 函数的说明请见 request_llm/bridge_all.py - """ - global claude_handle - if (claude_handle is None) or (not claude_handle.success): - claude_handle = ClaudeHandle() - observe_window[0] = load_message + "\n\n" + claude_handle.info - if not claude_handle.success: - error = claude_handle.info - claude_handle = None - raise RuntimeError(error) - - # 没有 sys_prompt 接口,因此把prompt加入 history - history_feedin = [] - for i in range(len(history)//2): - history_feedin.append([history[2*i], history[2*i+1]]) - - watch_dog_patience = 5 # 看门狗 (watchdog) 的耐心, 设置5秒即可 - response = "" - observe_window[0] = "[Local Message]: 等待Claude响应中 ..." - for response in claude_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=sys_prompt, max_length=llm_kwargs['max_length'], top_p=llm_kwargs['top_p'], temperature=llm_kwargs['temperature']): - observe_window[0] = preprocess_newbing_out_simple(response) - if len(observe_window) >= 2: - if (time.time()-observe_window[1]) > watch_dog_patience: - raise RuntimeError("程序终止。") - return preprocess_newbing_out_simple(response) - - -def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream=True, additional_fn=None): - """ - 单线程方法 - 函数的说明请见 request_llm/bridge_all.py - """ - chatbot.append((inputs, "[Local Message]: 等待Claude响应中 ...")) - - global claude_handle - if (claude_handle is None) or (not claude_handle.success): - claude_handle = ClaudeHandle() - chatbot[-1] = (inputs, load_message + "\n\n" + claude_handle.info) - yield from update_ui(chatbot=chatbot, history=[]) - if not claude_handle.success: - claude_handle = None - return - - if additional_fn is not None: - import core_functional - importlib.reload(core_functional) # 热更新prompt - core_functional = core_functional.get_core_functions() - if "PreProcess" in core_functional[additional_fn]: - inputs = core_functional[additional_fn]["PreProcess"]( - inputs) # 获取预处理函数(如果有的话) - inputs = core_functional[additional_fn]["Prefix"] + \ - inputs + core_functional[additional_fn]["Suffix"] - - history_feedin = [] - for i in range(len(history)//2): - history_feedin.append([history[2*i], history[2*i+1]]) - - chatbot[-1] = (inputs, "[Local Message]: 等待Claude响应中 ...") - response = "[Local Message]: 等待Claude响应中 ..." - yield from update_ui(chatbot=chatbot, history=history, msg="Claude响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。") - for response in claude_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=system_prompt): - chatbot[-1] = (inputs, preprocess_newbing_out(response)) - yield from update_ui(chatbot=chatbot, history=history, msg="Claude响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。") - if response == "[Local Message]: 等待Claude响应中 ...": - response = "[Local Message]: Claude响应异常,请刷新界面重试 ..." - history.extend([inputs, response]) - logging.info(f'[raw_input] {inputs}') - logging.info(f'[response] {response}') - yield from update_ui(chatbot=chatbot, history=history, msg="完成全部响应,请提交新问题。") diff --git a/spaces/fclong/summary/fengshen/models/deepVAE/latent_connector.py b/spaces/fclong/summary/fengshen/models/deepVAE/latent_connector.py deleted file mode 100644 index 509bd0a69a33a5e61d094a2e2943ed381459b87c..0000000000000000000000000000000000000000 --- a/spaces/fclong/summary/fengshen/models/deepVAE/latent_connector.py +++ /dev/null @@ -1,410 +0,0 @@ -# coding=utf-8 -# Copyright 2022 IDEA-CCNL The HuggingFace Inc. team. 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. -""" PyTorch Della model. """ - -import torch -import logging -import torch.nn as nn -from dataclasses import dataclass -from torch.nn import CrossEntropyLoss -from typing import Optional, Tuple, Dict, Any -# from transformers.utils.generic import ModelOutput -from transformers.file_utils import ModelOutput -from transformers.modeling_outputs import BaseModelOutputWithPastAndCrossAttentions -from transformers.models.gpt2.modeling_gpt2 import GPT2PreTrainedModel, GPT2Block, GPT2Model - - -@dataclass -class DeepVAEDecoderOutput(ModelOutput): - logits: torch.FloatTensor = None - loss: Optional[torch.FloatTensor] = None - hidden_states: Optional[Tuple[torch.FloatTensor]] = None - attentions: Optional[Tuple[torch.FloatTensor]] = None - - -logger = logging.getLogger(__name__) - - -class GPT2LatentDecoderModel(GPT2Model): - _keys_to_ignore_on_load_missing = ["attn.masked_bias"] - - def __init__(self, config, latent_dim=32): - super().__init__(config) - - self.embed_dim = config.hidden_size - - self.wte = nn.Embedding(config.vocab_size, self.embed_dim) - self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim) - - self.drop = nn.Dropout(config.embd_pdrop) - self.h = nn.ModuleList([GPT2Block(config, layer_idx=i) for i in range(config.num_hidden_layers)]) - self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon) - - # Model parallel - self.model_parallel = False - self.device_map = None - self.gradient_checkpointing = False - - # DeepVAE addition - self.linear_emb_layers = nn.ModuleList([nn.Linear(latent_dim, config.hidden_size, bias=False) for i in range(config.num_hidden_layers)]) - # self.linear_emb = nn.Linear(latent_dim, config.hidden_size, bias=False) # share the same latent vector as the embeddings - # Initialize weights and apply final processing - self.post_init() - - def forward( - self, - input_ids=None, - layer_latent_vecs=None, - past_key_values=None, - attention_mask=None, - token_type_ids=None, - position_ids=None, - head_mask=None, - inputs_embeds=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - use_cache=None, - output_attentions=None, - output_hidden_states=None, - return_dict=None, - ): - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - use_cache = use_cache if use_cache is not None else self.config.use_cache - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - if input_ids is not None and inputs_embeds is not None: - raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") - elif input_ids is not None: - input_shape = input_ids.size() - input_ids = input_ids.view(-1, input_shape[-1]) - batch_size = input_ids.shape[0] - elif inputs_embeds is not None: - input_shape = inputs_embeds.size()[:-1] - batch_size = inputs_embeds.shape[0] - else: - raise ValueError("You have to specify either input_ids or inputs_embeds") - - device = input_ids.device if input_ids is not None else inputs_embeds.device - - if token_type_ids is not None: - token_type_ids = token_type_ids.view(-1, input_shape[-1]) - if position_ids is not None: - position_ids = position_ids.view(-1, input_shape[-1]) - - if past_key_values is None: - past_length = 0 - past_key_values = tuple([None] * len(self.h)) - else: - past_length = past_key_values[0][0].size(-2) - if position_ids is None: - position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device) - position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1]) - - # GPT2Attention mask. - if attention_mask is not None: - if batch_size <= 0: - raise ValueError("batch_size has to be defined and > 0") - attention_mask = attention_mask.view(batch_size, -1) - # We create a 3D attention mask from a 2D tensor mask. - # Sizes are [batch_size, 1, 1, to_seq_length] - # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length] - # this attention mask is more simple than the triangular masking of causal attention - # used in OpenAI GPT, we just need to prepare the broadcast dimension here. - attention_mask = attention_mask[:, None, None, :] - - # Since attention_mask is 1.0 for positions we want to attend and 0.0 for - # masked positions, this operation will create a tensor which is 0.0 for - # positions we want to attend and -10000.0 for masked positions. - # Since we are adding it to the raw scores before the softmax, this is - # effectively the same as removing these entirely. - attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility - attention_mask = (1.0 - attention_mask) * -10000.0 - - # If a 2D or 3D attention mask is provided for the cross-attention - # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] - if self.config.add_cross_attention and encoder_hidden_states is not None: - encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() - encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) - if encoder_attention_mask is None: - encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) - encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask) - else: - encoder_attention_mask = None - - # Prepare head mask if needed - # 1.0 in head_mask indicate we keep the head - # attention_probs has shape bsz x n_heads x N x N - # head_mask has shape n_layer x batch x n_heads x N x N - head_mask = self.get_head_mask(head_mask, self.config.n_layer) - - if inputs_embeds is None: - inputs_embeds = self.wte(input_ids) - position_embeds = self.wpe(position_ids) - hidden_states = inputs_embeds + position_embeds - - if token_type_ids is not None: - token_type_embeds = self.wte(token_type_ids) - hidden_states = hidden_states + token_type_embeds - - hidden_states = self.drop(hidden_states) - - output_shape = input_shape + (hidden_states.size(-1),) - - presents = () if use_cache else None - all_self_attentions = () if output_attentions else None - all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None - all_hidden_states = () if output_hidden_states else None - for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)): - # NOTE: deepVAE modification. update hidden_states before passing into gpt2block! - # hidden_states are with shape (batch_size, sequence_length, hidden_size) - # layer_latent_vecs are with shape (batch_size, hidden_size) - latent_repr = self.linear_emb_layers[i](layer_latent_vecs[i]) - # latent_repr = self.linear_emb_layers[-1](layer_latent_vecs[-1]) - # latent_repr = self.linear_emb(layer_latent_vecs[i]) - hidden_states += latent_repr.unsqueeze(dim=1) - - # Model parallel - if self.model_parallel: - torch.cuda.set_device(hidden_states.device) - # Ensure layer_past is on same device as hidden_states (might not be correct) - if layer_past is not None: - layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past) - # Ensure that attention_mask is always on the same device as hidden_states - if attention_mask is not None: - attention_mask = attention_mask.to(hidden_states.device) - if isinstance(head_mask, torch.Tensor): - head_mask = head_mask.to(hidden_states.device) - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - if self.gradient_checkpointing and self.training: - - if use_cache: - logger.warning( - "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." - ) - use_cache = False - - def create_custom_forward(module): - def custom_forward(*inputs): - # None for past_key_value - return module(*inputs, use_cache, output_attentions) - - return custom_forward - - outputs = torch.utils.checkpoint.checkpoint( - create_custom_forward(block), - hidden_states, - None, - attention_mask, - head_mask[i], - encoder_hidden_states, - encoder_attention_mask, - ) - else: - outputs = block( - hidden_states, - layer_past=layer_past, - attention_mask=attention_mask, - head_mask=head_mask[i], - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_attention_mask, - use_cache=use_cache, - output_attentions=output_attentions, - ) - - hidden_states = outputs[0] - - if use_cache is True: - presents = presents + (outputs[1],) - - if output_attentions: - all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],) - if self.config.add_cross_attention: - all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],) - - # Model Parallel: If it's the last layer for that device, put things on the next device - if self.model_parallel: - for k, v in self.device_map.items(): - if i == v[-1] and "cuda:" + str(k) != self.last_device: - hidden_states = hidden_states.to("cuda:" + str(k + 1)) - - hidden_states = self.ln_f(hidden_states) - - hidden_states = hidden_states.view(*output_shape) - # Add last hidden state - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - if not return_dict: - return tuple( - v - for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions] - if v is not None - ) - - return BaseModelOutputWithPastAndCrossAttentions( - last_hidden_state=hidden_states, - past_key_values=presents, - hidden_states=all_hidden_states, - attentions=all_self_attentions, - cross_attentions=all_cross_attentions, - ) - - -class GPT2ForDecoderLatentConnector(GPT2PreTrainedModel): - r""" - **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``: - Labels for language modeling. - Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids`` - Indices are selected in ``[-1, 0, ..., config.vocab_size]`` - All labels set to ``-1`` are ignored (masked), the loss is only - computed for labels in ``[0, ..., config.vocab_size]`` - - Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: - **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: - Language modeling loss. - **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)`` - Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - **past**: - list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: - that contains pre-computed hidden-states (key and values in the attention blocks). - Can be used (see `past` input) to speed up sequential decoding. - **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) - list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) - of shape ``(batch_size, sequence_length, hidden_size)``: - Hidden-states of the model at the output of each layer plus the initial embedding outputs. - **attentions**: (`optional`, returned when ``config.output_attentions=True``) - list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: - Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. - - Examples:: - - import torch - from pytorch_transformers import GPT2Tokenizer, GPT2LMHeadModel - - tokenizer = GPT2Tokenizer.from_pretrained('gpt2') - model = GPT2LMHeadModel.from_pretrained('gpt2') - - input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 - outputs = model(input_ids, labels=input_ids) - loss, logits = outputs[:2] - - """ - - def __init__(self, config, latent_dim=32): - - super(GPT2ForDecoderLatentConnector, self).__init__(config) - self.transformer = GPT2LatentDecoderModel(config, latent_dim=latent_dim) - self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) - self.init_weights() - self.tie_weights() - - def tie_weights(self): - """ Make sure we are sharing the input and output embeddings. - Export to TorchScript can't handle parameter sharing so we are cloning them instead. - """ - self._tie_or_clone_weights(self.lm_head, - self.transformer.wte) - - def forward(self, input_ids, layer_latent_vecs, past=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, - labels=None, label_ignore=None, loss_mask=None, return_dict=False, - output_attentions=None, output_hidden_states=None, use_cache=None): - - transformer_outputs = self.transformer(input_ids, - layer_latent_vecs, - past_key_values=past, - attention_mask=attention_mask, - token_type_ids=token_type_ids, - position_ids=position_ids, - head_mask=head_mask, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states) - hidden_states = transformer_outputs[0] - - lm_logits = self.lm_head(hidden_states) - - outputs = (lm_logits,) + transformer_outputs[1:] - if labels is not None: - # Shift so that tokens < n predict n - shift_logits = lm_logits[..., :-1, :].contiguous() - shift_labels = labels[..., 1:].contiguous() - # Flatten the tokens - loss_fct = CrossEntropyLoss(ignore_index=label_ignore, reduction='none') - loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), - shift_labels.view(-1)) - - if loss_mask is not None: - loss = loss.view(-1, shift_labels.shape[-1]) * loss_mask[:, :-1] - loss = torch.sum(loss, -1) - else: - loss = torch.sum(loss.view(-1, shift_labels.shape[-1]), -1) - else: - loss = None - outputs = DeepVAEDecoderOutput(loss=loss, logits=lm_logits, hidden_states=transformer_outputs.hidden_states, - attentions=transformer_outputs.attentions) - return outputs - - def prepare_inputs_for_generation(self, input_ids: torch.LongTensor, **kwargs) -> Dict[str, Any]: - """ - Implement in subclasses of [`PreTrainedModel`] for custom behavior to prepare inputs in the generate method. - """ - return {"input_ids": input_ids, "layer_latent_vecs": kwargs['layer_latent_vecs']} - - -class GPT2ForEncoderLatentConnector(GPT2PreTrainedModel): - - def __init__(self, config): - - super(GPT2ForEncoderLatentConnector, self).__init__(config) - self.transformer = GPT2Model(config) - self.init_weights() - - def forward( - self, - input_ids=None, - past_key_values=None, - attention_mask=None, - token_type_ids=None, - position_ids=None, - head_mask=None, - inputs_embeds=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - use_cache=None, - output_attentions=None, - output_hidden_states=True, - return_dict=None, - ): - # output hidden states must set to true to allow for layer-wise latent vars - transformer_outputs = self.transformer( - input_ids, - past_key_values=past_key_values, - attention_mask=attention_mask, - token_type_ids=token_type_ids, - position_ids=position_ids, - head_mask=head_mask, - inputs_embeds=inputs_embeds, - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_attention_mask, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - return transformer_outputs diff --git a/spaces/fffffu/bing/src/components/ui/input.tsx b/spaces/fffffu/bing/src/components/ui/input.tsx deleted file mode 100644 index 684a857f3d769b78818fb13de1abaebfb09ca79c..0000000000000000000000000000000000000000 --- a/spaces/fffffu/bing/src/components/ui/input.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from 'react' - -import { cn } from '@/lib/utils' - -export interface InputProps - extends React.InputHTMLAttributes {} - -const Input = React.forwardRef( - ({ className, type, ...props }, ref) => { - return ( - - ) - } -) -Input.displayName = 'Input' - -export { Input } diff --git a/spaces/fffiloni/controlnet-animation-doodle/node_modules/encodeurl/index.js b/spaces/fffiloni/controlnet-animation-doodle/node_modules/encodeurl/index.js deleted file mode 100644 index fc4906c6c7896396a877e1f369c78f804e3afa10..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/controlnet-animation-doodle/node_modules/encodeurl/index.js +++ /dev/null @@ -1,60 +0,0 @@ -/*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = encodeUrl - -/** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private - */ - -var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g - -/** - * RegExp to match unmatched surrogate pair. - * @private - */ - -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g - -/** - * String to replace unmatched surrogate pair with. - * @private - */ - -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' - -/** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. - * - * This function will take an already-encoded URL and encode all the non-URL - * code points. This function will not encode the "%" character unless it is - * not part of a valid sequence (`%20` will be left as-is, but `%foo` will - * be encoded as `%25foo`). - * - * This encode is meant to be "safe" and does not throw errors. It will try as - * hard as it can to properly encode the given URL, including replacing any raw, - * unpaired surrogate pairs with the Unicode replacement character prior to - * encoding. - * - * @param {string} url - * @return {string} - * @public - */ - -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} diff --git a/spaces/flax-community/dalle-mini/html2canvas.js b/spaces/flax-community/dalle-mini/html2canvas.js deleted file mode 100644 index 96e2dc5707b1a584ff7b3b583aea7c6c18d4ea76..0000000000000000000000000000000000000000 --- a/spaces/flax-community/dalle-mini/html2canvas.js +++ /dev/null @@ -1,7756 +0,0 @@ -/*! - * html2canvas 1.4.1 - * Copyright (c) 2022 Niklas von Hertzen - * Released under MIT License - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.html2canvas = factory()); -}(this, (function () { 'use strict'; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - - function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - } - - function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - } - - function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || from); - } - - var Bounds = /** @class */ (function () { - function Bounds(left, top, width, height) { - this.left = left; - this.top = top; - this.width = width; - this.height = height; - } - Bounds.prototype.add = function (x, y, w, h) { - return new Bounds(this.left + x, this.top + y, this.width + w, this.height + h); - }; - Bounds.fromClientRect = function (context, clientRect) { - return new Bounds(clientRect.left + context.windowBounds.left, clientRect.top + context.windowBounds.top, clientRect.width, clientRect.height); - }; - Bounds.fromDOMRectList = function (context, domRectList) { - var domRect = Array.from(domRectList).find(function (rect) { return rect.width !== 0; }); - return domRect - ? new Bounds(domRect.left + context.windowBounds.left, domRect.top + context.windowBounds.top, domRect.width, domRect.height) - : Bounds.EMPTY; - }; - Bounds.EMPTY = new Bounds(0, 0, 0, 0); - return Bounds; - }()); - var parseBounds = function (context, node) { - return Bounds.fromClientRect(context, node.getBoundingClientRect()); - }; - var parseDocumentSize = function (document) { - var body = document.body; - var documentElement = document.documentElement; - if (!body || !documentElement) { - throw new Error("Unable to get document size"); - } - var width = Math.max(Math.max(body.scrollWidth, documentElement.scrollWidth), Math.max(body.offsetWidth, documentElement.offsetWidth), Math.max(body.clientWidth, documentElement.clientWidth)); - var height = Math.max(Math.max(body.scrollHeight, documentElement.scrollHeight), Math.max(body.offsetHeight, documentElement.offsetHeight), Math.max(body.clientHeight, documentElement.clientHeight)); - return new Bounds(0, 0, width, height); - }; - - /* - * css-line-break 2.1.0 - * Copyright (c) 2022 Niklas von Hertzen - * Released under MIT License - */ - var toCodePoints$1 = function (str) { - var codePoints = []; - var i = 0; - var length = str.length; - while (i < length) { - var value = str.charCodeAt(i++); - if (value >= 0xd800 && value <= 0xdbff && i < length) { - var extra = str.charCodeAt(i++); - if ((extra & 0xfc00) === 0xdc00) { - codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000); - } - else { - codePoints.push(value); - i--; - } - } - else { - codePoints.push(value); - } - } - return codePoints; - }; - var fromCodePoint$1 = function () { - var codePoints = []; - for (var _i = 0; _i < arguments.length; _i++) { - codePoints[_i] = arguments[_i]; - } - if (String.fromCodePoint) { - return String.fromCodePoint.apply(String, codePoints); - } - var length = codePoints.length; - if (!length) { - return ''; - } - var codeUnits = []; - var index = -1; - var result = ''; - while (++index < length) { - var codePoint = codePoints[index]; - if (codePoint <= 0xffff) { - codeUnits.push(codePoint); - } - else { - codePoint -= 0x10000; - codeUnits.push((codePoint >> 10) + 0xd800, (codePoint % 0x400) + 0xdc00); - } - if (index + 1 === length || codeUnits.length > 0x4000) { - result += String.fromCharCode.apply(String, codeUnits); - codeUnits.length = 0; - } - } - return result; - }; - var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // Use a lookup table to find the index. - var lookup$2 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); - for (var i$2 = 0; i$2 < chars$2.length; i$2++) { - lookup$2[chars$2.charCodeAt(i$2)] = i$2; - } - - /* - * utrie 1.0.2 - * Copyright (c) 2022 Niklas von Hertzen - * Released under MIT License - */ - var chars$1$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // Use a lookup table to find the index. - var lookup$1$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); - for (var i$1$1 = 0; i$1$1 < chars$1$1.length; i$1$1++) { - lookup$1$1[chars$1$1.charCodeAt(i$1$1)] = i$1$1; - } - var decode$1 = function (base64) { - var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; - if (base64[base64.length - 1] === '=') { - bufferLength--; - if (base64[base64.length - 2] === '=') { - bufferLength--; - } - } - var buffer = typeof ArrayBuffer !== 'undefined' && - typeof Uint8Array !== 'undefined' && - typeof Uint8Array.prototype.slice !== 'undefined' - ? new ArrayBuffer(bufferLength) - : new Array(bufferLength); - var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer); - for (i = 0; i < len; i += 4) { - encoded1 = lookup$1$1[base64.charCodeAt(i)]; - encoded2 = lookup$1$1[base64.charCodeAt(i + 1)]; - encoded3 = lookup$1$1[base64.charCodeAt(i + 2)]; - encoded4 = lookup$1$1[base64.charCodeAt(i + 3)]; - bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } - return buffer; - }; - var polyUint16Array$1 = function (buffer) { - var length = buffer.length; - var bytes = []; - for (var i = 0; i < length; i += 2) { - bytes.push((buffer[i + 1] << 8) | buffer[i]); - } - return bytes; - }; - var polyUint32Array$1 = function (buffer) { - var length = buffer.length; - var bytes = []; - for (var i = 0; i < length; i += 4) { - bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]); - } - return bytes; - }; - - /** Shift size for getting the index-2 table offset. */ - var UTRIE2_SHIFT_2$1 = 5; - /** Shift size for getting the index-1 table offset. */ - var UTRIE2_SHIFT_1$1 = 6 + 5; - /** - * Shift size for shifting left the index array values. - * Increases possible data size with 16-bit index values at the cost - * of compactability. - * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY. - */ - var UTRIE2_INDEX_SHIFT$1 = 2; - /** - * Difference between the two shift sizes, - * for getting an index-1 offset from an index-2 offset. 6=11-5 - */ - var UTRIE2_SHIFT_1_2$1 = UTRIE2_SHIFT_1$1 - UTRIE2_SHIFT_2$1; - /** - * The part of the index-2 table for U+D800..U+DBFF stores values for - * lead surrogate code _units_ not code _points_. - * Values for lead surrogate code _points_ are indexed with this portion of the table. - * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.) - */ - var UTRIE2_LSCP_INDEX_2_OFFSET$1 = 0x10000 >> UTRIE2_SHIFT_2$1; - /** Number of entries in a data block. 32=0x20 */ - var UTRIE2_DATA_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_2$1; - /** Mask for getting the lower bits for the in-data-block offset. */ - var UTRIE2_DATA_MASK$1 = UTRIE2_DATA_BLOCK_LENGTH$1 - 1; - var UTRIE2_LSCP_INDEX_2_LENGTH$1 = 0x400 >> UTRIE2_SHIFT_2$1; - /** Count the lengths of both BMP pieces. 2080=0x820 */ - var UTRIE2_INDEX_2_BMP_LENGTH$1 = UTRIE2_LSCP_INDEX_2_OFFSET$1 + UTRIE2_LSCP_INDEX_2_LENGTH$1; - /** - * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820. - * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2. - */ - var UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 = UTRIE2_INDEX_2_BMP_LENGTH$1; - var UTRIE2_UTF8_2B_INDEX_2_LENGTH$1 = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */ - /** - * The index-1 table, only used for supplementary code points, at offset 2112=0x840. - * Variable length, for code points up to highStart, where the last single-value range starts. - * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1. - * (For 0x100000 supplementary code points U+10000..U+10ffff.) - * - * The part of the index-2 table for supplementary code points starts - * after this index-1 table. - * - * Both the index-1 table and the following part of the index-2 table - * are omitted completely if there is only BMP data. - */ - var UTRIE2_INDEX_1_OFFSET$1 = UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 + UTRIE2_UTF8_2B_INDEX_2_LENGTH$1; - /** - * Number of index-1 entries for the BMP. 32=0x20 - * This part of the index-1 table is omitted from the serialized form. - */ - var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 = 0x10000 >> UTRIE2_SHIFT_1$1; - /** Number of entries in an index-2 block. 64=0x40 */ - var UTRIE2_INDEX_2_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_1_2$1; - /** Mask for getting the lower bits for the in-index-2-block offset. */ - var UTRIE2_INDEX_2_MASK$1 = UTRIE2_INDEX_2_BLOCK_LENGTH$1 - 1; - var slice16$1 = function (view, start, end) { - if (view.slice) { - return view.slice(start, end); - } - return new Uint16Array(Array.prototype.slice.call(view, start, end)); - }; - var slice32$1 = function (view, start, end) { - if (view.slice) { - return view.slice(start, end); - } - return new Uint32Array(Array.prototype.slice.call(view, start, end)); - }; - var createTrieFromBase64$1 = function (base64, _byteLength) { - var buffer = decode$1(base64); - var view32 = Array.isArray(buffer) ? polyUint32Array$1(buffer) : new Uint32Array(buffer); - var view16 = Array.isArray(buffer) ? polyUint16Array$1(buffer) : new Uint16Array(buffer); - var headerLength = 24; - var index = slice16$1(view16, headerLength / 2, view32[4] / 2); - var data = view32[5] === 2 - ? slice16$1(view16, (headerLength + view32[4]) / 2) - : slice32$1(view32, Math.ceil((headerLength + view32[4]) / 4)); - return new Trie$1(view32[0], view32[1], view32[2], view32[3], index, data); - }; - var Trie$1 = /** @class */ (function () { - function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) { - this.initialValue = initialValue; - this.errorValue = errorValue; - this.highStart = highStart; - this.highValueIndex = highValueIndex; - this.index = index; - this.data = data; - } - /** - * Get the value for a code point as stored in the Trie. - * - * @param codePoint the code point - * @return the value - */ - Trie.prototype.get = function (codePoint) { - var ix; - if (codePoint >= 0) { - if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) { - // Ordinary BMP code point, excluding leading surrogates. - // BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index. - // 16 bit data is stored in the index array itself. - ix = this.index[codePoint >> UTRIE2_SHIFT_2$1]; - ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1); - return this.data[ix]; - } - if (codePoint <= 0xffff) { - // Lead Surrogate Code Point. A Separate index section is stored for - // lead surrogate code units and code points. - // The main index has the code unit data. - // For this function, we need the code point data. - // Note: this expression could be refactored for slightly improved efficiency, but - // surrogate code points will be so rare in practice that it's not worth it. - ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET$1 + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2$1)]; - ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1); - return this.data[ix]; - } - if (codePoint < this.highStart) { - // Supplemental code point, use two-level lookup. - ix = UTRIE2_INDEX_1_OFFSET$1 - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 + (codePoint >> UTRIE2_SHIFT_1$1); - ix = this.index[ix]; - ix += (codePoint >> UTRIE2_SHIFT_2$1) & UTRIE2_INDEX_2_MASK$1; - ix = this.index[ix]; - ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1); - return this.data[ix]; - } - if (codePoint <= 0x10ffff) { - return this.data[this.highValueIndex]; - } - } - // Fall through. The code point is outside of the legal range of 0..0x10ffff. - return this.errorValue; - }; - return Trie; - }()); - - /* - * base64-arraybuffer 1.0.2 - * Copyright (c) 2022 Niklas von Hertzen - * Released under MIT License - */ - var chars$3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // Use a lookup table to find the index. - var lookup$3 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); - for (var i$3 = 0; i$3 < chars$3.length; i$3++) { - lookup$3[chars$3.charCodeAt(i$3)] = i$3; - } - - var base64$1 = 'KwAAAAAAAAAACA4AUD0AADAgAAACAAAAAAAIABAAGABAAEgAUABYAGAAaABgAGgAYgBqAF8AZwBgAGgAcQB5AHUAfQCFAI0AlQCdAKIAqgCyALoAYABoAGAAaABgAGgAwgDKAGAAaADGAM4A0wDbAOEA6QDxAPkAAQEJAQ8BFwF1AH0AHAEkASwBNAE6AUIBQQFJAVEBWQFhAWgBcAF4ATAAgAGGAY4BlQGXAZ8BpwGvAbUBvQHFAc0B0wHbAeMB6wHxAfkBAQIJAvEBEQIZAiECKQIxAjgCQAJGAk4CVgJeAmQCbAJ0AnwCgQKJApECmQKgAqgCsAK4ArwCxAIwAMwC0wLbAjAA4wLrAvMC+AIAAwcDDwMwABcDHQMlAy0DNQN1AD0DQQNJA0kDSQNRA1EDVwNZA1kDdQB1AGEDdQBpA20DdQN1AHsDdQCBA4kDkQN1AHUAmQOhA3UAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AKYDrgN1AHUAtgO+A8YDzgPWAxcD3gPjA+sD8wN1AHUA+wMDBAkEdQANBBUEHQQlBCoEFwMyBDgEYABABBcDSARQBFgEYARoBDAAcAQzAXgEgASIBJAEdQCXBHUAnwSnBK4EtgS6BMIEyAR1AHUAdQB1AHUAdQCVANAEYABgAGAAYABgAGAAYABgANgEYADcBOQEYADsBPQE/AQEBQwFFAUcBSQFLAU0BWQEPAVEBUsFUwVbBWAAYgVgAGoFcgV6BYIFigWRBWAAmQWfBaYFYABgAGAAYABgAKoFYACxBbAFuQW6BcEFwQXHBcEFwQXPBdMF2wXjBeoF8gX6BQIGCgYSBhoGIgYqBjIGOgZgAD4GRgZMBmAAUwZaBmAAYABgAGAAYABgAGAAYABgAGAAYABgAGIGYABpBnAGYABgAGAAYABgAGAAYABgAGAAYAB4Bn8GhQZgAGAAYAB1AHcDFQSLBmAAYABgAJMGdQA9A3UAmwajBqsGqwaVALMGuwbDBjAAywbSBtIG1QbSBtIG0gbSBtIG0gbdBuMG6wbzBvsGAwcLBxMHAwcbByMHJwcsBywHMQcsB9IGOAdAB0gHTgfSBkgHVgfSBtIG0gbSBtIG0gbSBtIG0gbSBiwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdgAGAALAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdbB2MHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB2kH0gZwB64EdQB1AHUAdQB1AHUAdQB1AHUHfQdgAIUHjQd1AHUAlQedB2AAYAClB6sHYACzB7YHvgfGB3UAzgfWBzMB3gfmB1EB7gf1B/0HlQENAQUIDQh1ABUIHQglCBcDLQg1CD0IRQhNCEEDUwh1AHUAdQBbCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIcAh3CHoIMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIgggwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAALAcsBywHLAcsBywHLAcsBywHLAcsB4oILAcsB44I0gaWCJ4Ipgh1AHUAqgiyCHUAdQB1AHUAdQB1AHUAdQB1AHUAtwh8AXUAvwh1AMUIyQjRCNkI4AjoCHUAdQB1AO4I9gj+CAYJDgkTCS0HGwkjCYIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiAAIAAAAFAAYABgAGIAXwBgAHEAdQBFAJUAogCyAKAAYABgAEIA4ABGANMA4QDxAMEBDwE1AFwBLAE6AQEBUQF4QkhCmEKoQrhCgAHIQsAB0MLAAcABwAHAAeDC6ABoAHDCwMMAAcABwAHAAdDDGMMAAcAB6MM4wwjDWMNow3jDaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEjDqABWw6bDqABpg6gAaABoAHcDvwOPA+gAaABfA/8DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DpcPAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcAB9cPKwkyCToJMAB1AHUAdQBCCUoJTQl1AFUJXAljCWcJawkwADAAMAAwAHMJdQB2CX4JdQCECYoJjgmWCXUAngkwAGAAYABxAHUApgn3A64JtAl1ALkJdQDACTAAMAAwADAAdQB1AHUAdQB1AHUAdQB1AHUAowYNBMUIMAAwADAAMADICcsJ0wnZCRUE4QkwAOkJ8An4CTAAMAB1AAAKvwh1AAgKDwoXCh8KdQAwACcKLgp1ADYKqAmICT4KRgowADAAdQB1AE4KMAB1AFYKdQBeCnUAZQowADAAMAAwADAAMAAwADAAMAAVBHUAbQowADAAdQC5CXUKMAAwAHwBxAijBogEMgF9CoQKiASMCpQKmgqIBKIKqgquCogEDQG2Cr4KxgrLCjAAMADTCtsKCgHjCusK8Qr5CgELMAAwADAAMAB1AIsECQsRC3UANAEZCzAAMAAwADAAMAB1ACELKQswAHUANAExCzkLdQBBC0kLMABRC1kLMAAwADAAMAAwADAAdQBhCzAAMAAwAGAAYABpC3ELdwt/CzAAMACHC4sLkwubC58Lpwt1AK4Ltgt1APsDMAAwADAAMAAwADAAMAAwAL4LwwvLC9IL1wvdCzAAMADlC+kL8Qv5C/8LSQswADAAMAAwADAAMAAwADAAMAAHDDAAMAAwADAAMAAODBYMHgx1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1ACYMMAAwADAAdQB1AHUALgx1AHUAdQB1AHUAdQA2DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AD4MdQBGDHUAdQB1AHUAdQB1AEkMdQB1AHUAdQB1AFAMMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQBYDHUAdQB1AF8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUA+wMVBGcMMAAwAHwBbwx1AHcMfwyHDI8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAYABgAJcMMAAwADAAdQB1AJ8MlQClDDAAMACtDCwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB7UMLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AA0EMAC9DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAsBywHLAcsBywHLAcsBywHLQcwAMEMyAwsBywHLAcsBywHLAcsBywHLAcsBywHzAwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1ANQM2QzhDDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMABgAGAAYABgAGAAYABgAOkMYADxDGAA+AwADQYNYABhCWAAYAAODTAAMAAwADAAFg1gAGAAHg37AzAAMAAwADAAYABgACYNYAAsDTQNPA1gAEMNPg1LDWAAYABgAGAAYABgAGAAYABgAGAAUg1aDYsGVglhDV0NcQBnDW0NdQ15DWAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAlQCBDZUAiA2PDZcNMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAnw2nDTAAMAAwADAAMAAwAHUArw23DTAAMAAwADAAMAAwADAAMAAwADAAMAB1AL8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQDHDTAAYABgAM8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA1w11ANwNMAAwAD0B5A0wADAAMAAwADAAMADsDfQN/A0EDgwOFA4wABsOMAAwADAAMAAwADAAMAAwANIG0gbSBtIG0gbSBtIG0gYjDigOwQUuDsEFMw7SBjoO0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGQg5KDlIOVg7SBtIGXg5lDm0OdQ7SBtIGfQ6EDooOjQ6UDtIGmg6hDtIG0gaoDqwO0ga0DrwO0gZgAGAAYADEDmAAYAAkBtIGzA5gANIOYADaDokO0gbSBt8O5w7SBu8O0gb1DvwO0gZgAGAAxA7SBtIG0gbSBtIGYABgAGAAYAAED2AAsAUMD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHJA8sBywHLAcsBywHLAccDywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywPLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAc0D9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHPA/SBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gYUD0QPlQCVAJUAMAAwADAAMACVAJUAlQCVAJUAlQCVAEwPMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA//8EAAQABAAEAAQABAAEAAQABAANAAMAAQABAAIABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQACgATABcAHgAbABoAHgAXABYAEgAeABsAGAAPABgAHABLAEsASwBLAEsASwBLAEsASwBLABgAGAAeAB4AHgATAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYAGwASAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWAA0AEQAeAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAFAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJABYAGgAbABsAGwAeAB0AHQAeAE8AFwAeAA0AHgAeABoAGwBPAE8ADgBQAB0AHQAdAE8ATwAXAE8ATwBPABYAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAFAATwBAAE8ATwBPAEAATwBQAFAATwBQAB4AHgAeAB4AHgAeAB0AHQAdAB0AHgAdAB4ADgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgBQAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkACQAJAAkACQAJAAkABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAFAAHgAeAB4AKwArAFAAUABQAFAAGABQACsAKwArACsAHgAeAFAAHgBQAFAAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUAAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAYAA0AKwArAB4AHgAbACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAB4ABAAEAB4ABAAEABMABAArACsAKwArACsAKwArACsAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAKwArACsAKwBWAFYAVgBWAB4AHgArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AGgAaABoAGAAYAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQAEwAEACsAEwATAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABLAEsASwBLAEsASwBLAEsASwBLABoAGQAZAB4AUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABMAUAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABABQAFAABAAEAB4ABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUAAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAFAABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQAUABQAB4AHgAYABMAUAArACsABAAbABsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAFAABAAEAAQABAAEAFAABAAEAAQAUAAEAAQABAAEAAQAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArACsAHgArAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAUAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEAA0ADQBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUAArACsAKwBQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABABQACsAKwArACsAKwArACsAKwAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUAAaABoAUABQAFAAUABQAEwAHgAbAFAAHgAEACsAKwAEAAQABAArAFAAUABQAFAAUABQACsAKwArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQACsAUABQACsAKwAEACsABAAEAAQABAAEACsAKwArACsABAAEACsAKwAEAAQABAArACsAKwAEACsAKwArACsAKwArACsAUABQAFAAUAArAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLAAQABABQAFAAUAAEAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAArACsAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AGwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAKwArACsAKwArAAQABAAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAAQAUAArAFAAUABQAFAAUABQACsAKwArAFAAUABQACsAUABQAFAAUAArACsAKwBQAFAAKwBQACsAUABQACsAKwArAFAAUAArACsAKwBQAFAAUAArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAAQABAAEAAQABAArACsAKwAEAAQABAArAAQABAAEAAQAKwArAFAAKwArACsAKwArACsABAArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAHgAeAB4AHgAeAB4AGwAeACsAKwArACsAKwAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAUABQAFAAKwArACsAKwArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwAOAFAAUABQAFAAUABQAFAAHgBQAAQABAAEAA4AUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAKwArAAQAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAKwArACsAKwArACsAUAArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABABQAB4AKwArACsAKwBQAFAAUAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQABoAUABQAFAAUABQAFAAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQACsAUAArACsAUABQAFAAUABQAFAAUAArACsAKwAEACsAKwArACsABAAEAAQABAAEAAQAKwAEACsABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgAqACsAKwArACsAGwBcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAeAEsASwBLAEsASwBLAEsASwBLAEsADQANACsAKwArACsAKwBcAFwAKwBcACsAXABcAFwAXABcACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAXAArAFwAXABcAFwAXABcAFwAXABcAFwAKgBcAFwAKgAqACoAKgAqACoAKgAqACoAXAArACsAXABcAFwAXABcACsAXAArACoAKgAqACoAKgAqACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwBcAFwAXABcAFAADgAOAA4ADgAeAA4ADgAJAA4ADgANAAkAEwATABMAEwATAAkAHgATAB4AHgAeAAQABAAeAB4AHgAeAB4AHgBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQAFAADQAEAB4ABAAeAAQAFgARABYAEQAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAAQABAAEAAQADQAEAAQAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAA0ADQAeAB4AHgAeAB4AHgAEAB4AHgAeAB4AHgAeACsAHgAeAA4ADgANAA4AHgAeAB4AHgAeAAkACQArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgBcAEsASwBLAEsASwBLAEsASwBLAEsADQANAB4AHgAeAB4AXABcAFwAXABcAFwAKgAqACoAKgBcAFwAXABcACoAKgAqAFwAKgAqACoAXABcACoAKgAqACoAKgAqACoAXABcAFwAKgAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqAFwAKgBLAEsASwBLAEsASwBLAEsASwBLACoAKgAqACoAKgAqAFAAUABQAFAAUABQACsAUAArACsAKwArACsAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAKwBQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsABAAEAAQAHgANAB4AHgAeAB4AHgAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUAArACsADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWABEAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQANAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAANAA0AKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUAArAAQABAArACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqAA0ADQAVAFwADQAeAA0AGwBcACoAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwAeAB4AEwATAA0ADQAOAB4AEwATAB4ABAAEAAQACQArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAHgArACsAKwATABMASwBLAEsASwBLAEsASwBLAEsASwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAXABcAFwAXABcACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAXAArACsAKwAqACoAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsAHgAeAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKwAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKwArAAQASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACoAKgAqACoAKgAqACoAXAAqACoAKgAqACoAKgArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABABQAFAAUABQAFAAUABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwANAA0AHgANAA0ADQANAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwAeAB4AHgAeAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArAA0ADQANAA0ADQBLAEsASwBLAEsASwBLAEsASwBLACsAKwArAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUAAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAAQAUABQAFAAUABQAFAABABQAFAABAAEAAQAUAArACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQACsAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQACsAKwAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQACsAHgAeAB4AHgAeAB4AHgAOAB4AKwANAA0ADQANAA0ADQANAAkADQANAA0ACAAEAAsABAAEAA0ACQANAA0ADAAdAB0AHgAXABcAFgAXABcAFwAWABcAHQAdAB4AHgAUABQAFAANAAEAAQAEAAQABAAEAAQACQAaABoAGgAaABoAGgAaABoAHgAXABcAHQAVABUAHgAeAB4AHgAeAB4AGAAWABEAFQAVABUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ADQAeAA0ADQANAA0AHgANAA0ADQAHAB4AHgAeAB4AKwAEAAQABAAEAAQABAAEAAQABAAEAFAAUAArACsATwBQAFAAUABQAFAAHgAeAB4AFgARAE8AUABPAE8ATwBPAFAAUABQAFAAUAAeAB4AHgAWABEAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArABsAGwAbABsAGwAbABsAGgAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGgAbABsAGwAbABoAGwAbABoAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAHgAeAFAAGgAeAB0AHgBQAB4AGgAeAB4AHgAeAB4AHgAeAB4AHgBPAB4AUAAbAB4AHgBQAFAAUABQAFAAHgAeAB4AHQAdAB4AUAAeAFAAHgBQAB4AUABPAFAAUAAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgBQAFAAUABQAE8ATwBQAFAAUABQAFAATwBQAFAATwBQAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAUABQAFAATwBPAE8ATwBPAE8ATwBPAE8ATwBQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABPAB4AHgArACsAKwArAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHQAdAB4AHgAeAB0AHQAeAB4AHQAeAB4AHgAdAB4AHQAbABsAHgAdAB4AHgAeAB4AHQAeAB4AHQAdAB0AHQAeAB4AHQAeAB0AHgAdAB0AHQAdAB0AHQAeAB0AHgAeAB4AHgAeAB0AHQAdAB0AHgAeAB4AHgAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB0AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAdAB0AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAWABEAHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AHQAdAB0AHgAeAB0AHgAeAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlAB4AHQAdAB4AHgAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AJQAlAB0AHQAlAB4AJQAlACUAIAAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAdAB0AHQAeAB0AJQAdAB0AHgAdAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAdAB0AHQAdACUAHgAlACUAJQAdACUAJQAdAB0AHQAlACUAHQAdACUAHQAdACUAJQAlAB4AHQAeAB4AHgAeAB0AHQAlAB0AHQAdAB0AHQAdACUAJQAlACUAJQAdACUAJQAgACUAHQAdACUAJQAlACUAJQAlACUAJQAeAB4AHgAlACUAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AFwAXABcAFwAXABcAHgATABMAJQAeAB4AHgAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARABYAEQAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAeAB4AKwArACsAKwArABMADQANAA0AUAATAA0AUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUAANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAA0ADQANAA0ADQANAA0ADQAeAA0AFgANAB4AHgAXABcAHgAeABcAFwAWABEAFgARABYAEQAWABEADQANAA0ADQATAFAADQANAB4ADQANAB4AHgAeAB4AHgAMAAwADQANAA0AHgANAA0AFgANAA0ADQANAA0ADQANAA0AHgANAB4ADQANAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArAA0AEQARACUAJQBHAFcAVwAWABEAFgARABYAEQAWABEAFgARACUAJQAWABEAFgARABYAEQAWABEAFQAWABEAEQAlAFcAVwBXAFcAVwBXAFcAVwBXAAQABAAEAAQABAAEACUAVwBXAFcAVwA2ACUAJQBXAFcAVwBHAEcAJQAlACUAKwBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBRAFcAUQBXAFEAVwBXAFcAVwBXAFcAUQBXAFcAVwBXAFcAVwBRAFEAKwArAAQABAAVABUARwBHAFcAFQBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBRAFcAVwBXAFcAVwBXAFEAUQBXAFcAVwBXABUAUQBHAEcAVwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwAlACUAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACsAKwArACsAKwArACsAKwArACsAKwArAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBPAE8ATwBPAE8ATwBPAE8AJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADQATAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQAHgBQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAeAA0ADQANAA0ADQArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAAQAUABQAFAABABQAFAAUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAeAB4AHgAeAAQAKwArACsAUABQAFAAUABQAFAAHgAeABoAHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADgAOABMAEwArACsAKwArACsAKwArACsABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUAAeAB4AHgBQAA4AUABQAAQAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAB4AWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYACsAKwArAAQAHgAeAB4AHgAeAB4ADQANAA0AHgAeAB4AHgArAFAASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArAB4AHgBcAFwAXABcAFwAKgBcAFwAXABcAFwAXABcAFwAXABcAEsASwBLAEsASwBLAEsASwBLAEsAXABcAFwAXABcACsAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAFAAUABQAAQAUABQAFAAUABQAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAHgANAA0ADQBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAKgAqACoAXABcACoAKgBcAFwAXABcAFwAKgAqAFwAKgBcACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAA0ADQBQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQADQAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAVABVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBUAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVACsAKwArACsAKwArACsAKwArACsAKwArAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAKwArACsAKwBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAKwArACsAKwAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArACsAKwArAFYABABWAFYAVgBWAFYAVgBWAFYAVgBWAB4AVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgArAFYAVgBWAFYAVgArAFYAKwBWAFYAKwBWAFYAKwBWAFYAVgBWAFYAVgBWAFYAVgBWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAEQAWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAaAB4AKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAGAARABEAGAAYABMAEwAWABEAFAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACUAJQAlACUAJQAWABEAFgARABYAEQAWABEAFgARABYAEQAlACUAFgARACUAJQAlACUAJQAlACUAEQAlABEAKwAVABUAEwATACUAFgARABYAEQAWABEAJQAlACUAJQAlACUAJQAlACsAJQAbABoAJQArACsAKwArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAcAKwATACUAJQAbABoAJQAlABYAEQAlACUAEQAlABEAJQBXAFcAVwBXAFcAVwBXAFcAVwBXABUAFQAlACUAJQATACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXABYAJQARACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAWACUAEQAlABYAEQARABYAEQARABUAVwBRAFEAUQBRAFEAUQBRAFEAUQBRAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcARwArACsAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXACsAKwBXAFcAVwBXAFcAVwArACsAVwBXAFcAKwArACsAGgAbACUAJQAlABsAGwArAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAAQAB0AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsADQANAA0AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAA0AUABQAFAAUAArACsAKwArAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwBQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAUABQAFAAUABQAAQABAAEACsABAAEACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAKwBQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAA0ADQANAA0ADQANAA0ADQAeACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAArACsAKwArAFAAUABQAFAAUAANAA0ADQANAA0ADQAUACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsADQANAA0ADQANAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArAAQABAANACsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAB4AHgAeAB4AHgArACsAKwArACsAKwAEAAQABAAEAAQABAAEAA0ADQAeAB4AHgAeAB4AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsASwBLAEsASwBLAEsASwBLAEsASwANAA0ADQANAFAABAAEAFAAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAeAA4AUAArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAADQANAB4ADQAEAAQABAAEAB4ABAAEAEsASwBLAEsASwBLAEsASwBLAEsAUAAOAFAADQANAA0AKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAA0AHgANAA0AHgAEACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAA0AKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsABAAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAUAArACsAKwArACsAKwAEACsAKwArACsAKwBQAFAAUABQAFAABAAEACsAKwAEAAQABAAEAAQABAAEACsAKwArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABABQAFAAUABQAA0ADQANAA0AHgBLAEsASwBLAEsASwBLAEsASwBLAA0ADQArAB4ABABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUAAeAFAAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABAAEAAQADgANAA0AEwATAB4AHgAeAA0ADQANAA0ADQANAA0ADQANAA0ADQANAA0ADQANAFAAUABQAFAABAAEACsAKwAEAA0ADQAeAFAAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKwArACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBcAFwADQANAA0AKgBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQAKwAEAAQAKwArAAQABAAEAAQAUAAEAFAABAAEAA0ADQANACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABABQAA4AUAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAOAB4ADQANAA0ADQAOAB4ABAArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAA0ADQANAFAADgAOAA4ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAFAADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAOABMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAArACsAKwAEACsABAAEACsABAAEAAQABAAEAAQABABQAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAaABoAGgAaAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABIAEgAQwBDAEMAUABQAFAAUABDAFAAUABQAEgAQwBIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABDAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAJAAkACQAJAAkACQAJABYAEQArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwANAA0AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAANACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQANAB4AHgAeAB4AHgAeAFAAUABQAFAADQAeACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAA0AHgAeACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAARwBHABUARwAJACsAKwArACsAKwArACsAKwArACsAKwAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUQBRAFEAKwArACsAKwArACsAKwArACsAKwArACsAKwBRAFEAUQBRACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAHgAEAAQADQAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQABAAEAAQABAAeAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQAHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAKwArAFAAKwArAFAAUAArACsAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUAArAFAAUABQAFAAUABQAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAHgAeAFAAUABQAFAAUAArAFAAKwArACsAUABQAFAAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeACsAKwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4ABAAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAHgAeAA0ADQANAA0AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArAAQABAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwBQAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArABsAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAB4AHgAeAB4ABAAEAAQABAAEAAQABABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArABYAFgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAGgBQAFAAUAAaAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUAArACsAKwArACsAKwBQACsAKwArACsAUAArAFAAKwBQACsAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUAArAFAAKwBQACsAUAArAFAAUAArAFAAKwArAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAKwBQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AJQAlACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeACUAJQAlAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAlACUAJQAlACUAHgAlACUAJQAlACUAIAAgACAAJQAlACAAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACEAIQAhACEAIQAlACUAIAAgACUAJQAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAIAAlACUAJQAlACAAIAAgACUAIAAgACAAJQAlACUAJQAlACUAJQAgACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAlAB4AJQAeACUAJQAlACUAJQAgACUAJQAlACUAHgAlAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACAAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABcAFwAXABUAFQAVAB4AHgAeAB4AJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAgACUAJQAgACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAIAAgACUAJQAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACAAIAAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACAAIAAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAA=='; - - var LETTER_NUMBER_MODIFIER = 50; - // Non-tailorable Line Breaking Classes - var BK = 1; // Cause a line break (after) - var CR$1 = 2; // Cause a line break (after), except between CR and LF - var LF$1 = 3; // Cause a line break (after) - var CM = 4; // Prohibit a line break between the character and the preceding character - var NL = 5; // Cause a line break (after) - var WJ = 7; // Prohibit line breaks before and after - var ZW = 8; // Provide a break opportunity - var GL = 9; // Prohibit line breaks before and after - var SP = 10; // Enable indirect line breaks - var ZWJ$1 = 11; // Prohibit line breaks within joiner sequences - // Break Opportunities - var B2 = 12; // Provide a line break opportunity before and after the character - var BA = 13; // Generally provide a line break opportunity after the character - var BB = 14; // Generally provide a line break opportunity before the character - var HY = 15; // Provide a line break opportunity after the character, except in numeric context - var CB = 16; // Provide a line break opportunity contingent on additional information - // Characters Prohibiting Certain Breaks - var CL = 17; // Prohibit line breaks before - var CP = 18; // Prohibit line breaks before - var EX = 19; // Prohibit line breaks before - var IN = 20; // Allow only indirect line breaks between pairs - var NS = 21; // Allow only indirect line breaks before - var OP = 22; // Prohibit line breaks after - var QU = 23; // Act like they are both opening and closing - // Numeric Context - var IS = 24; // Prevent breaks after any and before numeric - var NU = 25; // Form numeric expressions for line breaking purposes - var PO = 26; // Do not break following a numeric expression - var PR = 27; // Do not break in front of a numeric expression - var SY = 28; // Prevent a break before; and allow a break after - // Other Characters - var AI = 29; // Act like AL when the resolvedEAW is N; otherwise; act as ID - var AL = 30; // Are alphabetic characters or symbols that are used with alphabetic characters - var CJ = 31; // Treat as NS or ID for strict or normal breaking. - var EB = 32; // Do not break from following Emoji Modifier - var EM = 33; // Do not break from preceding Emoji Base - var H2 = 34; // Form Korean syllable blocks - var H3 = 35; // Form Korean syllable blocks - var HL = 36; // Do not break around a following hyphen; otherwise act as Alphabetic - var ID = 37; // Break before or after; except in some numeric context - var JL = 38; // Form Korean syllable blocks - var JV = 39; // Form Korean syllable blocks - var JT = 40; // Form Korean syllable blocks - var RI$1 = 41; // Keep pairs together. For pairs; break before and after other classes - var SA = 42; // Provide a line break opportunity contingent on additional, language-specific context analysis - var XX = 43; // Have as yet unknown line breaking behavior or unassigned code positions - var ea_OP = [0x2329, 0xff08]; - var BREAK_MANDATORY = '!'; - var BREAK_NOT_ALLOWED$1 = '×'; - var BREAK_ALLOWED$1 = '÷'; - var UnicodeTrie$1 = createTrieFromBase64$1(base64$1); - var ALPHABETICS = [AL, HL]; - var HARD_LINE_BREAKS = [BK, CR$1, LF$1, NL]; - var SPACE$1 = [SP, ZW]; - var PREFIX_POSTFIX = [PR, PO]; - var LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE$1); - var KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3]; - var HYPHEN = [HY, BA]; - var codePointsToCharacterClasses = function (codePoints, lineBreak) { - if (lineBreak === void 0) { lineBreak = 'strict'; } - var types = []; - var indices = []; - var categories = []; - codePoints.forEach(function (codePoint, index) { - var classType = UnicodeTrie$1.get(codePoint); - if (classType > LETTER_NUMBER_MODIFIER) { - categories.push(true); - classType -= LETTER_NUMBER_MODIFIER; - } - else { - categories.push(false); - } - if (['normal', 'auto', 'loose'].indexOf(lineBreak) !== -1) { - // U+2010, – U+2013, 〜 U+301C, ゠ U+30A0 - if ([0x2010, 0x2013, 0x301c, 0x30a0].indexOf(codePoint) !== -1) { - indices.push(index); - return types.push(CB); - } - } - if (classType === CM || classType === ZWJ$1) { - // LB10 Treat any remaining combining mark or ZWJ as AL. - if (index === 0) { - indices.push(index); - return types.push(AL); - } - // LB9 Do not break a combining character sequence; treat it as if it has the line breaking class of - // the base character in all of the following rules. Treat ZWJ as if it were CM. - var prev = types[index - 1]; - if (LINE_BREAKS.indexOf(prev) === -1) { - indices.push(indices[index - 1]); - return types.push(prev); - } - indices.push(index); - return types.push(AL); - } - indices.push(index); - if (classType === CJ) { - return types.push(lineBreak === 'strict' ? NS : ID); - } - if (classType === SA) { - return types.push(AL); - } - if (classType === AI) { - return types.push(AL); - } - // For supplementary characters, a useful default is to treat characters in the range 10000..1FFFD as AL - // and characters in the ranges 20000..2FFFD and 30000..3FFFD as ID, until the implementation can be revised - // to take into account the actual line breaking properties for these characters. - if (classType === XX) { - if ((codePoint >= 0x20000 && codePoint <= 0x2fffd) || (codePoint >= 0x30000 && codePoint <= 0x3fffd)) { - return types.push(ID); - } - else { - return types.push(AL); - } - } - types.push(classType); - }); - return [indices, types, categories]; - }; - var isAdjacentWithSpaceIgnored = function (a, b, currentIndex, classTypes) { - var current = classTypes[currentIndex]; - if (Array.isArray(a) ? a.indexOf(current) !== -1 : a === current) { - var i = currentIndex; - while (i <= classTypes.length) { - i++; - var next = classTypes[i]; - if (next === b) { - return true; - } - if (next !== SP) { - break; - } - } - } - if (current === SP) { - var i = currentIndex; - while (i > 0) { - i--; - var prev = classTypes[i]; - if (Array.isArray(a) ? a.indexOf(prev) !== -1 : a === prev) { - var n = currentIndex; - while (n <= classTypes.length) { - n++; - var next = classTypes[n]; - if (next === b) { - return true; - } - if (next !== SP) { - break; - } - } - } - if (prev !== SP) { - break; - } - } - } - return false; - }; - var previousNonSpaceClassType = function (currentIndex, classTypes) { - var i = currentIndex; - while (i >= 0) { - var type = classTypes[i]; - if (type === SP) { - i--; - } - else { - return type; - } - } - return 0; - }; - var _lineBreakAtIndex = function (codePoints, classTypes, indicies, index, forbiddenBreaks) { - if (indicies[index] === 0) { - return BREAK_NOT_ALLOWED$1; - } - var currentIndex = index - 1; - if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) { - return BREAK_NOT_ALLOWED$1; - } - var beforeIndex = currentIndex - 1; - var afterIndex = currentIndex + 1; - var current = classTypes[currentIndex]; - // LB4 Always break after hard line breaks. - // LB5 Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks. - var before = beforeIndex >= 0 ? classTypes[beforeIndex] : 0; - var next = classTypes[afterIndex]; - if (current === CR$1 && next === LF$1) { - return BREAK_NOT_ALLOWED$1; - } - if (HARD_LINE_BREAKS.indexOf(current) !== -1) { - return BREAK_MANDATORY; - } - // LB6 Do not break before hard line breaks. - if (HARD_LINE_BREAKS.indexOf(next) !== -1) { - return BREAK_NOT_ALLOWED$1; - } - // LB7 Do not break before spaces or zero width space. - if (SPACE$1.indexOf(next) !== -1) { - return BREAK_NOT_ALLOWED$1; - } - // LB8 Break before any character following a zero-width space, even if one or more spaces intervene. - if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) { - return BREAK_ALLOWED$1; - } - // LB8a Do not break after a zero width joiner. - if (UnicodeTrie$1.get(codePoints[currentIndex]) === ZWJ$1) { - return BREAK_NOT_ALLOWED$1; - } - // zwj emojis - if ((current === EB || current === EM) && UnicodeTrie$1.get(codePoints[afterIndex]) === ZWJ$1) { - return BREAK_NOT_ALLOWED$1; - } - // LB11 Do not break before or after Word joiner and related characters. - if (current === WJ || next === WJ) { - return BREAK_NOT_ALLOWED$1; - } - // LB12 Do not break after NBSP and related characters. - if (current === GL) { - return BREAK_NOT_ALLOWED$1; - } - // LB12a Do not break before NBSP and related characters, except after spaces and hyphens. - if ([SP, BA, HY].indexOf(current) === -1 && next === GL) { - return BREAK_NOT_ALLOWED$1; - } - // LB13 Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces. - if ([CL, CP, EX, IS, SY].indexOf(next) !== -1) { - return BREAK_NOT_ALLOWED$1; - } - // LB14 Do not break after ‘[’, even after spaces. - if (previousNonSpaceClassType(currentIndex, classTypes) === OP) { - return BREAK_NOT_ALLOWED$1; - } - // LB15 Do not break within ‘”[’, even with intervening spaces. - if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) { - return BREAK_NOT_ALLOWED$1; - } - // LB16 Do not break between closing punctuation and a nonstarter (lb=NS), even with intervening spaces. - if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) { - return BREAK_NOT_ALLOWED$1; - } - // LB17 Do not break within ‘——’, even with intervening spaces. - if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) { - return BREAK_NOT_ALLOWED$1; - } - // LB18 Break after spaces. - if (current === SP) { - return BREAK_ALLOWED$1; - } - // LB19 Do not break before or after quotation marks, such as ‘ ” ’. - if (current === QU || next === QU) { - return BREAK_NOT_ALLOWED$1; - } - // LB20 Break before and after unresolved CB. - if (next === CB || current === CB) { - return BREAK_ALLOWED$1; - } - // LB21 Do not break before hyphen-minus, other hyphens, fixed-width spaces, small kana, and other non-starters, or after acute accents. - if ([BA, HY, NS].indexOf(next) !== -1 || current === BB) { - return BREAK_NOT_ALLOWED$1; - } - // LB21a Don't break after Hebrew + Hyphen. - if (before === HL && HYPHEN.indexOf(current) !== -1) { - return BREAK_NOT_ALLOWED$1; - } - // LB21b Don’t break between Solidus and Hebrew letters. - if (current === SY && next === HL) { - return BREAK_NOT_ALLOWED$1; - } - // LB22 Do not break before ellipsis. - if (next === IN) { - return BREAK_NOT_ALLOWED$1; - } - // LB23 Do not break between digits and letters. - if ((ALPHABETICS.indexOf(next) !== -1 && current === NU) || (ALPHABETICS.indexOf(current) !== -1 && next === NU)) { - return BREAK_NOT_ALLOWED$1; - } - // LB23a Do not break between numeric prefixes and ideographs, or between ideographs and numeric postfixes. - if ((current === PR && [ID, EB, EM].indexOf(next) !== -1) || - ([ID, EB, EM].indexOf(current) !== -1 && next === PO)) { - return BREAK_NOT_ALLOWED$1; - } - // LB24 Do not break between numeric prefix/postfix and letters, or between letters and prefix/postfix. - if ((ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next) !== -1) || - (PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1)) { - return BREAK_NOT_ALLOWED$1; - } - // LB25 Do not break between the following pairs of classes relevant to numbers: - if ( - // (PR | PO) × ( OP | HY )? NU - ([PR, PO].indexOf(current) !== -1 && - (next === NU || ([OP, HY].indexOf(next) !== -1 && classTypes[afterIndex + 1] === NU))) || - // ( OP | HY ) × NU - ([OP, HY].indexOf(current) !== -1 && next === NU) || - // NU × (NU | SY | IS) - (current === NU && [NU, SY, IS].indexOf(next) !== -1)) { - return BREAK_NOT_ALLOWED$1; - } - // NU (NU | SY | IS)* × (NU | SY | IS | CL | CP) - if ([NU, SY, IS, CL, CP].indexOf(next) !== -1) { - var prevIndex = currentIndex; - while (prevIndex >= 0) { - var type = classTypes[prevIndex]; - if (type === NU) { - return BREAK_NOT_ALLOWED$1; - } - else if ([SY, IS].indexOf(type) !== -1) { - prevIndex--; - } - else { - break; - } - } - } - // NU (NU | SY | IS)* (CL | CP)? × (PO | PR)) - if ([PR, PO].indexOf(next) !== -1) { - var prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex; - while (prevIndex >= 0) { - var type = classTypes[prevIndex]; - if (type === NU) { - return BREAK_NOT_ALLOWED$1; - } - else if ([SY, IS].indexOf(type) !== -1) { - prevIndex--; - } - else { - break; - } - } - } - // LB26 Do not break a Korean syllable. - if ((JL === current && [JL, JV, H2, H3].indexOf(next) !== -1) || - ([JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next) !== -1) || - ([JT, H3].indexOf(current) !== -1 && next === JT)) { - return BREAK_NOT_ALLOWED$1; - } - // LB27 Treat a Korean Syllable Block the same as ID. - if ((KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next) !== -1) || - (KOREAN_SYLLABLE_BLOCK.indexOf(next) !== -1 && current === PR)) { - return BREAK_NOT_ALLOWED$1; - } - // LB28 Do not break between alphabetics (“at”). - if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) { - return BREAK_NOT_ALLOWED$1; - } - // LB29 Do not break between numeric punctuation and alphabetics (“e.g.”). - if (current === IS && ALPHABETICS.indexOf(next) !== -1) { - return BREAK_NOT_ALLOWED$1; - } - // LB30 Do not break between letters, numbers, or ordinary symbols and opening or closing parentheses. - if ((ALPHABETICS.concat(NU).indexOf(current) !== -1 && - next === OP && - ea_OP.indexOf(codePoints[afterIndex]) === -1) || - (ALPHABETICS.concat(NU).indexOf(next) !== -1 && current === CP)) { - return BREAK_NOT_ALLOWED$1; - } - // LB30a Break between two regional indicator symbols if and only if there are an even number of regional - // indicators preceding the position of the break. - if (current === RI$1 && next === RI$1) { - var i = indicies[currentIndex]; - var count = 1; - while (i > 0) { - i--; - if (classTypes[i] === RI$1) { - count++; - } - else { - break; - } - } - if (count % 2 !== 0) { - return BREAK_NOT_ALLOWED$1; - } - } - // LB30b Do not break between an emoji base and an emoji modifier. - if (current === EB && next === EM) { - return BREAK_NOT_ALLOWED$1; - } - return BREAK_ALLOWED$1; - }; - var cssFormattedClasses = function (codePoints, options) { - if (!options) { - options = { lineBreak: 'normal', wordBreak: 'normal' }; - } - var _a = codePointsToCharacterClasses(codePoints, options.lineBreak), indicies = _a[0], classTypes = _a[1], isLetterNumber = _a[2]; - if (options.wordBreak === 'break-all' || options.wordBreak === 'break-word') { - classTypes = classTypes.map(function (type) { return ([NU, AL, SA].indexOf(type) !== -1 ? ID : type); }); - } - var forbiddenBreakpoints = options.wordBreak === 'keep-all' - ? isLetterNumber.map(function (letterNumber, i) { - return letterNumber && codePoints[i] >= 0x4e00 && codePoints[i] <= 0x9fff; - }) - : undefined; - return [indicies, classTypes, forbiddenBreakpoints]; - }; - var Break = /** @class */ (function () { - function Break(codePoints, lineBreak, start, end) { - this.codePoints = codePoints; - this.required = lineBreak === BREAK_MANDATORY; - this.start = start; - this.end = end; - } - Break.prototype.slice = function () { - return fromCodePoint$1.apply(void 0, this.codePoints.slice(this.start, this.end)); - }; - return Break; - }()); - var LineBreaker = function (str, options) { - var codePoints = toCodePoints$1(str); - var _a = cssFormattedClasses(codePoints, options), indicies = _a[0], classTypes = _a[1], forbiddenBreakpoints = _a[2]; - var length = codePoints.length; - var lastEnd = 0; - var nextIndex = 0; - return { - next: function () { - if (nextIndex >= length) { - return { done: true, value: null }; - } - var lineBreak = BREAK_NOT_ALLOWED$1; - while (nextIndex < length && - (lineBreak = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) === - BREAK_NOT_ALLOWED$1) { } - if (lineBreak !== BREAK_NOT_ALLOWED$1 || nextIndex === length) { - var value = new Break(codePoints, lineBreak, lastEnd, nextIndex); - lastEnd = nextIndex; - return { value: value, done: false }; - } - return { done: true, value: null }; - }, - }; - }; - - // https://www.w3.org/TR/css-syntax-3 - var FLAG_UNRESTRICTED = 1 << 0; - var FLAG_ID = 1 << 1; - var FLAG_INTEGER = 1 << 2; - var FLAG_NUMBER = 1 << 3; - var LINE_FEED = 0x000a; - var SOLIDUS = 0x002f; - var REVERSE_SOLIDUS = 0x005c; - var CHARACTER_TABULATION = 0x0009; - var SPACE = 0x0020; - var QUOTATION_MARK = 0x0022; - var EQUALS_SIGN = 0x003d; - var NUMBER_SIGN = 0x0023; - var DOLLAR_SIGN = 0x0024; - var PERCENTAGE_SIGN = 0x0025; - var APOSTROPHE = 0x0027; - var LEFT_PARENTHESIS = 0x0028; - var RIGHT_PARENTHESIS = 0x0029; - var LOW_LINE = 0x005f; - var HYPHEN_MINUS = 0x002d; - var EXCLAMATION_MARK = 0x0021; - var LESS_THAN_SIGN = 0x003c; - var GREATER_THAN_SIGN = 0x003e; - var COMMERCIAL_AT = 0x0040; - var LEFT_SQUARE_BRACKET = 0x005b; - var RIGHT_SQUARE_BRACKET = 0x005d; - var CIRCUMFLEX_ACCENT = 0x003d; - var LEFT_CURLY_BRACKET = 0x007b; - var QUESTION_MARK = 0x003f; - var RIGHT_CURLY_BRACKET = 0x007d; - var VERTICAL_LINE = 0x007c; - var TILDE = 0x007e; - var CONTROL = 0x0080; - var REPLACEMENT_CHARACTER = 0xfffd; - var ASTERISK = 0x002a; - var PLUS_SIGN = 0x002b; - var COMMA = 0x002c; - var COLON = 0x003a; - var SEMICOLON = 0x003b; - var FULL_STOP = 0x002e; - var NULL = 0x0000; - var BACKSPACE = 0x0008; - var LINE_TABULATION = 0x000b; - var SHIFT_OUT = 0x000e; - var INFORMATION_SEPARATOR_ONE = 0x001f; - var DELETE = 0x007f; - var EOF = -1; - var ZERO = 0x0030; - var a = 0x0061; - var e = 0x0065; - var f = 0x0066; - var u = 0x0075; - var z = 0x007a; - var A = 0x0041; - var E = 0x0045; - var F = 0x0046; - var U = 0x0055; - var Z = 0x005a; - var isDigit = function (codePoint) { return codePoint >= ZERO && codePoint <= 0x0039; }; - var isSurrogateCodePoint = function (codePoint) { return codePoint >= 0xd800 && codePoint <= 0xdfff; }; - var isHex = function (codePoint) { - return isDigit(codePoint) || (codePoint >= A && codePoint <= F) || (codePoint >= a && codePoint <= f); - }; - var isLowerCaseLetter = function (codePoint) { return codePoint >= a && codePoint <= z; }; - var isUpperCaseLetter = function (codePoint) { return codePoint >= A && codePoint <= Z; }; - var isLetter = function (codePoint) { return isLowerCaseLetter(codePoint) || isUpperCaseLetter(codePoint); }; - var isNonASCIICodePoint = function (codePoint) { return codePoint >= CONTROL; }; - var isWhiteSpace = function (codePoint) { - return codePoint === LINE_FEED || codePoint === CHARACTER_TABULATION || codePoint === SPACE; - }; - var isNameStartCodePoint = function (codePoint) { - return isLetter(codePoint) || isNonASCIICodePoint(codePoint) || codePoint === LOW_LINE; - }; - var isNameCodePoint = function (codePoint) { - return isNameStartCodePoint(codePoint) || isDigit(codePoint) || codePoint === HYPHEN_MINUS; - }; - var isNonPrintableCodePoint = function (codePoint) { - return ((codePoint >= NULL && codePoint <= BACKSPACE) || - codePoint === LINE_TABULATION || - (codePoint >= SHIFT_OUT && codePoint <= INFORMATION_SEPARATOR_ONE) || - codePoint === DELETE); - }; - var isValidEscape = function (c1, c2) { - if (c1 !== REVERSE_SOLIDUS) { - return false; - } - return c2 !== LINE_FEED; - }; - var isIdentifierStart = function (c1, c2, c3) { - if (c1 === HYPHEN_MINUS) { - return isNameStartCodePoint(c2) || isValidEscape(c2, c3); - } - else if (isNameStartCodePoint(c1)) { - return true; - } - else if (c1 === REVERSE_SOLIDUS && isValidEscape(c1, c2)) { - return true; - } - return false; - }; - var isNumberStart = function (c1, c2, c3) { - if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) { - if (isDigit(c2)) { - return true; - } - return c2 === FULL_STOP && isDigit(c3); - } - if (c1 === FULL_STOP) { - return isDigit(c2); - } - return isDigit(c1); - }; - var stringToNumber = function (codePoints) { - var c = 0; - var sign = 1; - if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) { - if (codePoints[c] === HYPHEN_MINUS) { - sign = -1; - } - c++; - } - var integers = []; - while (isDigit(codePoints[c])) { - integers.push(codePoints[c++]); - } - var int = integers.length ? parseInt(fromCodePoint$1.apply(void 0, integers), 10) : 0; - if (codePoints[c] === FULL_STOP) { - c++; - } - var fraction = []; - while (isDigit(codePoints[c])) { - fraction.push(codePoints[c++]); - } - var fracd = fraction.length; - var frac = fracd ? parseInt(fromCodePoint$1.apply(void 0, fraction), 10) : 0; - if (codePoints[c] === E || codePoints[c] === e) { - c++; - } - var expsign = 1; - if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) { - if (codePoints[c] === HYPHEN_MINUS) { - expsign = -1; - } - c++; - } - var exponent = []; - while (isDigit(codePoints[c])) { - exponent.push(codePoints[c++]); - } - var exp = exponent.length ? parseInt(fromCodePoint$1.apply(void 0, exponent), 10) : 0; - return sign * (int + frac * Math.pow(10, -fracd)) * Math.pow(10, expsign * exp); - }; - var LEFT_PARENTHESIS_TOKEN = { - type: 2 /* LEFT_PARENTHESIS_TOKEN */ - }; - var RIGHT_PARENTHESIS_TOKEN = { - type: 3 /* RIGHT_PARENTHESIS_TOKEN */ - }; - var COMMA_TOKEN = { type: 4 /* COMMA_TOKEN */ }; - var SUFFIX_MATCH_TOKEN = { type: 13 /* SUFFIX_MATCH_TOKEN */ }; - var PREFIX_MATCH_TOKEN = { type: 8 /* PREFIX_MATCH_TOKEN */ }; - var COLUMN_TOKEN = { type: 21 /* COLUMN_TOKEN */ }; - var DASH_MATCH_TOKEN = { type: 9 /* DASH_MATCH_TOKEN */ }; - var INCLUDE_MATCH_TOKEN = { type: 10 /* INCLUDE_MATCH_TOKEN */ }; - var LEFT_CURLY_BRACKET_TOKEN = { - type: 11 /* LEFT_CURLY_BRACKET_TOKEN */ - }; - var RIGHT_CURLY_BRACKET_TOKEN = { - type: 12 /* RIGHT_CURLY_BRACKET_TOKEN */ - }; - var SUBSTRING_MATCH_TOKEN = { type: 14 /* SUBSTRING_MATCH_TOKEN */ }; - var BAD_URL_TOKEN = { type: 23 /* BAD_URL_TOKEN */ }; - var BAD_STRING_TOKEN = { type: 1 /* BAD_STRING_TOKEN */ }; - var CDO_TOKEN = { type: 25 /* CDO_TOKEN */ }; - var CDC_TOKEN = { type: 24 /* CDC_TOKEN */ }; - var COLON_TOKEN = { type: 26 /* COLON_TOKEN */ }; - var SEMICOLON_TOKEN = { type: 27 /* SEMICOLON_TOKEN */ }; - var LEFT_SQUARE_BRACKET_TOKEN = { - type: 28 /* LEFT_SQUARE_BRACKET_TOKEN */ - }; - var RIGHT_SQUARE_BRACKET_TOKEN = { - type: 29 /* RIGHT_SQUARE_BRACKET_TOKEN */ - }; - var WHITESPACE_TOKEN = { type: 31 /* WHITESPACE_TOKEN */ }; - var EOF_TOKEN = { type: 32 /* EOF_TOKEN */ }; - var Tokenizer = /** @class */ (function () { - function Tokenizer() { - this._value = []; - } - Tokenizer.prototype.write = function (chunk) { - this._value = this._value.concat(toCodePoints$1(chunk)); - }; - Tokenizer.prototype.read = function () { - var tokens = []; - var token = this.consumeToken(); - while (token !== EOF_TOKEN) { - tokens.push(token); - token = this.consumeToken(); - } - return tokens; - }; - Tokenizer.prototype.consumeToken = function () { - var codePoint = this.consumeCodePoint(); - switch (codePoint) { - case QUOTATION_MARK: - return this.consumeStringToken(QUOTATION_MARK); - case NUMBER_SIGN: - var c1 = this.peekCodePoint(0); - var c2 = this.peekCodePoint(1); - var c3 = this.peekCodePoint(2); - if (isNameCodePoint(c1) || isValidEscape(c2, c3)) { - var flags = isIdentifierStart(c1, c2, c3) ? FLAG_ID : FLAG_UNRESTRICTED; - var value = this.consumeName(); - return { type: 5 /* HASH_TOKEN */, value: value, flags: flags }; - } - break; - case DOLLAR_SIGN: - if (this.peekCodePoint(0) === EQUALS_SIGN) { - this.consumeCodePoint(); - return SUFFIX_MATCH_TOKEN; - } - break; - case APOSTROPHE: - return this.consumeStringToken(APOSTROPHE); - case LEFT_PARENTHESIS: - return LEFT_PARENTHESIS_TOKEN; - case RIGHT_PARENTHESIS: - return RIGHT_PARENTHESIS_TOKEN; - case ASTERISK: - if (this.peekCodePoint(0) === EQUALS_SIGN) { - this.consumeCodePoint(); - return SUBSTRING_MATCH_TOKEN; - } - break; - case PLUS_SIGN: - if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) { - this.reconsumeCodePoint(codePoint); - return this.consumeNumericToken(); - } - break; - case COMMA: - return COMMA_TOKEN; - case HYPHEN_MINUS: - var e1 = codePoint; - var e2 = this.peekCodePoint(0); - var e3 = this.peekCodePoint(1); - if (isNumberStart(e1, e2, e3)) { - this.reconsumeCodePoint(codePoint); - return this.consumeNumericToken(); - } - if (isIdentifierStart(e1, e2, e3)) { - this.reconsumeCodePoint(codePoint); - return this.consumeIdentLikeToken(); - } - if (e2 === HYPHEN_MINUS && e3 === GREATER_THAN_SIGN) { - this.consumeCodePoint(); - this.consumeCodePoint(); - return CDC_TOKEN; - } - break; - case FULL_STOP: - if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) { - this.reconsumeCodePoint(codePoint); - return this.consumeNumericToken(); - } - break; - case SOLIDUS: - if (this.peekCodePoint(0) === ASTERISK) { - this.consumeCodePoint(); - while (true) { - var c = this.consumeCodePoint(); - if (c === ASTERISK) { - c = this.consumeCodePoint(); - if (c === SOLIDUS) { - return this.consumeToken(); - } - } - if (c === EOF) { - return this.consumeToken(); - } - } - } - break; - case COLON: - return COLON_TOKEN; - case SEMICOLON: - return SEMICOLON_TOKEN; - case LESS_THAN_SIGN: - if (this.peekCodePoint(0) === EXCLAMATION_MARK && - this.peekCodePoint(1) === HYPHEN_MINUS && - this.peekCodePoint(2) === HYPHEN_MINUS) { - this.consumeCodePoint(); - this.consumeCodePoint(); - return CDO_TOKEN; - } - break; - case COMMERCIAL_AT: - var a1 = this.peekCodePoint(0); - var a2 = this.peekCodePoint(1); - var a3 = this.peekCodePoint(2); - if (isIdentifierStart(a1, a2, a3)) { - var value = this.consumeName(); - return { type: 7 /* AT_KEYWORD_TOKEN */, value: value }; - } - break; - case LEFT_SQUARE_BRACKET: - return LEFT_SQUARE_BRACKET_TOKEN; - case REVERSE_SOLIDUS: - if (isValidEscape(codePoint, this.peekCodePoint(0))) { - this.reconsumeCodePoint(codePoint); - return this.consumeIdentLikeToken(); - } - break; - case RIGHT_SQUARE_BRACKET: - return RIGHT_SQUARE_BRACKET_TOKEN; - case CIRCUMFLEX_ACCENT: - if (this.peekCodePoint(0) === EQUALS_SIGN) { - this.consumeCodePoint(); - return PREFIX_MATCH_TOKEN; - } - break; - case LEFT_CURLY_BRACKET: - return LEFT_CURLY_BRACKET_TOKEN; - case RIGHT_CURLY_BRACKET: - return RIGHT_CURLY_BRACKET_TOKEN; - case u: - case U: - var u1 = this.peekCodePoint(0); - var u2 = this.peekCodePoint(1); - if (u1 === PLUS_SIGN && (isHex(u2) || u2 === QUESTION_MARK)) { - this.consumeCodePoint(); - this.consumeUnicodeRangeToken(); - } - this.reconsumeCodePoint(codePoint); - return this.consumeIdentLikeToken(); - case VERTICAL_LINE: - if (this.peekCodePoint(0) === EQUALS_SIGN) { - this.consumeCodePoint(); - return DASH_MATCH_TOKEN; - } - if (this.peekCodePoint(0) === VERTICAL_LINE) { - this.consumeCodePoint(); - return COLUMN_TOKEN; - } - break; - case TILDE: - if (this.peekCodePoint(0) === EQUALS_SIGN) { - this.consumeCodePoint(); - return INCLUDE_MATCH_TOKEN; - } - break; - case EOF: - return EOF_TOKEN; - } - if (isWhiteSpace(codePoint)) { - this.consumeWhiteSpace(); - return WHITESPACE_TOKEN; - } - if (isDigit(codePoint)) { - this.reconsumeCodePoint(codePoint); - return this.consumeNumericToken(); - } - if (isNameStartCodePoint(codePoint)) { - this.reconsumeCodePoint(codePoint); - return this.consumeIdentLikeToken(); - } - return { type: 6 /* DELIM_TOKEN */, value: fromCodePoint$1(codePoint) }; - }; - Tokenizer.prototype.consumeCodePoint = function () { - var value = this._value.shift(); - return typeof value === 'undefined' ? -1 : value; - }; - Tokenizer.prototype.reconsumeCodePoint = function (codePoint) { - this._value.unshift(codePoint); - }; - Tokenizer.prototype.peekCodePoint = function (delta) { - if (delta >= this._value.length) { - return -1; - } - return this._value[delta]; - }; - Tokenizer.prototype.consumeUnicodeRangeToken = function () { - var digits = []; - var codePoint = this.consumeCodePoint(); - while (isHex(codePoint) && digits.length < 6) { - digits.push(codePoint); - codePoint = this.consumeCodePoint(); - } - var questionMarks = false; - while (codePoint === QUESTION_MARK && digits.length < 6) { - digits.push(codePoint); - codePoint = this.consumeCodePoint(); - questionMarks = true; - } - if (questionMarks) { - var start_1 = parseInt(fromCodePoint$1.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? ZERO : digit); })), 16); - var end = parseInt(fromCodePoint$1.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? F : digit); })), 16); - return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start_1, end: end }; - } - var start = parseInt(fromCodePoint$1.apply(void 0, digits), 16); - if (this.peekCodePoint(0) === HYPHEN_MINUS && isHex(this.peekCodePoint(1))) { - this.consumeCodePoint(); - codePoint = this.consumeCodePoint(); - var endDigits = []; - while (isHex(codePoint) && endDigits.length < 6) { - endDigits.push(codePoint); - codePoint = this.consumeCodePoint(); - } - var end = parseInt(fromCodePoint$1.apply(void 0, endDigits), 16); - return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start, end: end }; - } - else { - return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start, end: start }; - } - }; - Tokenizer.prototype.consumeIdentLikeToken = function () { - var value = this.consumeName(); - if (value.toLowerCase() === 'url' && this.peekCodePoint(0) === LEFT_PARENTHESIS) { - this.consumeCodePoint(); - return this.consumeUrlToken(); - } - else if (this.peekCodePoint(0) === LEFT_PARENTHESIS) { - this.consumeCodePoint(); - return { type: 19 /* FUNCTION_TOKEN */, value: value }; - } - return { type: 20 /* IDENT_TOKEN */, value: value }; - }; - Tokenizer.prototype.consumeUrlToken = function () { - var value = []; - this.consumeWhiteSpace(); - if (this.peekCodePoint(0) === EOF) { - return { type: 22 /* URL_TOKEN */, value: '' }; - } - var next = this.peekCodePoint(0); - if (next === APOSTROPHE || next === QUOTATION_MARK) { - var stringToken = this.consumeStringToken(this.consumeCodePoint()); - if (stringToken.type === 0 /* STRING_TOKEN */) { - this.consumeWhiteSpace(); - if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) { - this.consumeCodePoint(); - return { type: 22 /* URL_TOKEN */, value: stringToken.value }; - } - } - this.consumeBadUrlRemnants(); - return BAD_URL_TOKEN; - } - while (true) { - var codePoint = this.consumeCodePoint(); - if (codePoint === EOF || codePoint === RIGHT_PARENTHESIS) { - return { type: 22 /* URL_TOKEN */, value: fromCodePoint$1.apply(void 0, value) }; - } - else if (isWhiteSpace(codePoint)) { - this.consumeWhiteSpace(); - if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) { - this.consumeCodePoint(); - return { type: 22 /* URL_TOKEN */, value: fromCodePoint$1.apply(void 0, value) }; - } - this.consumeBadUrlRemnants(); - return BAD_URL_TOKEN; - } - else if (codePoint === QUOTATION_MARK || - codePoint === APOSTROPHE || - codePoint === LEFT_PARENTHESIS || - isNonPrintableCodePoint(codePoint)) { - this.consumeBadUrlRemnants(); - return BAD_URL_TOKEN; - } - else if (codePoint === REVERSE_SOLIDUS) { - if (isValidEscape(codePoint, this.peekCodePoint(0))) { - value.push(this.consumeEscapedCodePoint()); - } - else { - this.consumeBadUrlRemnants(); - return BAD_URL_TOKEN; - } - } - else { - value.push(codePoint); - } - } - }; - Tokenizer.prototype.consumeWhiteSpace = function () { - while (isWhiteSpace(this.peekCodePoint(0))) { - this.consumeCodePoint(); - } - }; - Tokenizer.prototype.consumeBadUrlRemnants = function () { - while (true) { - var codePoint = this.consumeCodePoint(); - if (codePoint === RIGHT_PARENTHESIS || codePoint === EOF) { - return; - } - if (isValidEscape(codePoint, this.peekCodePoint(0))) { - this.consumeEscapedCodePoint(); - } - } - }; - Tokenizer.prototype.consumeStringSlice = function (count) { - var SLICE_STACK_SIZE = 50000; - var value = ''; - while (count > 0) { - var amount = Math.min(SLICE_STACK_SIZE, count); - value += fromCodePoint$1.apply(void 0, this._value.splice(0, amount)); - count -= amount; - } - this._value.shift(); - return value; - }; - Tokenizer.prototype.consumeStringToken = function (endingCodePoint) { - var value = ''; - var i = 0; - do { - var codePoint = this._value[i]; - if (codePoint === EOF || codePoint === undefined || codePoint === endingCodePoint) { - value += this.consumeStringSlice(i); - return { type: 0 /* STRING_TOKEN */, value: value }; - } - if (codePoint === LINE_FEED) { - this._value.splice(0, i); - return BAD_STRING_TOKEN; - } - if (codePoint === REVERSE_SOLIDUS) { - var next = this._value[i + 1]; - if (next !== EOF && next !== undefined) { - if (next === LINE_FEED) { - value += this.consumeStringSlice(i); - i = -1; - this._value.shift(); - } - else if (isValidEscape(codePoint, next)) { - value += this.consumeStringSlice(i); - value += fromCodePoint$1(this.consumeEscapedCodePoint()); - i = -1; - } - } - } - i++; - } while (true); - }; - Tokenizer.prototype.consumeNumber = function () { - var repr = []; - var type = FLAG_INTEGER; - var c1 = this.peekCodePoint(0); - if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) { - repr.push(this.consumeCodePoint()); - } - while (isDigit(this.peekCodePoint(0))) { - repr.push(this.consumeCodePoint()); - } - c1 = this.peekCodePoint(0); - var c2 = this.peekCodePoint(1); - if (c1 === FULL_STOP && isDigit(c2)) { - repr.push(this.consumeCodePoint(), this.consumeCodePoint()); - type = FLAG_NUMBER; - while (isDigit(this.peekCodePoint(0))) { - repr.push(this.consumeCodePoint()); - } - } - c1 = this.peekCodePoint(0); - c2 = this.peekCodePoint(1); - var c3 = this.peekCodePoint(2); - if ((c1 === E || c1 === e) && (((c2 === PLUS_SIGN || c2 === HYPHEN_MINUS) && isDigit(c3)) || isDigit(c2))) { - repr.push(this.consumeCodePoint(), this.consumeCodePoint()); - type = FLAG_NUMBER; - while (isDigit(this.peekCodePoint(0))) { - repr.push(this.consumeCodePoint()); - } - } - return [stringToNumber(repr), type]; - }; - Tokenizer.prototype.consumeNumericToken = function () { - var _a = this.consumeNumber(), number = _a[0], flags = _a[1]; - var c1 = this.peekCodePoint(0); - var c2 = this.peekCodePoint(1); - var c3 = this.peekCodePoint(2); - if (isIdentifierStart(c1, c2, c3)) { - var unit = this.consumeName(); - return { type: 15 /* DIMENSION_TOKEN */, number: number, flags: flags, unit: unit }; - } - if (c1 === PERCENTAGE_SIGN) { - this.consumeCodePoint(); - return { type: 16 /* PERCENTAGE_TOKEN */, number: number, flags: flags }; - } - return { type: 17 /* NUMBER_TOKEN */, number: number, flags: flags }; - }; - Tokenizer.prototype.consumeEscapedCodePoint = function () { - var codePoint = this.consumeCodePoint(); - if (isHex(codePoint)) { - var hex = fromCodePoint$1(codePoint); - while (isHex(this.peekCodePoint(0)) && hex.length < 6) { - hex += fromCodePoint$1(this.consumeCodePoint()); - } - if (isWhiteSpace(this.peekCodePoint(0))) { - this.consumeCodePoint(); - } - var hexCodePoint = parseInt(hex, 16); - if (hexCodePoint === 0 || isSurrogateCodePoint(hexCodePoint) || hexCodePoint > 0x10ffff) { - return REPLACEMENT_CHARACTER; - } - return hexCodePoint; - } - if (codePoint === EOF) { - return REPLACEMENT_CHARACTER; - } - return codePoint; - }; - Tokenizer.prototype.consumeName = function () { - var result = ''; - while (true) { - var codePoint = this.consumeCodePoint(); - if (isNameCodePoint(codePoint)) { - result += fromCodePoint$1(codePoint); - } - else if (isValidEscape(codePoint, this.peekCodePoint(0))) { - result += fromCodePoint$1(this.consumeEscapedCodePoint()); - } - else { - this.reconsumeCodePoint(codePoint); - return result; - } - } - }; - return Tokenizer; - }()); - - var Parser = /** @class */ (function () { - function Parser(tokens) { - this._tokens = tokens; - } - Parser.create = function (value) { - var tokenizer = new Tokenizer(); - tokenizer.write(value); - return new Parser(tokenizer.read()); - }; - Parser.parseValue = function (value) { - return Parser.create(value).parseComponentValue(); - }; - Parser.parseValues = function (value) { - return Parser.create(value).parseComponentValues(); - }; - Parser.prototype.parseComponentValue = function () { - var token = this.consumeToken(); - while (token.type === 31 /* WHITESPACE_TOKEN */) { - token = this.consumeToken(); - } - if (token.type === 32 /* EOF_TOKEN */) { - throw new SyntaxError("Error parsing CSS component value, unexpected EOF"); - } - this.reconsumeToken(token); - var value = this.consumeComponentValue(); - do { - token = this.consumeToken(); - } while (token.type === 31 /* WHITESPACE_TOKEN */); - if (token.type === 32 /* EOF_TOKEN */) { - return value; - } - throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one"); - }; - Parser.prototype.parseComponentValues = function () { - var values = []; - while (true) { - var value = this.consumeComponentValue(); - if (value.type === 32 /* EOF_TOKEN */) { - return values; - } - values.push(value); - values.push(); - } - }; - Parser.prototype.consumeComponentValue = function () { - var token = this.consumeToken(); - switch (token.type) { - case 11 /* LEFT_CURLY_BRACKET_TOKEN */: - case 28 /* LEFT_SQUARE_BRACKET_TOKEN */: - case 2 /* LEFT_PARENTHESIS_TOKEN */: - return this.consumeSimpleBlock(token.type); - case 19 /* FUNCTION_TOKEN */: - return this.consumeFunction(token); - } - return token; - }; - Parser.prototype.consumeSimpleBlock = function (type) { - var block = { type: type, values: [] }; - var token = this.consumeToken(); - while (true) { - if (token.type === 32 /* EOF_TOKEN */ || isEndingTokenFor(token, type)) { - return block; - } - this.reconsumeToken(token); - block.values.push(this.consumeComponentValue()); - token = this.consumeToken(); - } - }; - Parser.prototype.consumeFunction = function (functionToken) { - var cssFunction = { - name: functionToken.value, - values: [], - type: 18 /* FUNCTION */ - }; - while (true) { - var token = this.consumeToken(); - if (token.type === 32 /* EOF_TOKEN */ || token.type === 3 /* RIGHT_PARENTHESIS_TOKEN */) { - return cssFunction; - } - this.reconsumeToken(token); - cssFunction.values.push(this.consumeComponentValue()); - } - }; - Parser.prototype.consumeToken = function () { - var token = this._tokens.shift(); - return typeof token === 'undefined' ? EOF_TOKEN : token; - }; - Parser.prototype.reconsumeToken = function (token) { - this._tokens.unshift(token); - }; - return Parser; - }()); - var isDimensionToken = function (token) { return token.type === 15 /* DIMENSION_TOKEN */; }; - var isNumberToken = function (token) { return token.type === 17 /* NUMBER_TOKEN */; }; - var isIdentToken = function (token) { return token.type === 20 /* IDENT_TOKEN */; }; - var isStringToken = function (token) { return token.type === 0 /* STRING_TOKEN */; }; - var isIdentWithValue = function (token, value) { - return isIdentToken(token) && token.value === value; - }; - var nonWhiteSpace = function (token) { return token.type !== 31 /* WHITESPACE_TOKEN */; }; - var nonFunctionArgSeparator = function (token) { - return token.type !== 31 /* WHITESPACE_TOKEN */ && token.type !== 4 /* COMMA_TOKEN */; - }; - var parseFunctionArgs = function (tokens) { - var args = []; - var arg = []; - tokens.forEach(function (token) { - if (token.type === 4 /* COMMA_TOKEN */) { - if (arg.length === 0) { - throw new Error("Error parsing function args, zero tokens for arg"); - } - args.push(arg); - arg = []; - return; - } - if (token.type !== 31 /* WHITESPACE_TOKEN */) { - arg.push(token); - } - }); - if (arg.length) { - args.push(arg); - } - return args; - }; - var isEndingTokenFor = function (token, type) { - if (type === 11 /* LEFT_CURLY_BRACKET_TOKEN */ && token.type === 12 /* RIGHT_CURLY_BRACKET_TOKEN */) { - return true; - } - if (type === 28 /* LEFT_SQUARE_BRACKET_TOKEN */ && token.type === 29 /* RIGHT_SQUARE_BRACKET_TOKEN */) { - return true; - } - return type === 2 /* LEFT_PARENTHESIS_TOKEN */ && token.type === 3 /* RIGHT_PARENTHESIS_TOKEN */; - }; - - var isLength = function (token) { - return token.type === 17 /* NUMBER_TOKEN */ || token.type === 15 /* DIMENSION_TOKEN */; - }; - - var isLengthPercentage = function (token) { - return token.type === 16 /* PERCENTAGE_TOKEN */ || isLength(token); - }; - var parseLengthPercentageTuple = function (tokens) { - return tokens.length > 1 ? [tokens[0], tokens[1]] : [tokens[0]]; - }; - var ZERO_LENGTH = { - type: 17 /* NUMBER_TOKEN */, - number: 0, - flags: FLAG_INTEGER - }; - var FIFTY_PERCENT = { - type: 16 /* PERCENTAGE_TOKEN */, - number: 50, - flags: FLAG_INTEGER - }; - var HUNDRED_PERCENT = { - type: 16 /* PERCENTAGE_TOKEN */, - number: 100, - flags: FLAG_INTEGER - }; - var getAbsoluteValueForTuple = function (tuple, width, height) { - var x = tuple[0], y = tuple[1]; - return [getAbsoluteValue(x, width), getAbsoluteValue(typeof y !== 'undefined' ? y : x, height)]; - }; - var getAbsoluteValue = function (token, parent) { - if (token.type === 16 /* PERCENTAGE_TOKEN */) { - return (token.number / 100) * parent; - } - if (isDimensionToken(token)) { - switch (token.unit) { - case 'rem': - case 'em': - return 16 * token.number; // TODO use correct font-size - case 'px': - default: - return token.number; - } - } - return token.number; - }; - - var DEG = 'deg'; - var GRAD = 'grad'; - var RAD = 'rad'; - var TURN = 'turn'; - var angle = { - name: 'angle', - parse: function (_context, value) { - if (value.type === 15 /* DIMENSION_TOKEN */) { - switch (value.unit) { - case DEG: - return (Math.PI * value.number) / 180; - case GRAD: - return (Math.PI / 200) * value.number; - case RAD: - return value.number; - case TURN: - return Math.PI * 2 * value.number; - } - } - throw new Error("Unsupported angle type"); - } - }; - var isAngle = function (value) { - if (value.type === 15 /* DIMENSION_TOKEN */) { - if (value.unit === DEG || value.unit === GRAD || value.unit === RAD || value.unit === TURN) { - return true; - } - } - return false; - }; - var parseNamedSide = function (tokens) { - var sideOrCorner = tokens - .filter(isIdentToken) - .map(function (ident) { return ident.value; }) - .join(' '); - switch (sideOrCorner) { - case 'to bottom right': - case 'to right bottom': - case 'left top': - case 'top left': - return [ZERO_LENGTH, ZERO_LENGTH]; - case 'to top': - case 'bottom': - return deg(0); - case 'to bottom left': - case 'to left bottom': - case 'right top': - case 'top right': - return [ZERO_LENGTH, HUNDRED_PERCENT]; - case 'to right': - case 'left': - return deg(90); - case 'to top left': - case 'to left top': - case 'right bottom': - case 'bottom right': - return [HUNDRED_PERCENT, HUNDRED_PERCENT]; - case 'to bottom': - case 'top': - return deg(180); - case 'to top right': - case 'to right top': - case 'left bottom': - case 'bottom left': - return [HUNDRED_PERCENT, ZERO_LENGTH]; - case 'to left': - case 'right': - return deg(270); - } - return 0; - }; - var deg = function (deg) { return (Math.PI * deg) / 180; }; - - var color$1 = { - name: 'color', - parse: function (context, value) { - if (value.type === 18 /* FUNCTION */) { - var colorFunction = SUPPORTED_COLOR_FUNCTIONS[value.name]; - if (typeof colorFunction === 'undefined') { - throw new Error("Attempting to parse an unsupported color function \"" + value.name + "\""); - } - return colorFunction(context, value.values); - } - if (value.type === 5 /* HASH_TOKEN */) { - if (value.value.length === 3) { - var r = value.value.substring(0, 1); - var g = value.value.substring(1, 2); - var b = value.value.substring(2, 3); - return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), 1); - } - if (value.value.length === 4) { - var r = value.value.substring(0, 1); - var g = value.value.substring(1, 2); - var b = value.value.substring(2, 3); - var a = value.value.substring(3, 4); - return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), parseInt(a + a, 16) / 255); - } - if (value.value.length === 6) { - var r = value.value.substring(0, 2); - var g = value.value.substring(2, 4); - var b = value.value.substring(4, 6); - return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1); - } - if (value.value.length === 8) { - var r = value.value.substring(0, 2); - var g = value.value.substring(2, 4); - var b = value.value.substring(4, 6); - var a = value.value.substring(6, 8); - return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), parseInt(a, 16) / 255); - } - } - if (value.type === 20 /* IDENT_TOKEN */) { - var namedColor = COLORS[value.value.toUpperCase()]; - if (typeof namedColor !== 'undefined') { - return namedColor; - } - } - return COLORS.TRANSPARENT; - } - }; - var isTransparent = function (color) { return (0xff & color) === 0; }; - var asString = function (color) { - var alpha = 0xff & color; - var blue = 0xff & (color >> 8); - var green = 0xff & (color >> 16); - var red = 0xff & (color >> 24); - return alpha < 255 ? "rgba(" + red + "," + green + "," + blue + "," + alpha / 255 + ")" : "rgb(" + red + "," + green + "," + blue + ")"; - }; - var pack = function (r, g, b, a) { - return ((r << 24) | (g << 16) | (b << 8) | (Math.round(a * 255) << 0)) >>> 0; - }; - var getTokenColorValue = function (token, i) { - if (token.type === 17 /* NUMBER_TOKEN */) { - return token.number; - } - if (token.type === 16 /* PERCENTAGE_TOKEN */) { - var max = i === 3 ? 1 : 255; - return i === 3 ? (token.number / 100) * max : Math.round((token.number / 100) * max); - } - return 0; - }; - var rgb = function (_context, args) { - var tokens = args.filter(nonFunctionArgSeparator); - if (tokens.length === 3) { - var _a = tokens.map(getTokenColorValue), r = _a[0], g = _a[1], b = _a[2]; - return pack(r, g, b, 1); - } - if (tokens.length === 4) { - var _b = tokens.map(getTokenColorValue), r = _b[0], g = _b[1], b = _b[2], a = _b[3]; - return pack(r, g, b, a); - } - return 0; - }; - function hue2rgb(t1, t2, hue) { - if (hue < 0) { - hue += 1; - } - if (hue >= 1) { - hue -= 1; - } - if (hue < 1 / 6) { - return (t2 - t1) * hue * 6 + t1; - } - else if (hue < 1 / 2) { - return t2; - } - else if (hue < 2 / 3) { - return (t2 - t1) * 6 * (2 / 3 - hue) + t1; - } - else { - return t1; - } - } - var hsl = function (context, args) { - var tokens = args.filter(nonFunctionArgSeparator); - var hue = tokens[0], saturation = tokens[1], lightness = tokens[2], alpha = tokens[3]; - var h = (hue.type === 17 /* NUMBER_TOKEN */ ? deg(hue.number) : angle.parse(context, hue)) / (Math.PI * 2); - var s = isLengthPercentage(saturation) ? saturation.number / 100 : 0; - var l = isLengthPercentage(lightness) ? lightness.number / 100 : 0; - var a = typeof alpha !== 'undefined' && isLengthPercentage(alpha) ? getAbsoluteValue(alpha, 1) : 1; - if (s === 0) { - return pack(l * 255, l * 255, l * 255, 1); - } - var t2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; - var t1 = l * 2 - t2; - var r = hue2rgb(t1, t2, h + 1 / 3); - var g = hue2rgb(t1, t2, h); - var b = hue2rgb(t1, t2, h - 1 / 3); - return pack(r * 255, g * 255, b * 255, a); - }; - var SUPPORTED_COLOR_FUNCTIONS = { - hsl: hsl, - hsla: hsl, - rgb: rgb, - rgba: rgb - }; - var parseColor = function (context, value) { - return color$1.parse(context, Parser.create(value).parseComponentValue()); - }; - var COLORS = { - ALICEBLUE: 0xf0f8ffff, - ANTIQUEWHITE: 0xfaebd7ff, - AQUA: 0x00ffffff, - AQUAMARINE: 0x7fffd4ff, - AZURE: 0xf0ffffff, - BEIGE: 0xf5f5dcff, - BISQUE: 0xffe4c4ff, - BLACK: 0x000000ff, - BLANCHEDALMOND: 0xffebcdff, - BLUE: 0x0000ffff, - BLUEVIOLET: 0x8a2be2ff, - BROWN: 0xa52a2aff, - BURLYWOOD: 0xdeb887ff, - CADETBLUE: 0x5f9ea0ff, - CHARTREUSE: 0x7fff00ff, - CHOCOLATE: 0xd2691eff, - CORAL: 0xff7f50ff, - CORNFLOWERBLUE: 0x6495edff, - CORNSILK: 0xfff8dcff, - CRIMSON: 0xdc143cff, - CYAN: 0x00ffffff, - DARKBLUE: 0x00008bff, - DARKCYAN: 0x008b8bff, - DARKGOLDENROD: 0xb886bbff, - DARKGRAY: 0xa9a9a9ff, - DARKGREEN: 0x006400ff, - DARKGREY: 0xa9a9a9ff, - DARKKHAKI: 0xbdb76bff, - DARKMAGENTA: 0x8b008bff, - DARKOLIVEGREEN: 0x556b2fff, - DARKORANGE: 0xff8c00ff, - DARKORCHID: 0x9932ccff, - DARKRED: 0x8b0000ff, - DARKSALMON: 0xe9967aff, - DARKSEAGREEN: 0x8fbc8fff, - DARKSLATEBLUE: 0x483d8bff, - DARKSLATEGRAY: 0x2f4f4fff, - DARKSLATEGREY: 0x2f4f4fff, - DARKTURQUOISE: 0x00ced1ff, - DARKVIOLET: 0x9400d3ff, - DEEPPINK: 0xff1493ff, - DEEPSKYBLUE: 0x00bfffff, - DIMGRAY: 0x696969ff, - DIMGREY: 0x696969ff, - DODGERBLUE: 0x1e90ffff, - FIREBRICK: 0xb22222ff, - FLORALWHITE: 0xfffaf0ff, - FORESTGREEN: 0x228b22ff, - FUCHSIA: 0xff00ffff, - GAINSBORO: 0xdcdcdcff, - GHOSTWHITE: 0xf8f8ffff, - GOLD: 0xffd700ff, - GOLDENROD: 0xdaa520ff, - GRAY: 0x808080ff, - GREEN: 0x008000ff, - GREENYELLOW: 0xadff2fff, - GREY: 0x808080ff, - HONEYDEW: 0xf0fff0ff, - HOTPINK: 0xff69b4ff, - INDIANRED: 0xcd5c5cff, - INDIGO: 0x4b0082ff, - IVORY: 0xfffff0ff, - KHAKI: 0xf0e68cff, - LAVENDER: 0xe6e6faff, - LAVENDERBLUSH: 0xfff0f5ff, - LAWNGREEN: 0x7cfc00ff, - LEMONCHIFFON: 0xfffacdff, - LIGHTBLUE: 0xadd8e6ff, - LIGHTCORAL: 0xf08080ff, - LIGHTCYAN: 0xe0ffffff, - LIGHTGOLDENRODYELLOW: 0xfafad2ff, - LIGHTGRAY: 0xd3d3d3ff, - LIGHTGREEN: 0x90ee90ff, - LIGHTGREY: 0xd3d3d3ff, - LIGHTPINK: 0xffb6c1ff, - LIGHTSALMON: 0xffa07aff, - LIGHTSEAGREEN: 0x20b2aaff, - LIGHTSKYBLUE: 0x87cefaff, - LIGHTSLATEGRAY: 0x778899ff, - LIGHTSLATEGREY: 0x778899ff, - LIGHTSTEELBLUE: 0xb0c4deff, - LIGHTYELLOW: 0xffffe0ff, - LIME: 0x00ff00ff, - LIMEGREEN: 0x32cd32ff, - LINEN: 0xfaf0e6ff, - MAGENTA: 0xff00ffff, - MAROON: 0x800000ff, - MEDIUMAQUAMARINE: 0x66cdaaff, - MEDIUMBLUE: 0x0000cdff, - MEDIUMORCHID: 0xba55d3ff, - MEDIUMPURPLE: 0x9370dbff, - MEDIUMSEAGREEN: 0x3cb371ff, - MEDIUMSLATEBLUE: 0x7b68eeff, - MEDIUMSPRINGGREEN: 0x00fa9aff, - MEDIUMTURQUOISE: 0x48d1ccff, - MEDIUMVIOLETRED: 0xc71585ff, - MIDNIGHTBLUE: 0x191970ff, - MINTCREAM: 0xf5fffaff, - MISTYROSE: 0xffe4e1ff, - MOCCASIN: 0xffe4b5ff, - NAVAJOWHITE: 0xffdeadff, - NAVY: 0x000080ff, - OLDLACE: 0xfdf5e6ff, - OLIVE: 0x808000ff, - OLIVEDRAB: 0x6b8e23ff, - ORANGE: 0xffa500ff, - ORANGERED: 0xff4500ff, - ORCHID: 0xda70d6ff, - PALEGOLDENROD: 0xeee8aaff, - PALEGREEN: 0x98fb98ff, - PALETURQUOISE: 0xafeeeeff, - PALEVIOLETRED: 0xdb7093ff, - PAPAYAWHIP: 0xffefd5ff, - PEACHPUFF: 0xffdab9ff, - PERU: 0xcd853fff, - PINK: 0xffc0cbff, - PLUM: 0xdda0ddff, - POWDERBLUE: 0xb0e0e6ff, - PURPLE: 0x800080ff, - REBECCAPURPLE: 0x663399ff, - RED: 0xff0000ff, - ROSYBROWN: 0xbc8f8fff, - ROYALBLUE: 0x4169e1ff, - SADDLEBROWN: 0x8b4513ff, - SALMON: 0xfa8072ff, - SANDYBROWN: 0xf4a460ff, - SEAGREEN: 0x2e8b57ff, - SEASHELL: 0xfff5eeff, - SIENNA: 0xa0522dff, - SILVER: 0xc0c0c0ff, - SKYBLUE: 0x87ceebff, - SLATEBLUE: 0x6a5acdff, - SLATEGRAY: 0x708090ff, - SLATEGREY: 0x708090ff, - SNOW: 0xfffafaff, - SPRINGGREEN: 0x00ff7fff, - STEELBLUE: 0x4682b4ff, - TAN: 0xd2b48cff, - TEAL: 0x008080ff, - THISTLE: 0xd8bfd8ff, - TOMATO: 0xff6347ff, - TRANSPARENT: 0x00000000, - TURQUOISE: 0x40e0d0ff, - VIOLET: 0xee82eeff, - WHEAT: 0xf5deb3ff, - WHITE: 0xffffffff, - WHITESMOKE: 0xf5f5f5ff, - YELLOW: 0xffff00ff, - YELLOWGREEN: 0x9acd32ff - }; - - var backgroundClip = { - name: 'background-clip', - initialValue: 'border-box', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - return tokens.map(function (token) { - if (isIdentToken(token)) { - switch (token.value) { - case 'padding-box': - return 1 /* PADDING_BOX */; - case 'content-box': - return 2 /* CONTENT_BOX */; - } - } - return 0 /* BORDER_BOX */; - }); - } - }; - - var backgroundColor = { - name: "background-color", - initialValue: 'transparent', - prefix: false, - type: 3 /* TYPE_VALUE */, - format: 'color' - }; - - var parseColorStop = function (context, args) { - var color = color$1.parse(context, args[0]); - var stop = args[1]; - return stop && isLengthPercentage(stop) ? { color: color, stop: stop } : { color: color, stop: null }; - }; - var processColorStops = function (stops, lineLength) { - var first = stops[0]; - var last = stops[stops.length - 1]; - if (first.stop === null) { - first.stop = ZERO_LENGTH; - } - if (last.stop === null) { - last.stop = HUNDRED_PERCENT; - } - var processStops = []; - var previous = 0; - for (var i = 0; i < stops.length; i++) { - var stop_1 = stops[i].stop; - if (stop_1 !== null) { - var absoluteValue = getAbsoluteValue(stop_1, lineLength); - if (absoluteValue > previous) { - processStops.push(absoluteValue); - } - else { - processStops.push(previous); - } - previous = absoluteValue; - } - else { - processStops.push(null); - } - } - var gapBegin = null; - for (var i = 0; i < processStops.length; i++) { - var stop_2 = processStops[i]; - if (stop_2 === null) { - if (gapBegin === null) { - gapBegin = i; - } - } - else if (gapBegin !== null) { - var gapLength = i - gapBegin; - var beforeGap = processStops[gapBegin - 1]; - var gapValue = (stop_2 - beforeGap) / (gapLength + 1); - for (var g = 1; g <= gapLength; g++) { - processStops[gapBegin + g - 1] = gapValue * g; - } - gapBegin = null; - } - } - return stops.map(function (_a, i) { - var color = _a.color; - return { color: color, stop: Math.max(Math.min(1, processStops[i] / lineLength), 0) }; - }); - }; - var getAngleFromCorner = function (corner, width, height) { - var centerX = width / 2; - var centerY = height / 2; - var x = getAbsoluteValue(corner[0], width) - centerX; - var y = centerY - getAbsoluteValue(corner[1], height); - return (Math.atan2(y, x) + Math.PI * 2) % (Math.PI * 2); - }; - var calculateGradientDirection = function (angle, width, height) { - var radian = typeof angle === 'number' ? angle : getAngleFromCorner(angle, width, height); - var lineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian)); - var halfWidth = width / 2; - var halfHeight = height / 2; - var halfLineLength = lineLength / 2; - var yDiff = Math.sin(radian - Math.PI / 2) * halfLineLength; - var xDiff = Math.cos(radian - Math.PI / 2) * halfLineLength; - return [lineLength, halfWidth - xDiff, halfWidth + xDiff, halfHeight - yDiff, halfHeight + yDiff]; - }; - var distance = function (a, b) { return Math.sqrt(a * a + b * b); }; - var findCorner = function (width, height, x, y, closest) { - var corners = [ - [0, 0], - [0, height], - [width, 0], - [width, height] - ]; - return corners.reduce(function (stat, corner) { - var cx = corner[0], cy = corner[1]; - var d = distance(x - cx, y - cy); - if (closest ? d < stat.optimumDistance : d > stat.optimumDistance) { - return { - optimumCorner: corner, - optimumDistance: d - }; - } - return stat; - }, { - optimumDistance: closest ? Infinity : -Infinity, - optimumCorner: null - }).optimumCorner; - }; - var calculateRadius = function (gradient, x, y, width, height) { - var rx = 0; - var ry = 0; - switch (gradient.size) { - case 0 /* CLOSEST_SIDE */: - // The ending shape is sized so that that it exactly meets the side of the gradient box closest to the gradient’s center. - // If the shape is an ellipse, it exactly meets the closest side in each dimension. - if (gradient.shape === 0 /* CIRCLE */) { - rx = ry = Math.min(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height)); - } - else if (gradient.shape === 1 /* ELLIPSE */) { - rx = Math.min(Math.abs(x), Math.abs(x - width)); - ry = Math.min(Math.abs(y), Math.abs(y - height)); - } - break; - case 2 /* CLOSEST_CORNER */: - // The ending shape is sized so that that it passes through the corner of the gradient box closest to the gradient’s center. - // If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified. - if (gradient.shape === 0 /* CIRCLE */) { - rx = ry = Math.min(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height)); - } - else if (gradient.shape === 1 /* ELLIPSE */) { - // Compute the ratio ry/rx (which is to be the same as for "closest-side") - var c = Math.min(Math.abs(y), Math.abs(y - height)) / Math.min(Math.abs(x), Math.abs(x - width)); - var _a = findCorner(width, height, x, y, true), cx = _a[0], cy = _a[1]; - rx = distance(cx - x, (cy - y) / c); - ry = c * rx; - } - break; - case 1 /* FARTHEST_SIDE */: - // Same as closest-side, except the ending shape is sized based on the farthest side(s) - if (gradient.shape === 0 /* CIRCLE */) { - rx = ry = Math.max(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height)); - } - else if (gradient.shape === 1 /* ELLIPSE */) { - rx = Math.max(Math.abs(x), Math.abs(x - width)); - ry = Math.max(Math.abs(y), Math.abs(y - height)); - } - break; - case 3 /* FARTHEST_CORNER */: - // Same as closest-corner, except the ending shape is sized based on the farthest corner. - // If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified. - if (gradient.shape === 0 /* CIRCLE */) { - rx = ry = Math.max(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height)); - } - else if (gradient.shape === 1 /* ELLIPSE */) { - // Compute the ratio ry/rx (which is to be the same as for "farthest-side") - var c = Math.max(Math.abs(y), Math.abs(y - height)) / Math.max(Math.abs(x), Math.abs(x - width)); - var _b = findCorner(width, height, x, y, false), cx = _b[0], cy = _b[1]; - rx = distance(cx - x, (cy - y) / c); - ry = c * rx; - } - break; - } - if (Array.isArray(gradient.size)) { - rx = getAbsoluteValue(gradient.size[0], width); - ry = gradient.size.length === 2 ? getAbsoluteValue(gradient.size[1], height) : rx; - } - return [rx, ry]; - }; - - var linearGradient = function (context, tokens) { - var angle$1 = deg(180); - var stops = []; - parseFunctionArgs(tokens).forEach(function (arg, i) { - if (i === 0) { - var firstToken = arg[0]; - if (firstToken.type === 20 /* IDENT_TOKEN */ && firstToken.value === 'to') { - angle$1 = parseNamedSide(arg); - return; - } - else if (isAngle(firstToken)) { - angle$1 = angle.parse(context, firstToken); - return; - } - } - var colorStop = parseColorStop(context, arg); - stops.push(colorStop); - }); - return { angle: angle$1, stops: stops, type: 1 /* LINEAR_GRADIENT */ }; - }; - - var prefixLinearGradient = function (context, tokens) { - var angle$1 = deg(180); - var stops = []; - parseFunctionArgs(tokens).forEach(function (arg, i) { - if (i === 0) { - var firstToken = arg[0]; - if (firstToken.type === 20 /* IDENT_TOKEN */ && - ['top', 'left', 'right', 'bottom'].indexOf(firstToken.value) !== -1) { - angle$1 = parseNamedSide(arg); - return; - } - else if (isAngle(firstToken)) { - angle$1 = (angle.parse(context, firstToken) + deg(270)) % deg(360); - return; - } - } - var colorStop = parseColorStop(context, arg); - stops.push(colorStop); - }); - return { - angle: angle$1, - stops: stops, - type: 1 /* LINEAR_GRADIENT */ - }; - }; - - var webkitGradient = function (context, tokens) { - var angle = deg(180); - var stops = []; - var type = 1 /* LINEAR_GRADIENT */; - var shape = 0 /* CIRCLE */; - var size = 3 /* FARTHEST_CORNER */; - var position = []; - parseFunctionArgs(tokens).forEach(function (arg, i) { - var firstToken = arg[0]; - if (i === 0) { - if (isIdentToken(firstToken) && firstToken.value === 'linear') { - type = 1 /* LINEAR_GRADIENT */; - return; - } - else if (isIdentToken(firstToken) && firstToken.value === 'radial') { - type = 2 /* RADIAL_GRADIENT */; - return; - } - } - if (firstToken.type === 18 /* FUNCTION */) { - if (firstToken.name === 'from') { - var color = color$1.parse(context, firstToken.values[0]); - stops.push({ stop: ZERO_LENGTH, color: color }); - } - else if (firstToken.name === 'to') { - var color = color$1.parse(context, firstToken.values[0]); - stops.push({ stop: HUNDRED_PERCENT, color: color }); - } - else if (firstToken.name === 'color-stop') { - var values = firstToken.values.filter(nonFunctionArgSeparator); - if (values.length === 2) { - var color = color$1.parse(context, values[1]); - var stop_1 = values[0]; - if (isNumberToken(stop_1)) { - stops.push({ - stop: { type: 16 /* PERCENTAGE_TOKEN */, number: stop_1.number * 100, flags: stop_1.flags }, - color: color - }); - } - } - } - } - }); - return type === 1 /* LINEAR_GRADIENT */ - ? { - angle: (angle + deg(180)) % deg(360), - stops: stops, - type: type - } - : { size: size, shape: shape, stops: stops, position: position, type: type }; - }; - - var CLOSEST_SIDE = 'closest-side'; - var FARTHEST_SIDE = 'farthest-side'; - var CLOSEST_CORNER = 'closest-corner'; - var FARTHEST_CORNER = 'farthest-corner'; - var CIRCLE = 'circle'; - var ELLIPSE = 'ellipse'; - var COVER = 'cover'; - var CONTAIN = 'contain'; - var radialGradient = function (context, tokens) { - var shape = 0 /* CIRCLE */; - var size = 3 /* FARTHEST_CORNER */; - var stops = []; - var position = []; - parseFunctionArgs(tokens).forEach(function (arg, i) { - var isColorStop = true; - if (i === 0) { - var isAtPosition_1 = false; - isColorStop = arg.reduce(function (acc, token) { - if (isAtPosition_1) { - if (isIdentToken(token)) { - switch (token.value) { - case 'center': - position.push(FIFTY_PERCENT); - return acc; - case 'top': - case 'left': - position.push(ZERO_LENGTH); - return acc; - case 'right': - case 'bottom': - position.push(HUNDRED_PERCENT); - return acc; - } - } - else if (isLengthPercentage(token) || isLength(token)) { - position.push(token); - } - } - else if (isIdentToken(token)) { - switch (token.value) { - case CIRCLE: - shape = 0 /* CIRCLE */; - return false; - case ELLIPSE: - shape = 1 /* ELLIPSE */; - return false; - case 'at': - isAtPosition_1 = true; - return false; - case CLOSEST_SIDE: - size = 0 /* CLOSEST_SIDE */; - return false; - case COVER: - case FARTHEST_SIDE: - size = 1 /* FARTHEST_SIDE */; - return false; - case CONTAIN: - case CLOSEST_CORNER: - size = 2 /* CLOSEST_CORNER */; - return false; - case FARTHEST_CORNER: - size = 3 /* FARTHEST_CORNER */; - return false; - } - } - else if (isLength(token) || isLengthPercentage(token)) { - if (!Array.isArray(size)) { - size = []; - } - size.push(token); - return false; - } - return acc; - }, isColorStop); - } - if (isColorStop) { - var colorStop = parseColorStop(context, arg); - stops.push(colorStop); - } - }); - return { size: size, shape: shape, stops: stops, position: position, type: 2 /* RADIAL_GRADIENT */ }; - }; - - var prefixRadialGradient = function (context, tokens) { - var shape = 0 /* CIRCLE */; - var size = 3 /* FARTHEST_CORNER */; - var stops = []; - var position = []; - parseFunctionArgs(tokens).forEach(function (arg, i) { - var isColorStop = true; - if (i === 0) { - isColorStop = arg.reduce(function (acc, token) { - if (isIdentToken(token)) { - switch (token.value) { - case 'center': - position.push(FIFTY_PERCENT); - return false; - case 'top': - case 'left': - position.push(ZERO_LENGTH); - return false; - case 'right': - case 'bottom': - position.push(HUNDRED_PERCENT); - return false; - } - } - else if (isLengthPercentage(token) || isLength(token)) { - position.push(token); - return false; - } - return acc; - }, isColorStop); - } - else if (i === 1) { - isColorStop = arg.reduce(function (acc, token) { - if (isIdentToken(token)) { - switch (token.value) { - case CIRCLE: - shape = 0 /* CIRCLE */; - return false; - case ELLIPSE: - shape = 1 /* ELLIPSE */; - return false; - case CONTAIN: - case CLOSEST_SIDE: - size = 0 /* CLOSEST_SIDE */; - return false; - case FARTHEST_SIDE: - size = 1 /* FARTHEST_SIDE */; - return false; - case CLOSEST_CORNER: - size = 2 /* CLOSEST_CORNER */; - return false; - case COVER: - case FARTHEST_CORNER: - size = 3 /* FARTHEST_CORNER */; - return false; - } - } - else if (isLength(token) || isLengthPercentage(token)) { - if (!Array.isArray(size)) { - size = []; - } - size.push(token); - return false; - } - return acc; - }, isColorStop); - } - if (isColorStop) { - var colorStop = parseColorStop(context, arg); - stops.push(colorStop); - } - }); - return { size: size, shape: shape, stops: stops, position: position, type: 2 /* RADIAL_GRADIENT */ }; - }; - - var isLinearGradient = function (background) { - return background.type === 1 /* LINEAR_GRADIENT */; - }; - var isRadialGradient = function (background) { - return background.type === 2 /* RADIAL_GRADIENT */; - }; - var image = { - name: 'image', - parse: function (context, value) { - if (value.type === 22 /* URL_TOKEN */) { - var image_1 = { url: value.value, type: 0 /* URL */ }; - context.cache.addImage(value.value); - return image_1; - } - if (value.type === 18 /* FUNCTION */) { - var imageFunction = SUPPORTED_IMAGE_FUNCTIONS[value.name]; - if (typeof imageFunction === 'undefined') { - throw new Error("Attempting to parse an unsupported image function \"" + value.name + "\""); - } - return imageFunction(context, value.values); - } - throw new Error("Unsupported image type " + value.type); - } - }; - function isSupportedImage(value) { - return (!(value.type === 20 /* IDENT_TOKEN */ && value.value === 'none') && - (value.type !== 18 /* FUNCTION */ || !!SUPPORTED_IMAGE_FUNCTIONS[value.name])); - } - var SUPPORTED_IMAGE_FUNCTIONS = { - 'linear-gradient': linearGradient, - '-moz-linear-gradient': prefixLinearGradient, - '-ms-linear-gradient': prefixLinearGradient, - '-o-linear-gradient': prefixLinearGradient, - '-webkit-linear-gradient': prefixLinearGradient, - 'radial-gradient': radialGradient, - '-moz-radial-gradient': prefixRadialGradient, - '-ms-radial-gradient': prefixRadialGradient, - '-o-radial-gradient': prefixRadialGradient, - '-webkit-radial-gradient': prefixRadialGradient, - '-webkit-gradient': webkitGradient - }; - - var backgroundImage = { - name: 'background-image', - initialValue: 'none', - type: 1 /* LIST */, - prefix: false, - parse: function (context, tokens) { - if (tokens.length === 0) { - return []; - } - var first = tokens[0]; - if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') { - return []; - } - return tokens - .filter(function (value) { return nonFunctionArgSeparator(value) && isSupportedImage(value); }) - .map(function (value) { return image.parse(context, value); }); - } - }; - - var backgroundOrigin = { - name: 'background-origin', - initialValue: 'border-box', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - return tokens.map(function (token) { - if (isIdentToken(token)) { - switch (token.value) { - case 'padding-box': - return 1 /* PADDING_BOX */; - case 'content-box': - return 2 /* CONTENT_BOX */; - } - } - return 0 /* BORDER_BOX */; - }); - } - }; - - var backgroundPosition = { - name: 'background-position', - initialValue: '0% 0%', - type: 1 /* LIST */, - prefix: false, - parse: function (_context, tokens) { - return parseFunctionArgs(tokens) - .map(function (values) { return values.filter(isLengthPercentage); }) - .map(parseLengthPercentageTuple); - } - }; - - var backgroundRepeat = { - name: 'background-repeat', - initialValue: 'repeat', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - return parseFunctionArgs(tokens) - .map(function (values) { - return values - .filter(isIdentToken) - .map(function (token) { return token.value; }) - .join(' '); - }) - .map(parseBackgroundRepeat); - } - }; - var parseBackgroundRepeat = function (value) { - switch (value) { - case 'no-repeat': - return 1 /* NO_REPEAT */; - case 'repeat-x': - case 'repeat no-repeat': - return 2 /* REPEAT_X */; - case 'repeat-y': - case 'no-repeat repeat': - return 3 /* REPEAT_Y */; - case 'repeat': - default: - return 0 /* REPEAT */; - } - }; - - var BACKGROUND_SIZE; - (function (BACKGROUND_SIZE) { - BACKGROUND_SIZE["AUTO"] = "auto"; - BACKGROUND_SIZE["CONTAIN"] = "contain"; - BACKGROUND_SIZE["COVER"] = "cover"; - })(BACKGROUND_SIZE || (BACKGROUND_SIZE = {})); - var backgroundSize = { - name: 'background-size', - initialValue: '0', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - return parseFunctionArgs(tokens).map(function (values) { return values.filter(isBackgroundSizeInfoToken); }); - } - }; - var isBackgroundSizeInfoToken = function (value) { - return isIdentToken(value) || isLengthPercentage(value); - }; - - var borderColorForSide = function (side) { return ({ - name: "border-" + side + "-color", - initialValue: 'transparent', - prefix: false, - type: 3 /* TYPE_VALUE */, - format: 'color' - }); }; - var borderTopColor = borderColorForSide('top'); - var borderRightColor = borderColorForSide('right'); - var borderBottomColor = borderColorForSide('bottom'); - var borderLeftColor = borderColorForSide('left'); - - var borderRadiusForSide = function (side) { return ({ - name: "border-radius-" + side, - initialValue: '0 0', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - return parseLengthPercentageTuple(tokens.filter(isLengthPercentage)); - } - }); }; - var borderTopLeftRadius = borderRadiusForSide('top-left'); - var borderTopRightRadius = borderRadiusForSide('top-right'); - var borderBottomRightRadius = borderRadiusForSide('bottom-right'); - var borderBottomLeftRadius = borderRadiusForSide('bottom-left'); - - var borderStyleForSide = function (side) { return ({ - name: "border-" + side + "-style", - initialValue: 'solid', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, style) { - switch (style) { - case 'none': - return 0 /* NONE */; - case 'dashed': - return 2 /* DASHED */; - case 'dotted': - return 3 /* DOTTED */; - case 'double': - return 4 /* DOUBLE */; - } - return 1 /* SOLID */; - } - }); }; - var borderTopStyle = borderStyleForSide('top'); - var borderRightStyle = borderStyleForSide('right'); - var borderBottomStyle = borderStyleForSide('bottom'); - var borderLeftStyle = borderStyleForSide('left'); - - var borderWidthForSide = function (side) { return ({ - name: "border-" + side + "-width", - initialValue: '0', - type: 0 /* VALUE */, - prefix: false, - parse: function (_context, token) { - if (isDimensionToken(token)) { - return token.number; - } - return 0; - } - }); }; - var borderTopWidth = borderWidthForSide('top'); - var borderRightWidth = borderWidthForSide('right'); - var borderBottomWidth = borderWidthForSide('bottom'); - var borderLeftWidth = borderWidthForSide('left'); - - var color = { - name: "color", - initialValue: 'transparent', - prefix: false, - type: 3 /* TYPE_VALUE */, - format: 'color' - }; - - var direction = { - name: 'direction', - initialValue: 'ltr', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, direction) { - switch (direction) { - case 'rtl': - return 1 /* RTL */; - case 'ltr': - default: - return 0 /* LTR */; - } - } - }; - - var display = { - name: 'display', - initialValue: 'inline-block', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - return tokens.filter(isIdentToken).reduce(function (bit, token) { - return bit | parseDisplayValue(token.value); - }, 0 /* NONE */); - } - }; - var parseDisplayValue = function (display) { - switch (display) { - case 'block': - case '-webkit-box': - return 2 /* BLOCK */; - case 'inline': - return 4 /* INLINE */; - case 'run-in': - return 8 /* RUN_IN */; - case 'flow': - return 16 /* FLOW */; - case 'flow-root': - return 32 /* FLOW_ROOT */; - case 'table': - return 64 /* TABLE */; - case 'flex': - case '-webkit-flex': - return 128 /* FLEX */; - case 'grid': - case '-ms-grid': - return 256 /* GRID */; - case 'ruby': - return 512 /* RUBY */; - case 'subgrid': - return 1024 /* SUBGRID */; - case 'list-item': - return 2048 /* LIST_ITEM */; - case 'table-row-group': - return 4096 /* TABLE_ROW_GROUP */; - case 'table-header-group': - return 8192 /* TABLE_HEADER_GROUP */; - case 'table-footer-group': - return 16384 /* TABLE_FOOTER_GROUP */; - case 'table-row': - return 32768 /* TABLE_ROW */; - case 'table-cell': - return 65536 /* TABLE_CELL */; - case 'table-column-group': - return 131072 /* TABLE_COLUMN_GROUP */; - case 'table-column': - return 262144 /* TABLE_COLUMN */; - case 'table-caption': - return 524288 /* TABLE_CAPTION */; - case 'ruby-base': - return 1048576 /* RUBY_BASE */; - case 'ruby-text': - return 2097152 /* RUBY_TEXT */; - case 'ruby-base-container': - return 4194304 /* RUBY_BASE_CONTAINER */; - case 'ruby-text-container': - return 8388608 /* RUBY_TEXT_CONTAINER */; - case 'contents': - return 16777216 /* CONTENTS */; - case 'inline-block': - return 33554432 /* INLINE_BLOCK */; - case 'inline-list-item': - return 67108864 /* INLINE_LIST_ITEM */; - case 'inline-table': - return 134217728 /* INLINE_TABLE */; - case 'inline-flex': - return 268435456 /* INLINE_FLEX */; - case 'inline-grid': - return 536870912 /* INLINE_GRID */; - } - return 0 /* NONE */; - }; - - var float = { - name: 'float', - initialValue: 'none', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, float) { - switch (float) { - case 'left': - return 1 /* LEFT */; - case 'right': - return 2 /* RIGHT */; - case 'inline-start': - return 3 /* INLINE_START */; - case 'inline-end': - return 4 /* INLINE_END */; - } - return 0 /* NONE */; - } - }; - - var letterSpacing = { - name: 'letter-spacing', - initialValue: '0', - prefix: false, - type: 0 /* VALUE */, - parse: function (_context, token) { - if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'normal') { - return 0; - } - if (token.type === 17 /* NUMBER_TOKEN */) { - return token.number; - } - if (token.type === 15 /* DIMENSION_TOKEN */) { - return token.number; - } - return 0; - } - }; - - var LINE_BREAK; - (function (LINE_BREAK) { - LINE_BREAK["NORMAL"] = "normal"; - LINE_BREAK["STRICT"] = "strict"; - })(LINE_BREAK || (LINE_BREAK = {})); - var lineBreak = { - name: 'line-break', - initialValue: 'normal', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, lineBreak) { - switch (lineBreak) { - case 'strict': - return LINE_BREAK.STRICT; - case 'normal': - default: - return LINE_BREAK.NORMAL; - } - } - }; - - var lineHeight = { - name: 'line-height', - initialValue: 'normal', - prefix: false, - type: 4 /* TOKEN_VALUE */ - }; - var computeLineHeight = function (token, fontSize) { - if (isIdentToken(token) && token.value === 'normal') { - return 1.2 * fontSize; - } - else if (token.type === 17 /* NUMBER_TOKEN */) { - return fontSize * token.number; - } - else if (isLengthPercentage(token)) { - return getAbsoluteValue(token, fontSize); - } - return fontSize; - }; - - var listStyleImage = { - name: 'list-style-image', - initialValue: 'none', - type: 0 /* VALUE */, - prefix: false, - parse: function (context, token) { - if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') { - return null; - } - return image.parse(context, token); - } - }; - - var listStylePosition = { - name: 'list-style-position', - initialValue: 'outside', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, position) { - switch (position) { - case 'inside': - return 0 /* INSIDE */; - case 'outside': - default: - return 1 /* OUTSIDE */; - } - } - }; - - var listStyleType = { - name: 'list-style-type', - initialValue: 'none', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, type) { - switch (type) { - case 'disc': - return 0 /* DISC */; - case 'circle': - return 1 /* CIRCLE */; - case 'square': - return 2 /* SQUARE */; - case 'decimal': - return 3 /* DECIMAL */; - case 'cjk-decimal': - return 4 /* CJK_DECIMAL */; - case 'decimal-leading-zero': - return 5 /* DECIMAL_LEADING_ZERO */; - case 'lower-roman': - return 6 /* LOWER_ROMAN */; - case 'upper-roman': - return 7 /* UPPER_ROMAN */; - case 'lower-greek': - return 8 /* LOWER_GREEK */; - case 'lower-alpha': - return 9 /* LOWER_ALPHA */; - case 'upper-alpha': - return 10 /* UPPER_ALPHA */; - case 'arabic-indic': - return 11 /* ARABIC_INDIC */; - case 'armenian': - return 12 /* ARMENIAN */; - case 'bengali': - return 13 /* BENGALI */; - case 'cambodian': - return 14 /* CAMBODIAN */; - case 'cjk-earthly-branch': - return 15 /* CJK_EARTHLY_BRANCH */; - case 'cjk-heavenly-stem': - return 16 /* CJK_HEAVENLY_STEM */; - case 'cjk-ideographic': - return 17 /* CJK_IDEOGRAPHIC */; - case 'devanagari': - return 18 /* DEVANAGARI */; - case 'ethiopic-numeric': - return 19 /* ETHIOPIC_NUMERIC */; - case 'georgian': - return 20 /* GEORGIAN */; - case 'gujarati': - return 21 /* GUJARATI */; - case 'gurmukhi': - return 22 /* GURMUKHI */; - case 'hebrew': - return 22 /* HEBREW */; - case 'hiragana': - return 23 /* HIRAGANA */; - case 'hiragana-iroha': - return 24 /* HIRAGANA_IROHA */; - case 'japanese-formal': - return 25 /* JAPANESE_FORMAL */; - case 'japanese-informal': - return 26 /* JAPANESE_INFORMAL */; - case 'kannada': - return 27 /* KANNADA */; - case 'katakana': - return 28 /* KATAKANA */; - case 'katakana-iroha': - return 29 /* KATAKANA_IROHA */; - case 'khmer': - return 30 /* KHMER */; - case 'korean-hangul-formal': - return 31 /* KOREAN_HANGUL_FORMAL */; - case 'korean-hanja-formal': - return 32 /* KOREAN_HANJA_FORMAL */; - case 'korean-hanja-informal': - return 33 /* KOREAN_HANJA_INFORMAL */; - case 'lao': - return 34 /* LAO */; - case 'lower-armenian': - return 35 /* LOWER_ARMENIAN */; - case 'malayalam': - return 36 /* MALAYALAM */; - case 'mongolian': - return 37 /* MONGOLIAN */; - case 'myanmar': - return 38 /* MYANMAR */; - case 'oriya': - return 39 /* ORIYA */; - case 'persian': - return 40 /* PERSIAN */; - case 'simp-chinese-formal': - return 41 /* SIMP_CHINESE_FORMAL */; - case 'simp-chinese-informal': - return 42 /* SIMP_CHINESE_INFORMAL */; - case 'tamil': - return 43 /* TAMIL */; - case 'telugu': - return 44 /* TELUGU */; - case 'thai': - return 45 /* THAI */; - case 'tibetan': - return 46 /* TIBETAN */; - case 'trad-chinese-formal': - return 47 /* TRAD_CHINESE_FORMAL */; - case 'trad-chinese-informal': - return 48 /* TRAD_CHINESE_INFORMAL */; - case 'upper-armenian': - return 49 /* UPPER_ARMENIAN */; - case 'disclosure-open': - return 50 /* DISCLOSURE_OPEN */; - case 'disclosure-closed': - return 51 /* DISCLOSURE_CLOSED */; - case 'none': - default: - return -1 /* NONE */; - } - } - }; - - var marginForSide = function (side) { return ({ - name: "margin-" + side, - initialValue: '0', - prefix: false, - type: 4 /* TOKEN_VALUE */ - }); }; - var marginTop = marginForSide('top'); - var marginRight = marginForSide('right'); - var marginBottom = marginForSide('bottom'); - var marginLeft = marginForSide('left'); - - var overflow = { - name: 'overflow', - initialValue: 'visible', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - return tokens.filter(isIdentToken).map(function (overflow) { - switch (overflow.value) { - case 'hidden': - return 1 /* HIDDEN */; - case 'scroll': - return 2 /* SCROLL */; - case 'clip': - return 3 /* CLIP */; - case 'auto': - return 4 /* AUTO */; - case 'visible': - default: - return 0 /* VISIBLE */; - } - }); - } - }; - - var overflowWrap = { - name: 'overflow-wrap', - initialValue: 'normal', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, overflow) { - switch (overflow) { - case 'break-word': - return "break-word" /* BREAK_WORD */; - case 'normal': - default: - return "normal" /* NORMAL */; - } - } - }; - - var paddingForSide = function (side) { return ({ - name: "padding-" + side, - initialValue: '0', - prefix: false, - type: 3 /* TYPE_VALUE */, - format: 'length-percentage' - }); }; - var paddingTop = paddingForSide('top'); - var paddingRight = paddingForSide('right'); - var paddingBottom = paddingForSide('bottom'); - var paddingLeft = paddingForSide('left'); - - var textAlign = { - name: 'text-align', - initialValue: 'left', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, textAlign) { - switch (textAlign) { - case 'right': - return 2 /* RIGHT */; - case 'center': - case 'justify': - return 1 /* CENTER */; - case 'left': - default: - return 0 /* LEFT */; - } - } - }; - - var position = { - name: 'position', - initialValue: 'static', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, position) { - switch (position) { - case 'relative': - return 1 /* RELATIVE */; - case 'absolute': - return 2 /* ABSOLUTE */; - case 'fixed': - return 3 /* FIXED */; - case 'sticky': - return 4 /* STICKY */; - } - return 0 /* STATIC */; - } - }; - - var textShadow = { - name: 'text-shadow', - initialValue: 'none', - type: 1 /* LIST */, - prefix: false, - parse: function (context, tokens) { - if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) { - return []; - } - return parseFunctionArgs(tokens).map(function (values) { - var shadow = { - color: COLORS.TRANSPARENT, - offsetX: ZERO_LENGTH, - offsetY: ZERO_LENGTH, - blur: ZERO_LENGTH - }; - var c = 0; - for (var i = 0; i < values.length; i++) { - var token = values[i]; - if (isLength(token)) { - if (c === 0) { - shadow.offsetX = token; - } - else if (c === 1) { - shadow.offsetY = token; - } - else { - shadow.blur = token; - } - c++; - } - else { - shadow.color = color$1.parse(context, token); - } - } - return shadow; - }); - } - }; - - var textTransform = { - name: 'text-transform', - initialValue: 'none', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, textTransform) { - switch (textTransform) { - case 'uppercase': - return 2 /* UPPERCASE */; - case 'lowercase': - return 1 /* LOWERCASE */; - case 'capitalize': - return 3 /* CAPITALIZE */; - } - return 0 /* NONE */; - } - }; - - var transform$1 = { - name: 'transform', - initialValue: 'none', - prefix: true, - type: 0 /* VALUE */, - parse: function (_context, token) { - if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') { - return null; - } - if (token.type === 18 /* FUNCTION */) { - var transformFunction = SUPPORTED_TRANSFORM_FUNCTIONS[token.name]; - if (typeof transformFunction === 'undefined') { - throw new Error("Attempting to parse an unsupported transform function \"" + token.name + "\""); - } - return transformFunction(token.values); - } - return null; - } - }; - var matrix = function (args) { - var values = args.filter(function (arg) { return arg.type === 17 /* NUMBER_TOKEN */; }).map(function (arg) { return arg.number; }); - return values.length === 6 ? values : null; - }; - // doesn't support 3D transforms at the moment - var matrix3d = function (args) { - var values = args.filter(function (arg) { return arg.type === 17 /* NUMBER_TOKEN */; }).map(function (arg) { return arg.number; }); - var a1 = values[0], b1 = values[1]; values[2]; values[3]; var a2 = values[4], b2 = values[5]; values[6]; values[7]; values[8]; values[9]; values[10]; values[11]; var a4 = values[12], b4 = values[13]; values[14]; values[15]; - return values.length === 16 ? [a1, b1, a2, b2, a4, b4] : null; - }; - var SUPPORTED_TRANSFORM_FUNCTIONS = { - matrix: matrix, - matrix3d: matrix3d - }; - - var DEFAULT_VALUE = { - type: 16 /* PERCENTAGE_TOKEN */, - number: 50, - flags: FLAG_INTEGER - }; - var DEFAULT = [DEFAULT_VALUE, DEFAULT_VALUE]; - var transformOrigin = { - name: 'transform-origin', - initialValue: '50% 50%', - prefix: true, - type: 1 /* LIST */, - parse: function (_context, tokens) { - var origins = tokens.filter(isLengthPercentage); - if (origins.length !== 2) { - return DEFAULT; - } - return [origins[0], origins[1]]; - } - }; - - var visibility = { - name: 'visible', - initialValue: 'none', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, visibility) { - switch (visibility) { - case 'hidden': - return 1 /* HIDDEN */; - case 'collapse': - return 2 /* COLLAPSE */; - case 'visible': - default: - return 0 /* VISIBLE */; - } - } - }; - - var WORD_BREAK; - (function (WORD_BREAK) { - WORD_BREAK["NORMAL"] = "normal"; - WORD_BREAK["BREAK_ALL"] = "break-all"; - WORD_BREAK["KEEP_ALL"] = "keep-all"; - })(WORD_BREAK || (WORD_BREAK = {})); - var wordBreak = { - name: 'word-break', - initialValue: 'normal', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, wordBreak) { - switch (wordBreak) { - case 'break-all': - return WORD_BREAK.BREAK_ALL; - case 'keep-all': - return WORD_BREAK.KEEP_ALL; - case 'normal': - default: - return WORD_BREAK.NORMAL; - } - } - }; - - var zIndex = { - name: 'z-index', - initialValue: 'auto', - prefix: false, - type: 0 /* VALUE */, - parse: function (_context, token) { - if (token.type === 20 /* IDENT_TOKEN */) { - return { auto: true, order: 0 }; - } - if (isNumberToken(token)) { - return { auto: false, order: token.number }; - } - throw new Error("Invalid z-index number parsed"); - } - }; - - var time = { - name: 'time', - parse: function (_context, value) { - if (value.type === 15 /* DIMENSION_TOKEN */) { - switch (value.unit.toLowerCase()) { - case 's': - return 1000 * value.number; - case 'ms': - return value.number; - } - } - throw new Error("Unsupported time type"); - } - }; - - var opacity = { - name: 'opacity', - initialValue: '1', - type: 0 /* VALUE */, - prefix: false, - parse: function (_context, token) { - if (isNumberToken(token)) { - return token.number; - } - return 1; - } - }; - - var textDecorationColor = { - name: "text-decoration-color", - initialValue: 'transparent', - prefix: false, - type: 3 /* TYPE_VALUE */, - format: 'color' - }; - - var textDecorationLine = { - name: 'text-decoration-line', - initialValue: 'none', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - return tokens - .filter(isIdentToken) - .map(function (token) { - switch (token.value) { - case 'underline': - return 1 /* UNDERLINE */; - case 'overline': - return 2 /* OVERLINE */; - case 'line-through': - return 3 /* LINE_THROUGH */; - case 'none': - return 4 /* BLINK */; - } - return 0 /* NONE */; - }) - .filter(function (line) { return line !== 0 /* NONE */; }); - } - }; - - var fontFamily = { - name: "font-family", - initialValue: '', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - var accumulator = []; - var results = []; - tokens.forEach(function (token) { - switch (token.type) { - case 20 /* IDENT_TOKEN */: - case 0 /* STRING_TOKEN */: - accumulator.push(token.value); - break; - case 17 /* NUMBER_TOKEN */: - accumulator.push(token.number.toString()); - break; - case 4 /* COMMA_TOKEN */: - results.push(accumulator.join(' ')); - accumulator.length = 0; - break; - } - }); - if (accumulator.length) { - results.push(accumulator.join(' ')); - } - return results.map(function (result) { return (result.indexOf(' ') === -1 ? result : "'" + result + "'"); }); - } - }; - - var fontSize = { - name: "font-size", - initialValue: '0', - prefix: false, - type: 3 /* TYPE_VALUE */, - format: 'length' - }; - - var fontWeight = { - name: 'font-weight', - initialValue: 'normal', - type: 0 /* VALUE */, - prefix: false, - parse: function (_context, token) { - if (isNumberToken(token)) { - return token.number; - } - if (isIdentToken(token)) { - switch (token.value) { - case 'bold': - return 700; - case 'normal': - default: - return 400; - } - } - return 400; - } - }; - - var fontVariant = { - name: 'font-variant', - initialValue: 'none', - type: 1 /* LIST */, - prefix: false, - parse: function (_context, tokens) { - return tokens.filter(isIdentToken).map(function (token) { return token.value; }); - } - }; - - var fontStyle = { - name: 'font-style', - initialValue: 'normal', - prefix: false, - type: 2 /* IDENT_VALUE */, - parse: function (_context, overflow) { - switch (overflow) { - case 'oblique': - return "oblique" /* OBLIQUE */; - case 'italic': - return "italic" /* ITALIC */; - case 'normal': - default: - return "normal" /* NORMAL */; - } - } - }; - - var contains = function (bit, value) { return (bit & value) !== 0; }; - - var content = { - name: 'content', - initialValue: 'none', - type: 1 /* LIST */, - prefix: false, - parse: function (_context, tokens) { - if (tokens.length === 0) { - return []; - } - var first = tokens[0]; - if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') { - return []; - } - return tokens; - } - }; - - var counterIncrement = { - name: 'counter-increment', - initialValue: 'none', - prefix: true, - type: 1 /* LIST */, - parse: function (_context, tokens) { - if (tokens.length === 0) { - return null; - } - var first = tokens[0]; - if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') { - return null; - } - var increments = []; - var filtered = tokens.filter(nonWhiteSpace); - for (var i = 0; i < filtered.length; i++) { - var counter = filtered[i]; - var next = filtered[i + 1]; - if (counter.type === 20 /* IDENT_TOKEN */) { - var increment = next && isNumberToken(next) ? next.number : 1; - increments.push({ counter: counter.value, increment: increment }); - } - } - return increments; - } - }; - - var counterReset = { - name: 'counter-reset', - initialValue: 'none', - prefix: true, - type: 1 /* LIST */, - parse: function (_context, tokens) { - if (tokens.length === 0) { - return []; - } - var resets = []; - var filtered = tokens.filter(nonWhiteSpace); - for (var i = 0; i < filtered.length; i++) { - var counter = filtered[i]; - var next = filtered[i + 1]; - if (isIdentToken(counter) && counter.value !== 'none') { - var reset = next && isNumberToken(next) ? next.number : 0; - resets.push({ counter: counter.value, reset: reset }); - } - } - return resets; - } - }; - - var duration = { - name: 'duration', - initialValue: '0s', - prefix: false, - type: 1 /* LIST */, - parse: function (context, tokens) { - return tokens.filter(isDimensionToken).map(function (token) { return time.parse(context, token); }); - } - }; - - var quotes = { - name: 'quotes', - initialValue: 'none', - prefix: true, - type: 1 /* LIST */, - parse: function (_context, tokens) { - if (tokens.length === 0) { - return null; - } - var first = tokens[0]; - if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') { - return null; - } - var quotes = []; - var filtered = tokens.filter(isStringToken); - if (filtered.length % 2 !== 0) { - return null; - } - for (var i = 0; i < filtered.length; i += 2) { - var open_1 = filtered[i].value; - var close_1 = filtered[i + 1].value; - quotes.push({ open: open_1, close: close_1 }); - } - return quotes; - } - }; - var getQuote = function (quotes, depth, open) { - if (!quotes) { - return ''; - } - var quote = quotes[Math.min(depth, quotes.length - 1)]; - if (!quote) { - return ''; - } - return open ? quote.open : quote.close; - }; - - var paintOrder = { - name: 'paint-order', - initialValue: 'normal', - prefix: false, - type: 1 /* LIST */, - parse: function (_context, tokens) { - var DEFAULT_VALUE = [0 /* FILL */, 1 /* STROKE */, 2 /* MARKERS */]; - var layers = []; - tokens.filter(isIdentToken).forEach(function (token) { - switch (token.value) { - case 'stroke': - layers.push(1 /* STROKE */); - break; - case 'fill': - layers.push(0 /* FILL */); - break; - case 'markers': - layers.push(2 /* MARKERS */); - break; - } - }); - DEFAULT_VALUE.forEach(function (value) { - if (layers.indexOf(value) === -1) { - layers.push(value); - } - }); - return layers; - } - }; - - var webkitTextStrokeColor = { - name: "-webkit-text-stroke-color", - initialValue: 'currentcolor', - prefix: false, - type: 3 /* TYPE_VALUE */, - format: 'color' - }; - - var webkitTextStrokeWidth = { - name: "-webkit-text-stroke-width", - initialValue: '0', - type: 0 /* VALUE */, - prefix: false, - parse: function (_context, token) { - if (isDimensionToken(token)) { - return token.number; - } - return 0; - } - }; - - var CSSParsedDeclaration = /** @class */ (function () { - function CSSParsedDeclaration(context, declaration) { - var _a, _b; - this.animationDuration = parse(context, duration, declaration.animationDuration); - this.backgroundClip = parse(context, backgroundClip, declaration.backgroundClip); - this.backgroundColor = parse(context, backgroundColor, declaration.backgroundColor); - this.backgroundImage = parse(context, backgroundImage, declaration.backgroundImage); - this.backgroundOrigin = parse(context, backgroundOrigin, declaration.backgroundOrigin); - this.backgroundPosition = parse(context, backgroundPosition, declaration.backgroundPosition); - this.backgroundRepeat = parse(context, backgroundRepeat, declaration.backgroundRepeat); - this.backgroundSize = parse(context, backgroundSize, declaration.backgroundSize); - this.borderTopColor = parse(context, borderTopColor, declaration.borderTopColor); - this.borderRightColor = parse(context, borderRightColor, declaration.borderRightColor); - this.borderBottomColor = parse(context, borderBottomColor, declaration.borderBottomColor); - this.borderLeftColor = parse(context, borderLeftColor, declaration.borderLeftColor); - this.borderTopLeftRadius = parse(context, borderTopLeftRadius, declaration.borderTopLeftRadius); - this.borderTopRightRadius = parse(context, borderTopRightRadius, declaration.borderTopRightRadius); - this.borderBottomRightRadius = parse(context, borderBottomRightRadius, declaration.borderBottomRightRadius); - this.borderBottomLeftRadius = parse(context, borderBottomLeftRadius, declaration.borderBottomLeftRadius); - this.borderTopStyle = parse(context, borderTopStyle, declaration.borderTopStyle); - this.borderRightStyle = parse(context, borderRightStyle, declaration.borderRightStyle); - this.borderBottomStyle = parse(context, borderBottomStyle, declaration.borderBottomStyle); - this.borderLeftStyle = parse(context, borderLeftStyle, declaration.borderLeftStyle); - this.borderTopWidth = parse(context, borderTopWidth, declaration.borderTopWidth); - this.borderRightWidth = parse(context, borderRightWidth, declaration.borderRightWidth); - this.borderBottomWidth = parse(context, borderBottomWidth, declaration.borderBottomWidth); - this.borderLeftWidth = parse(context, borderLeftWidth, declaration.borderLeftWidth); - this.color = parse(context, color, declaration.color); - this.direction = parse(context, direction, declaration.direction); - this.display = parse(context, display, declaration.display); - this.float = parse(context, float, declaration.cssFloat); - this.fontFamily = parse(context, fontFamily, declaration.fontFamily); - this.fontSize = parse(context, fontSize, declaration.fontSize); - this.fontStyle = parse(context, fontStyle, declaration.fontStyle); - this.fontVariant = parse(context, fontVariant, declaration.fontVariant); - this.fontWeight = parse(context, fontWeight, declaration.fontWeight); - this.letterSpacing = parse(context, letterSpacing, declaration.letterSpacing); - this.lineBreak = parse(context, lineBreak, declaration.lineBreak); - this.lineHeight = parse(context, lineHeight, declaration.lineHeight); - this.listStyleImage = parse(context, listStyleImage, declaration.listStyleImage); - this.listStylePosition = parse(context, listStylePosition, declaration.listStylePosition); - this.listStyleType = parse(context, listStyleType, declaration.listStyleType); - this.marginTop = parse(context, marginTop, declaration.marginTop); - this.marginRight = parse(context, marginRight, declaration.marginRight); - this.marginBottom = parse(context, marginBottom, declaration.marginBottom); - this.marginLeft = parse(context, marginLeft, declaration.marginLeft); - this.opacity = parse(context, opacity, declaration.opacity); - var overflowTuple = parse(context, overflow, declaration.overflow); - this.overflowX = overflowTuple[0]; - this.overflowY = overflowTuple[overflowTuple.length > 1 ? 1 : 0]; - this.overflowWrap = parse(context, overflowWrap, declaration.overflowWrap); - this.paddingTop = parse(context, paddingTop, declaration.paddingTop); - this.paddingRight = parse(context, paddingRight, declaration.paddingRight); - this.paddingBottom = parse(context, paddingBottom, declaration.paddingBottom); - this.paddingLeft = parse(context, paddingLeft, declaration.paddingLeft); - this.paintOrder = parse(context, paintOrder, declaration.paintOrder); - this.position = parse(context, position, declaration.position); - this.textAlign = parse(context, textAlign, declaration.textAlign); - this.textDecorationColor = parse(context, textDecorationColor, (_a = declaration.textDecorationColor) !== null && _a !== void 0 ? _a : declaration.color); - this.textDecorationLine = parse(context, textDecorationLine, (_b = declaration.textDecorationLine) !== null && _b !== void 0 ? _b : declaration.textDecoration); - this.textShadow = parse(context, textShadow, declaration.textShadow); - this.textTransform = parse(context, textTransform, declaration.textTransform); - this.transform = parse(context, transform$1, declaration.transform); - this.transformOrigin = parse(context, transformOrigin, declaration.transformOrigin); - this.visibility = parse(context, visibility, declaration.visibility); - this.webkitTextStrokeColor = parse(context, webkitTextStrokeColor, declaration.webkitTextStrokeColor); - this.webkitTextStrokeWidth = parse(context, webkitTextStrokeWidth, declaration.webkitTextStrokeWidth); - this.wordBreak = parse(context, wordBreak, declaration.wordBreak); - this.zIndex = parse(context, zIndex, declaration.zIndex); - } - CSSParsedDeclaration.prototype.isVisible = function () { - return this.display > 0 && this.opacity > 0 && this.visibility === 0 /* VISIBLE */; - }; - CSSParsedDeclaration.prototype.isTransparent = function () { - return isTransparent(this.backgroundColor); - }; - CSSParsedDeclaration.prototype.isTransformed = function () { - return this.transform !== null; - }; - CSSParsedDeclaration.prototype.isPositioned = function () { - return this.position !== 0 /* STATIC */; - }; - CSSParsedDeclaration.prototype.isPositionedWithZIndex = function () { - return this.isPositioned() && !this.zIndex.auto; - }; - CSSParsedDeclaration.prototype.isFloating = function () { - return this.float !== 0 /* NONE */; - }; - CSSParsedDeclaration.prototype.isInlineLevel = function () { - return (contains(this.display, 4 /* INLINE */) || - contains(this.display, 33554432 /* INLINE_BLOCK */) || - contains(this.display, 268435456 /* INLINE_FLEX */) || - contains(this.display, 536870912 /* INLINE_GRID */) || - contains(this.display, 67108864 /* INLINE_LIST_ITEM */) || - contains(this.display, 134217728 /* INLINE_TABLE */)); - }; - return CSSParsedDeclaration; - }()); - var CSSParsedPseudoDeclaration = /** @class */ (function () { - function CSSParsedPseudoDeclaration(context, declaration) { - this.content = parse(context, content, declaration.content); - this.quotes = parse(context, quotes, declaration.quotes); - } - return CSSParsedPseudoDeclaration; - }()); - var CSSParsedCounterDeclaration = /** @class */ (function () { - function CSSParsedCounterDeclaration(context, declaration) { - this.counterIncrement = parse(context, counterIncrement, declaration.counterIncrement); - this.counterReset = parse(context, counterReset, declaration.counterReset); - } - return CSSParsedCounterDeclaration; - }()); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var parse = function (context, descriptor, style) { - var tokenizer = new Tokenizer(); - var value = style !== null && typeof style !== 'undefined' ? style.toString() : descriptor.initialValue; - tokenizer.write(value); - var parser = new Parser(tokenizer.read()); - switch (descriptor.type) { - case 2 /* IDENT_VALUE */: - var token = parser.parseComponentValue(); - return descriptor.parse(context, isIdentToken(token) ? token.value : descriptor.initialValue); - case 0 /* VALUE */: - return descriptor.parse(context, parser.parseComponentValue()); - case 1 /* LIST */: - return descriptor.parse(context, parser.parseComponentValues()); - case 4 /* TOKEN_VALUE */: - return parser.parseComponentValue(); - case 3 /* TYPE_VALUE */: - switch (descriptor.format) { - case 'angle': - return angle.parse(context, parser.parseComponentValue()); - case 'color': - return color$1.parse(context, parser.parseComponentValue()); - case 'image': - return image.parse(context, parser.parseComponentValue()); - case 'length': - var length_1 = parser.parseComponentValue(); - return isLength(length_1) ? length_1 : ZERO_LENGTH; - case 'length-percentage': - var value_1 = parser.parseComponentValue(); - return isLengthPercentage(value_1) ? value_1 : ZERO_LENGTH; - case 'time': - return time.parse(context, parser.parseComponentValue()); - } - break; - } - }; - - var elementDebuggerAttribute = 'data-html2canvas-debug'; - var getElementDebugType = function (element) { - var attribute = element.getAttribute(elementDebuggerAttribute); - switch (attribute) { - case 'all': - return 1 /* ALL */; - case 'clone': - return 2 /* CLONE */; - case 'parse': - return 3 /* PARSE */; - case 'render': - return 4 /* RENDER */; - default: - return 0 /* NONE */; - } - }; - var isDebugging = function (element, type) { - var elementType = getElementDebugType(element); - return elementType === 1 /* ALL */ || type === elementType; - }; - - var ElementContainer = /** @class */ (function () { - function ElementContainer(context, element) { - this.context = context; - this.textNodes = []; - this.elements = []; - this.flags = 0; - if (isDebugging(element, 3 /* PARSE */)) { - debugger; - } - this.styles = new CSSParsedDeclaration(context, window.getComputedStyle(element, null)); - if (isHTMLElementNode(element)) { - if (this.styles.animationDuration.some(function (duration) { return duration > 0; })) { - element.style.animationDuration = '0s'; - } - if (this.styles.transform !== null) { - // getBoundingClientRect takes transforms into account - element.style.transform = 'none'; - } - } - this.bounds = parseBounds(this.context, element); - if (isDebugging(element, 4 /* RENDER */)) { - this.flags |= 16 /* DEBUG_RENDER */; - } - } - return ElementContainer; - }()); - - /* - * text-segmentation 1.0.3 - * Copyright (c) 2022 Niklas von Hertzen - * Released under MIT License - */ - var base64 = 'AAAAAAAAAAAAEA4AGBkAAFAaAAACAAAAAAAIABAAGAAwADgACAAQAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAgAEAAIABAAQABIAEQATAAIABAACAAQAAgAEAAIABAAVABcAAgAEAAIABAACAAQAGAAaABwAHgAgACIAI4AlgAIABAAmwCjAKgAsAC2AL4AvQDFAMoA0gBPAVYBWgEIAAgACACMANoAYgFkAWwBdAF8AX0BhQGNAZUBlgGeAaMBlQGWAasBswF8AbsBwwF0AcsBYwHTAQgA2wG/AOMBdAF8AekB8QF0AfkB+wHiAHQBfAEIAAMC5gQIAAsCEgIIAAgAFgIeAggAIgIpAggAMQI5AkACygEIAAgASAJQAlgCYAIIAAgACAAKBQoFCgUTBRMFGQUrBSsFCAAIAAgACAAIAAgACAAIAAgACABdAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABoAmgCrwGvAQgAbgJ2AggAHgEIAAgACADnAXsCCAAIAAgAgwIIAAgACAAIAAgACACKAggAkQKZAggAPADJAAgAoQKkAqwCsgK6AsICCADJAggA0AIIAAgACAAIANYC3gIIAAgACAAIAAgACABAAOYCCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAkASoB+QIEAAgACAA8AEMCCABCBQgACABJBVAFCAAIAAgACAAIAAgACAAIAAgACABTBVoFCAAIAFoFCABfBWUFCAAIAAgACAAIAAgAbQUIAAgACAAIAAgACABzBXsFfQWFBYoFigWKBZEFigWKBYoFmAWfBaYFrgWxBbkFCAAIAAgACAAIAAgACAAIAAgACAAIAMEFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAMgFCADQBQgACAAIAAgACAAIAAgACAAIAAgACAAIAO4CCAAIAAgAiQAIAAgACABAAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAD0AggACAD8AggACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIANYFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAMDvwAIAAgAJAIIAAgACAAIAAgACAAIAAgACwMTAwgACAB9BOsEGwMjAwgAKwMyAwsFYgE3A/MEPwMIAEUDTQNRAwgAWQOsAGEDCAAIAAgACAAIAAgACABpAzQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFIQUoBSwFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABtAwgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABMAEwACAAIAAgACAAIABgACAAIAAgACAC/AAgACAAyAQgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACAAIAAwAAgACAAIAAgACAAIAAgACAAIAAAARABIAAgACAAIABQASAAIAAgAIABwAEAAjgCIABsAqAC2AL0AigDQAtwC+IJIQqVAZUBWQqVAZUBlQGVAZUBlQGrC5UBlQGVAZUBlQGVAZUBlQGVAXsKlQGVAbAK6wsrDGUMpQzlDJUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAfAKAAuZA64AtwCJALoC6ADwAAgAuACgA/oEpgO6AqsD+AAIAAgAswMIAAgACAAIAIkAuwP5AfsBwwPLAwgACAAIAAgACADRA9kDCAAIAOED6QMIAAgACAAIAAgACADuA/YDCAAIAP4DyQAIAAgABgQIAAgAXQAOBAgACAAIAAgACAAIABMECAAIAAgACAAIAAgACAD8AAQBCAAIAAgAGgQiBCoECAExBAgAEAEIAAgACAAIAAgACAAIAAgACAAIAAgACAA4BAgACABABEYECAAIAAgATAQYAQgAVAQIAAgACAAIAAgACAAIAAgACAAIAFoECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAOQEIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAB+BAcACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAEABhgSMBAgACAAIAAgAlAQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAwAEAAQABAADAAMAAwADAAQABAAEAAQABAAEAAQABHATAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAdQMIAAgACAAIAAgACAAIAMkACAAIAAgAfQMIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACFA4kDCAAIAAgACAAIAOcBCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAIcDCAAIAAgACAAIAAgACAAIAAgACAAIAJEDCAAIAAgACADFAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABgBAgAZgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAbAQCBXIECAAIAHkECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABAAJwEQACjBKoEsgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAC6BMIECAAIAAgACAAIAAgACABmBAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAxwQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAGYECAAIAAgAzgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBd0FXwUIAOIF6gXxBYoF3gT5BQAGCAaKBYoFigWKBYoFigWKBYoFigWKBYoFigXWBIoFigWKBYoFigWKBYoFigWKBYsFEAaKBYoFigWKBYoFigWKBRQGCACKBYoFigWKBQgACAAIANEECAAIABgGigUgBggAJgYIAC4GMwaKBYoF0wQ3Bj4GigWKBYoFigWKBYoFigWKBYoFigWKBYoFigUIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWLBf///////wQABAAEAAQABAAEAAQABAAEAAQAAwAEAAQAAgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAQADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUAAAAFAAUAAAAFAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAQAAAAUABQAFAAUABQAFAAAAAAAFAAUAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAFAAUAAQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAAABwAHAAcAAAAHAAcABwAFAAEAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAcABwAFAAUAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQABAAAAAAAAAAAAAAAFAAUABQAFAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAHAAcAAAAHAAcAAAAAAAUABQAHAAUAAQAHAAEABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwABAAUABQAFAAUAAAAAAAAAAAAAAAEAAQABAAEAAQABAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABQANAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAABQAHAAUABQAFAAAAAAAAAAcABQAFAAUABQAFAAQABAAEAAQABAAEAAQABAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUAAAAFAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAUAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAcABwAFAAcABwAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUABwAHAAUABQAFAAUAAAAAAAcABwAAAAAABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAAAAAAAAAAABQAFAAAAAAAFAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAFAAUABQAFAAUAAAAFAAUABwAAAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABwAFAAUABQAFAAAAAAAHAAcAAAAAAAcABwAFAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAAAAAAAAAHAAcABwAAAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAUABQAFAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAHAAcABQAHAAcAAAAFAAcABwAAAAcABwAFAAUAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAFAAcABwAFAAUABQAAAAUAAAAHAAcABwAHAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAHAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUAAAAFAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAUAAAAFAAUAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABwAFAAUABQAFAAUABQAAAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABQAFAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAFAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAHAAUABQAFAAUABQAFAAUABwAHAAcABwAHAAcABwAHAAUABwAHAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABwAHAAcABwAFAAUABwAHAAcAAAAAAAAAAAAHAAcABQAHAAcABwAHAAcABwAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAUABQAFAAUABQAFAAUAAAAFAAAABQAAAAAABQAFAAUABQAFAAUABQAFAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAUABQAFAAUABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABwAFAAcABwAHAAcABwAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAUABQAFAAUABwAHAAUABQAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABQAFAAcABwAHAAUABwAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAcABQAFAAUABQAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAAAAAABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAAAAAAAAAFAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAUABQAHAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAFAAUABQAFAAcABwAFAAUABwAHAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAcABwAFAAUABwAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABQAAAAAABQAFAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAcABwAAAAAAAAAAAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAcABwAFAAcABwAAAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAFAAUABQAAAAUABQAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABwAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAHAAcABQAHAAUABQAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAAABwAHAAAAAAAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAFAAUABwAFAAcABwAFAAcABQAFAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAAAAAABwAHAAcABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAFAAcABwAFAAUABQAFAAUABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAUABQAFAAcABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABQAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAAAAAAFAAUABwAHAAcABwAFAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAHAAUABQAFAAUABQAFAAUABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAABQAAAAUABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAHAAcAAAAFAAUAAAAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABQAFAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAABQAFAAUABQAFAAUABQAAAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAFAAUABQAFAAUADgAOAA4ADgAOAA4ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAMAAwADAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAAAAAAAAAAAAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAAAAAAAAAAAAsADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwACwAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAADgAOAA4AAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAAAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4AAAAOAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAAAAAAAAAAAA4AAAAOAAAAAAAAAAAADgAOAA4AAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAA='; - - /* - * utrie 1.0.2 - * Copyright (c) 2022 Niklas von Hertzen - * Released under MIT License - */ - var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // Use a lookup table to find the index. - var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); - for (var i$1 = 0; i$1 < chars$1.length; i$1++) { - lookup$1[chars$1.charCodeAt(i$1)] = i$1; - } - var decode = function (base64) { - var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; - if (base64[base64.length - 1] === '=') { - bufferLength--; - if (base64[base64.length - 2] === '=') { - bufferLength--; - } - } - var buffer = typeof ArrayBuffer !== 'undefined' && - typeof Uint8Array !== 'undefined' && - typeof Uint8Array.prototype.slice !== 'undefined' - ? new ArrayBuffer(bufferLength) - : new Array(bufferLength); - var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer); - for (i = 0; i < len; i += 4) { - encoded1 = lookup$1[base64.charCodeAt(i)]; - encoded2 = lookup$1[base64.charCodeAt(i + 1)]; - encoded3 = lookup$1[base64.charCodeAt(i + 2)]; - encoded4 = lookup$1[base64.charCodeAt(i + 3)]; - bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } - return buffer; - }; - var polyUint16Array = function (buffer) { - var length = buffer.length; - var bytes = []; - for (var i = 0; i < length; i += 2) { - bytes.push((buffer[i + 1] << 8) | buffer[i]); - } - return bytes; - }; - var polyUint32Array = function (buffer) { - var length = buffer.length; - var bytes = []; - for (var i = 0; i < length; i += 4) { - bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]); - } - return bytes; - }; - - /** Shift size for getting the index-2 table offset. */ - var UTRIE2_SHIFT_2 = 5; - /** Shift size for getting the index-1 table offset. */ - var UTRIE2_SHIFT_1 = 6 + 5; - /** - * Shift size for shifting left the index array values. - * Increases possible data size with 16-bit index values at the cost - * of compactability. - * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY. - */ - var UTRIE2_INDEX_SHIFT = 2; - /** - * Difference between the two shift sizes, - * for getting an index-1 offset from an index-2 offset. 6=11-5 - */ - var UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2; - /** - * The part of the index-2 table for U+D800..U+DBFF stores values for - * lead surrogate code _units_ not code _points_. - * Values for lead surrogate code _points_ are indexed with this portion of the table. - * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.) - */ - var UTRIE2_LSCP_INDEX_2_OFFSET = 0x10000 >> UTRIE2_SHIFT_2; - /** Number of entries in a data block. 32=0x20 */ - var UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2; - /** Mask for getting the lower bits for the in-data-block offset. */ - var UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1; - var UTRIE2_LSCP_INDEX_2_LENGTH = 0x400 >> UTRIE2_SHIFT_2; - /** Count the lengths of both BMP pieces. 2080=0x820 */ - var UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH; - /** - * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820. - * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2. - */ - var UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH; - var UTRIE2_UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */ - /** - * The index-1 table, only used for supplementary code points, at offset 2112=0x840. - * Variable length, for code points up to highStart, where the last single-value range starts. - * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1. - * (For 0x100000 supplementary code points U+10000..U+10ffff.) - * - * The part of the index-2 table for supplementary code points starts - * after this index-1 table. - * - * Both the index-1 table and the following part of the index-2 table - * are omitted completely if there is only BMP data. - */ - var UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH; - /** - * Number of index-1 entries for the BMP. 32=0x20 - * This part of the index-1 table is omitted from the serialized form. - */ - var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> UTRIE2_SHIFT_1; - /** Number of entries in an index-2 block. 64=0x40 */ - var UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2; - /** Mask for getting the lower bits for the in-index-2-block offset. */ - var UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1; - var slice16 = function (view, start, end) { - if (view.slice) { - return view.slice(start, end); - } - return new Uint16Array(Array.prototype.slice.call(view, start, end)); - }; - var slice32 = function (view, start, end) { - if (view.slice) { - return view.slice(start, end); - } - return new Uint32Array(Array.prototype.slice.call(view, start, end)); - }; - var createTrieFromBase64 = function (base64, _byteLength) { - var buffer = decode(base64); - var view32 = Array.isArray(buffer) ? polyUint32Array(buffer) : new Uint32Array(buffer); - var view16 = Array.isArray(buffer) ? polyUint16Array(buffer) : new Uint16Array(buffer); - var headerLength = 24; - var index = slice16(view16, headerLength / 2, view32[4] / 2); - var data = view32[5] === 2 - ? slice16(view16, (headerLength + view32[4]) / 2) - : slice32(view32, Math.ceil((headerLength + view32[4]) / 4)); - return new Trie(view32[0], view32[1], view32[2], view32[3], index, data); - }; - var Trie = /** @class */ (function () { - function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) { - this.initialValue = initialValue; - this.errorValue = errorValue; - this.highStart = highStart; - this.highValueIndex = highValueIndex; - this.index = index; - this.data = data; - } - /** - * Get the value for a code point as stored in the Trie. - * - * @param codePoint the code point - * @return the value - */ - Trie.prototype.get = function (codePoint) { - var ix; - if (codePoint >= 0) { - if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) { - // Ordinary BMP code point, excluding leading surrogates. - // BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index. - // 16 bit data is stored in the index array itself. - ix = this.index[codePoint >> UTRIE2_SHIFT_2]; - ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); - return this.data[ix]; - } - if (codePoint <= 0xffff) { - // Lead Surrogate Code Point. A Separate index section is stored for - // lead surrogate code units and code points. - // The main index has the code unit data. - // For this function, we need the code point data. - // Note: this expression could be refactored for slightly improved efficiency, but - // surrogate code points will be so rare in practice that it's not worth it. - ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2)]; - ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); - return this.data[ix]; - } - if (codePoint < this.highStart) { - // Supplemental code point, use two-level lookup. - ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1); - ix = this.index[ix]; - ix += (codePoint >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK; - ix = this.index[ix]; - ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); - return this.data[ix]; - } - if (codePoint <= 0x10ffff) { - return this.data[this.highValueIndex]; - } - } - // Fall through. The code point is outside of the legal range of 0..0x10ffff. - return this.errorValue; - }; - return Trie; - }()); - - /* - * base64-arraybuffer 1.0.2 - * Copyright (c) 2022 Niklas von Hertzen - * Released under MIT License - */ - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // Use a lookup table to find the index. - var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup[chars.charCodeAt(i)] = i; - } - - var Prepend = 1; - var CR = 2; - var LF = 3; - var Control = 4; - var Extend = 5; - var SpacingMark = 7; - var L = 8; - var V = 9; - var T = 10; - var LV = 11; - var LVT = 12; - var ZWJ = 13; - var Extended_Pictographic = 14; - var RI = 15; - var toCodePoints = function (str) { - var codePoints = []; - var i = 0; - var length = str.length; - while (i < length) { - var value = str.charCodeAt(i++); - if (value >= 0xd800 && value <= 0xdbff && i < length) { - var extra = str.charCodeAt(i++); - if ((extra & 0xfc00) === 0xdc00) { - codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000); - } - else { - codePoints.push(value); - i--; - } - } - else { - codePoints.push(value); - } - } - return codePoints; - }; - var fromCodePoint = function () { - var codePoints = []; - for (var _i = 0; _i < arguments.length; _i++) { - codePoints[_i] = arguments[_i]; - } - if (String.fromCodePoint) { - return String.fromCodePoint.apply(String, codePoints); - } - var length = codePoints.length; - if (!length) { - return ''; - } - var codeUnits = []; - var index = -1; - var result = ''; - while (++index < length) { - var codePoint = codePoints[index]; - if (codePoint <= 0xffff) { - codeUnits.push(codePoint); - } - else { - codePoint -= 0x10000; - codeUnits.push((codePoint >> 10) + 0xd800, (codePoint % 0x400) + 0xdc00); - } - if (index + 1 === length || codeUnits.length > 0x4000) { - result += String.fromCharCode.apply(String, codeUnits); - codeUnits.length = 0; - } - } - return result; - }; - var UnicodeTrie = createTrieFromBase64(base64); - var BREAK_NOT_ALLOWED = '×'; - var BREAK_ALLOWED = '÷'; - var codePointToClass = function (codePoint) { return UnicodeTrie.get(codePoint); }; - var _graphemeBreakAtIndex = function (_codePoints, classTypes, index) { - var prevIndex = index - 2; - var prev = classTypes[prevIndex]; - var current = classTypes[index - 1]; - var next = classTypes[index]; - // GB3 Do not break between a CR and LF - if (current === CR && next === LF) { - return BREAK_NOT_ALLOWED; - } - // GB4 Otherwise, break before and after controls. - if (current === CR || current === LF || current === Control) { - return BREAK_ALLOWED; - } - // GB5 - if (next === CR || next === LF || next === Control) { - return BREAK_ALLOWED; - } - // Do not break Hangul syllable sequences. - // GB6 - if (current === L && [L, V, LV, LVT].indexOf(next) !== -1) { - return BREAK_NOT_ALLOWED; - } - // GB7 - if ((current === LV || current === V) && (next === V || next === T)) { - return BREAK_NOT_ALLOWED; - } - // GB8 - if ((current === LVT || current === T) && next === T) { - return BREAK_NOT_ALLOWED; - } - // GB9 Do not break before extending characters or ZWJ. - if (next === ZWJ || next === Extend) { - return BREAK_NOT_ALLOWED; - } - // Do not break before SpacingMarks, or after Prepend characters. - // GB9a - if (next === SpacingMark) { - return BREAK_NOT_ALLOWED; - } - // GB9a - if (current === Prepend) { - return BREAK_NOT_ALLOWED; - } - // GB11 Do not break within emoji modifier sequences or emoji zwj sequences. - if (current === ZWJ && next === Extended_Pictographic) { - while (prev === Extend) { - prev = classTypes[--prevIndex]; - } - if (prev === Extended_Pictographic) { - return BREAK_NOT_ALLOWED; - } - } - // GB12 Do not break within emoji flag sequences. - // That is, do not break between regional indicator (RI) symbols - // if there is an odd number of RI characters before the break point. - if (current === RI && next === RI) { - var countRI = 0; - while (prev === RI) { - countRI++; - prev = classTypes[--prevIndex]; - } - if (countRI % 2 === 0) { - return BREAK_NOT_ALLOWED; - } - } - return BREAK_ALLOWED; - }; - var GraphemeBreaker = function (str) { - var codePoints = toCodePoints(str); - var length = codePoints.length; - var index = 0; - var lastEnd = 0; - var classTypes = codePoints.map(codePointToClass); - return { - next: function () { - if (index >= length) { - return { done: true, value: null }; - } - var graphemeBreak = BREAK_NOT_ALLOWED; - while (index < length && - (graphemeBreak = _graphemeBreakAtIndex(codePoints, classTypes, ++index)) === BREAK_NOT_ALLOWED) { } - if (graphemeBreak !== BREAK_NOT_ALLOWED || index === length) { - var value = fromCodePoint.apply(null, codePoints.slice(lastEnd, index)); - lastEnd = index; - return { value: value, done: false }; - } - return { done: true, value: null }; - }, - }; - }; - var splitGraphemes = function (str) { - var breaker = GraphemeBreaker(str); - var graphemes = []; - var bk; - while (!(bk = breaker.next()).done) { - if (bk.value) { - graphemes.push(bk.value.slice()); - } - } - return graphemes; - }; - - var testRangeBounds = function (document) { - var TEST_HEIGHT = 123; - if (document.createRange) { - var range = document.createRange(); - if (range.getBoundingClientRect) { - var testElement = document.createElement('boundtest'); - testElement.style.height = TEST_HEIGHT + "px"; - testElement.style.display = 'block'; - document.body.appendChild(testElement); - range.selectNode(testElement); - var rangeBounds = range.getBoundingClientRect(); - var rangeHeight = Math.round(rangeBounds.height); - document.body.removeChild(testElement); - if (rangeHeight === TEST_HEIGHT) { - return true; - } - } - } - return false; - }; - var testIOSLineBreak = function (document) { - var testElement = document.createElement('boundtest'); - testElement.style.width = '50px'; - testElement.style.display = 'block'; - testElement.style.fontSize = '12px'; - testElement.style.letterSpacing = '0px'; - testElement.style.wordSpacing = '0px'; - document.body.appendChild(testElement); - var range = document.createRange(); - testElement.innerHTML = typeof ''.repeat === 'function' ? '👨'.repeat(10) : ''; - var node = testElement.firstChild; - var textList = toCodePoints$1(node.data).map(function (i) { return fromCodePoint$1(i); }); - var offset = 0; - var prev = {}; - // ios 13 does not handle range getBoundingClientRect line changes correctly #2177 - var supports = textList.every(function (text, i) { - range.setStart(node, offset); - range.setEnd(node, offset + text.length); - var rect = range.getBoundingClientRect(); - offset += text.length; - var boundAhead = rect.x > prev.x || rect.y > prev.y; - prev = rect; - if (i === 0) { - return true; - } - return boundAhead; - }); - document.body.removeChild(testElement); - return supports; - }; - var testCORS = function () { return typeof new Image().crossOrigin !== 'undefined'; }; - var testResponseType = function () { return typeof new XMLHttpRequest().responseType === 'string'; }; - var testSVG = function (document) { - var img = new Image(); - var canvas = document.createElement('canvas'); - var ctx = canvas.getContext('2d'); - if (!ctx) { - return false; - } - img.src = "data:image/svg+xml,"; - try { - ctx.drawImage(img, 0, 0); - canvas.toDataURL(); - } - catch (e) { - return false; - } - return true; - }; - var isGreenPixel = function (data) { - return data[0] === 0 && data[1] === 255 && data[2] === 0 && data[3] === 255; - }; - var testForeignObject = function (document) { - var canvas = document.createElement('canvas'); - var size = 100; - canvas.width = size; - canvas.height = size; - var ctx = canvas.getContext('2d'); - if (!ctx) { - return Promise.reject(false); - } - ctx.fillStyle = 'rgb(0, 255, 0)'; - ctx.fillRect(0, 0, size, size); - var img = new Image(); - var greenImageSrc = canvas.toDataURL(); - img.src = greenImageSrc; - var svg = createForeignObjectSVG(size, size, 0, 0, img); - ctx.fillStyle = 'red'; - ctx.fillRect(0, 0, size, size); - return loadSerializedSVG$1(svg) - .then(function (img) { - ctx.drawImage(img, 0, 0); - var data = ctx.getImageData(0, 0, size, size).data; - ctx.fillStyle = 'red'; - ctx.fillRect(0, 0, size, size); - var node = document.createElement('div'); - node.style.backgroundImage = "url(" + greenImageSrc + ")"; - node.style.height = size + "px"; - // Firefox 55 does not render inline tags - return isGreenPixel(data) - ? loadSerializedSVG$1(createForeignObjectSVG(size, size, 0, 0, node)) - : Promise.reject(false); - }) - .then(function (img) { - ctx.drawImage(img, 0, 0); - // Edge does not render background-images - return isGreenPixel(ctx.getImageData(0, 0, size, size).data); - }) - .catch(function () { return false; }); - }; - var createForeignObjectSVG = function (width, height, x, y, node) { - var xmlns = 'http://www.w3.org/2000/svg'; - var svg = document.createElementNS(xmlns, 'svg'); - var foreignObject = document.createElementNS(xmlns, 'foreignObject'); - svg.setAttributeNS(null, 'width', width.toString()); - svg.setAttributeNS(null, 'height', height.toString()); - foreignObject.setAttributeNS(null, 'width', '100%'); - foreignObject.setAttributeNS(null, 'height', '100%'); - foreignObject.setAttributeNS(null, 'x', x.toString()); - foreignObject.setAttributeNS(null, 'y', y.toString()); - foreignObject.setAttributeNS(null, 'externalResourcesRequired', 'true'); - svg.appendChild(foreignObject); - foreignObject.appendChild(node); - return svg; - }; - var loadSerializedSVG$1 = function (svg) { - return new Promise(function (resolve, reject) { - var img = new Image(); - img.onload = function () { return resolve(img); }; - img.onerror = reject; - img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg)); - }); - }; - var FEATURES = { - get SUPPORT_RANGE_BOUNDS() { - var value = testRangeBounds(document); - Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', { value: value }); - return value; - }, - get SUPPORT_WORD_BREAKING() { - var value = FEATURES.SUPPORT_RANGE_BOUNDS && testIOSLineBreak(document); - Object.defineProperty(FEATURES, 'SUPPORT_WORD_BREAKING', { value: value }); - return value; - }, - get SUPPORT_SVG_DRAWING() { - var value = testSVG(document); - Object.defineProperty(FEATURES, 'SUPPORT_SVG_DRAWING', { value: value }); - return value; - }, - get SUPPORT_FOREIGNOBJECT_DRAWING() { - var value = typeof Array.from === 'function' && typeof window.fetch === 'function' - ? testForeignObject(document) - : Promise.resolve(false); - Object.defineProperty(FEATURES, 'SUPPORT_FOREIGNOBJECT_DRAWING', { value: value }); - return value; - }, - get SUPPORT_CORS_IMAGES() { - var value = testCORS(); - Object.defineProperty(FEATURES, 'SUPPORT_CORS_IMAGES', { value: value }); - return value; - }, - get SUPPORT_RESPONSE_TYPE() { - var value = testResponseType(); - Object.defineProperty(FEATURES, 'SUPPORT_RESPONSE_TYPE', { value: value }); - return value; - }, - get SUPPORT_CORS_XHR() { - var value = 'withCredentials' in new XMLHttpRequest(); - Object.defineProperty(FEATURES, 'SUPPORT_CORS_XHR', { value: value }); - return value; - }, - get SUPPORT_NATIVE_TEXT_SEGMENTATION() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var value = !!(typeof Intl !== 'undefined' && Intl.Segmenter); - Object.defineProperty(FEATURES, 'SUPPORT_NATIVE_TEXT_SEGMENTATION', { value: value }); - return value; - } - }; - - var TextBounds = /** @class */ (function () { - function TextBounds(text, bounds) { - this.text = text; - this.bounds = bounds; - } - return TextBounds; - }()); - var parseTextBounds = function (context, value, styles, node) { - var textList = breakText(value, styles); - var textBounds = []; - var offset = 0; - textList.forEach(function (text) { - if (styles.textDecorationLine.length || text.trim().length > 0) { - if (FEATURES.SUPPORT_RANGE_BOUNDS) { - var clientRects = createRange(node, offset, text.length).getClientRects(); - if (clientRects.length > 1) { - var subSegments = segmentGraphemes(text); - var subOffset_1 = 0; - subSegments.forEach(function (subSegment) { - textBounds.push(new TextBounds(subSegment, Bounds.fromDOMRectList(context, createRange(node, subOffset_1 + offset, subSegment.length).getClientRects()))); - subOffset_1 += subSegment.length; - }); - } - else { - textBounds.push(new TextBounds(text, Bounds.fromDOMRectList(context, clientRects))); - } - } - else { - var replacementNode = node.splitText(text.length); - textBounds.push(new TextBounds(text, getWrapperBounds(context, node))); - node = replacementNode; - } - } - else if (!FEATURES.SUPPORT_RANGE_BOUNDS) { - node = node.splitText(text.length); - } - offset += text.length; - }); - return textBounds; - }; - var getWrapperBounds = function (context, node) { - var ownerDocument = node.ownerDocument; - if (ownerDocument) { - var wrapper = ownerDocument.createElement('html2canvaswrapper'); - wrapper.appendChild(node.cloneNode(true)); - var parentNode = node.parentNode; - if (parentNode) { - parentNode.replaceChild(wrapper, node); - var bounds = parseBounds(context, wrapper); - if (wrapper.firstChild) { - parentNode.replaceChild(wrapper.firstChild, wrapper); - } - return bounds; - } - } - return Bounds.EMPTY; - }; - var createRange = function (node, offset, length) { - var ownerDocument = node.ownerDocument; - if (!ownerDocument) { - throw new Error('Node has no owner document'); - } - var range = ownerDocument.createRange(); - range.setStart(node, offset); - range.setEnd(node, offset + length); - return range; - }; - var segmentGraphemes = function (value) { - if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var segmenter = new Intl.Segmenter(void 0, { granularity: 'grapheme' }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return Array.from(segmenter.segment(value)).map(function (segment) { return segment.segment; }); - } - return splitGraphemes(value); - }; - var segmentWords = function (value, styles) { - if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var segmenter = new Intl.Segmenter(void 0, { - granularity: 'word' - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return Array.from(segmenter.segment(value)).map(function (segment) { return segment.segment; }); - } - return breakWords(value, styles); - }; - var breakText = function (value, styles) { - return styles.letterSpacing !== 0 ? segmentGraphemes(value) : segmentWords(value, styles); - }; - // https://drafts.csswg.org/css-text/#word-separator - var wordSeparators = [0x0020, 0x00a0, 0x1361, 0x10100, 0x10101, 0x1039, 0x1091]; - var breakWords = function (str, styles) { - var breaker = LineBreaker(str, { - lineBreak: styles.lineBreak, - wordBreak: styles.overflowWrap === "break-word" /* BREAK_WORD */ ? 'break-word' : styles.wordBreak - }); - var words = []; - var bk; - var _loop_1 = function () { - if (bk.value) { - var value = bk.value.slice(); - var codePoints = toCodePoints$1(value); - var word_1 = ''; - codePoints.forEach(function (codePoint) { - if (wordSeparators.indexOf(codePoint) === -1) { - word_1 += fromCodePoint$1(codePoint); - } - else { - if (word_1.length) { - words.push(word_1); - } - words.push(fromCodePoint$1(codePoint)); - word_1 = ''; - } - }); - if (word_1.length) { - words.push(word_1); - } - } - }; - while (!(bk = breaker.next()).done) { - _loop_1(); - } - return words; - }; - - var TextContainer = /** @class */ (function () { - function TextContainer(context, node, styles) { - this.text = transform(node.data, styles.textTransform); - this.textBounds = parseTextBounds(context, this.text, styles, node); - } - return TextContainer; - }()); - var transform = function (text, transform) { - switch (transform) { - case 1 /* LOWERCASE */: - return text.toLowerCase(); - case 3 /* CAPITALIZE */: - return text.replace(CAPITALIZE, capitalize); - case 2 /* UPPERCASE */: - return text.toUpperCase(); - default: - return text; - } - }; - var CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g; - var capitalize = function (m, p1, p2) { - if (m.length > 0) { - return p1 + p2.toUpperCase(); - } - return m; - }; - - var ImageElementContainer = /** @class */ (function (_super) { - __extends(ImageElementContainer, _super); - function ImageElementContainer(context, img) { - var _this = _super.call(this, context, img) || this; - _this.src = img.currentSrc || img.src; - _this.intrinsicWidth = img.naturalWidth; - _this.intrinsicHeight = img.naturalHeight; - _this.context.cache.addImage(_this.src); - return _this; - } - return ImageElementContainer; - }(ElementContainer)); - - var CanvasElementContainer = /** @class */ (function (_super) { - __extends(CanvasElementContainer, _super); - function CanvasElementContainer(context, canvas) { - var _this = _super.call(this, context, canvas) || this; - _this.canvas = canvas; - _this.intrinsicWidth = canvas.width; - _this.intrinsicHeight = canvas.height; - return _this; - } - return CanvasElementContainer; - }(ElementContainer)); - - var SVGElementContainer = /** @class */ (function (_super) { - __extends(SVGElementContainer, _super); - function SVGElementContainer(context, img) { - var _this = _super.call(this, context, img) || this; - var s = new XMLSerializer(); - var bounds = parseBounds(context, img); - img.setAttribute('width', bounds.width + "px"); - img.setAttribute('height', bounds.height + "px"); - _this.svg = "data:image/svg+xml," + encodeURIComponent(s.serializeToString(img)); - _this.intrinsicWidth = img.width.baseVal.value; - _this.intrinsicHeight = img.height.baseVal.value; - _this.context.cache.addImage(_this.svg); - return _this; - } - return SVGElementContainer; - }(ElementContainer)); - - var LIElementContainer = /** @class */ (function (_super) { - __extends(LIElementContainer, _super); - function LIElementContainer(context, element) { - var _this = _super.call(this, context, element) || this; - _this.value = element.value; - return _this; - } - return LIElementContainer; - }(ElementContainer)); - - var OLElementContainer = /** @class */ (function (_super) { - __extends(OLElementContainer, _super); - function OLElementContainer(context, element) { - var _this = _super.call(this, context, element) || this; - _this.start = element.start; - _this.reversed = typeof element.reversed === 'boolean' && element.reversed === true; - return _this; - } - return OLElementContainer; - }(ElementContainer)); - - var CHECKBOX_BORDER_RADIUS = [ - { - type: 15 /* DIMENSION_TOKEN */, - flags: 0, - unit: 'px', - number: 3 - } - ]; - var RADIO_BORDER_RADIUS = [ - { - type: 16 /* PERCENTAGE_TOKEN */, - flags: 0, - number: 50 - } - ]; - var reformatInputBounds = function (bounds) { - if (bounds.width > bounds.height) { - return new Bounds(bounds.left + (bounds.width - bounds.height) / 2, bounds.top, bounds.height, bounds.height); - } - else if (bounds.width < bounds.height) { - return new Bounds(bounds.left, bounds.top + (bounds.height - bounds.width) / 2, bounds.width, bounds.width); - } - return bounds; - }; - var getInputValue = function (node) { - var value = node.type === PASSWORD ? new Array(node.value.length + 1).join('\u2022') : node.value; - return value.length === 0 ? node.placeholder || '' : value; - }; - var CHECKBOX = 'checkbox'; - var RADIO = 'radio'; - var PASSWORD = 'password'; - var INPUT_COLOR = 0x2a2a2aff; - var InputElementContainer = /** @class */ (function (_super) { - __extends(InputElementContainer, _super); - function InputElementContainer(context, input) { - var _this = _super.call(this, context, input) || this; - _this.type = input.type.toLowerCase(); - _this.checked = input.checked; - _this.value = getInputValue(input); - if (_this.type === CHECKBOX || _this.type === RADIO) { - _this.styles.backgroundColor = 0xdededeff; - _this.styles.borderTopColor = - _this.styles.borderRightColor = - _this.styles.borderBottomColor = - _this.styles.borderLeftColor = - 0xa5a5a5ff; - _this.styles.borderTopWidth = - _this.styles.borderRightWidth = - _this.styles.borderBottomWidth = - _this.styles.borderLeftWidth = - 1; - _this.styles.borderTopStyle = - _this.styles.borderRightStyle = - _this.styles.borderBottomStyle = - _this.styles.borderLeftStyle = - 1 /* SOLID */; - _this.styles.backgroundClip = [0 /* BORDER_BOX */]; - _this.styles.backgroundOrigin = [0 /* BORDER_BOX */]; - _this.bounds = reformatInputBounds(_this.bounds); - } - switch (_this.type) { - case CHECKBOX: - _this.styles.borderTopRightRadius = - _this.styles.borderTopLeftRadius = - _this.styles.borderBottomRightRadius = - _this.styles.borderBottomLeftRadius = - CHECKBOX_BORDER_RADIUS; - break; - case RADIO: - _this.styles.borderTopRightRadius = - _this.styles.borderTopLeftRadius = - _this.styles.borderBottomRightRadius = - _this.styles.borderBottomLeftRadius = - RADIO_BORDER_RADIUS; - break; - } - return _this; - } - return InputElementContainer; - }(ElementContainer)); - - var SelectElementContainer = /** @class */ (function (_super) { - __extends(SelectElementContainer, _super); - function SelectElementContainer(context, element) { - var _this = _super.call(this, context, element) || this; - var option = element.options[element.selectedIndex || 0]; - _this.value = option ? option.text || '' : ''; - return _this; - } - return SelectElementContainer; - }(ElementContainer)); - - var TextareaElementContainer = /** @class */ (function (_super) { - __extends(TextareaElementContainer, _super); - function TextareaElementContainer(context, element) { - var _this = _super.call(this, context, element) || this; - _this.value = element.value; - return _this; - } - return TextareaElementContainer; - }(ElementContainer)); - - var IFrameElementContainer = /** @class */ (function (_super) { - __extends(IFrameElementContainer, _super); - function IFrameElementContainer(context, iframe) { - var _this = _super.call(this, context, iframe) || this; - _this.src = iframe.src; - _this.width = parseInt(iframe.width, 10) || 0; - _this.height = parseInt(iframe.height, 10) || 0; - _this.backgroundColor = _this.styles.backgroundColor; - try { - if (iframe.contentWindow && - iframe.contentWindow.document && - iframe.contentWindow.document.documentElement) { - _this.tree = parseTree(context, iframe.contentWindow.document.documentElement); - // http://www.w3.org/TR/css3-background/#special-backgrounds - var documentBackgroundColor = iframe.contentWindow.document.documentElement - ? parseColor(context, getComputedStyle(iframe.contentWindow.document.documentElement).backgroundColor) - : COLORS.TRANSPARENT; - var bodyBackgroundColor = iframe.contentWindow.document.body - ? parseColor(context, getComputedStyle(iframe.contentWindow.document.body).backgroundColor) - : COLORS.TRANSPARENT; - _this.backgroundColor = isTransparent(documentBackgroundColor) - ? isTransparent(bodyBackgroundColor) - ? _this.styles.backgroundColor - : bodyBackgroundColor - : documentBackgroundColor; - } - } - catch (e) { } - return _this; - } - return IFrameElementContainer; - }(ElementContainer)); - - var LIST_OWNERS = ['OL', 'UL', 'MENU']; - var parseNodeTree = function (context, node, parent, root) { - for (var childNode = node.firstChild, nextNode = void 0; childNode; childNode = nextNode) { - nextNode = childNode.nextSibling; - if (isTextNode(childNode) && childNode.data.trim().length > 0) { - parent.textNodes.push(new TextContainer(context, childNode, parent.styles)); - } - else if (isElementNode(childNode)) { - if (isSlotElement(childNode) && childNode.assignedNodes) { - childNode.assignedNodes().forEach(function (childNode) { return parseNodeTree(context, childNode, parent, root); }); - } - else { - var container = createContainer(context, childNode); - if (container.styles.isVisible()) { - if (createsRealStackingContext(childNode, container, root)) { - container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */; - } - else if (createsStackingContext(container.styles)) { - container.flags |= 2 /* CREATES_STACKING_CONTEXT */; - } - if (LIST_OWNERS.indexOf(childNode.tagName) !== -1) { - container.flags |= 8 /* IS_LIST_OWNER */; - } - parent.elements.push(container); - childNode.slot; - if (childNode.shadowRoot) { - parseNodeTree(context, childNode.shadowRoot, container, root); - } - else if (!isTextareaElement(childNode) && - !isSVGElement(childNode) && - !isSelectElement(childNode)) { - parseNodeTree(context, childNode, container, root); - } - } - } - } - } - }; - var createContainer = function (context, element) { - if (isImageElement(element)) { - return new ImageElementContainer(context, element); - } - if (isCanvasElement(element)) { - return new CanvasElementContainer(context, element); - } - if (isSVGElement(element)) { - return new SVGElementContainer(context, element); - } - if (isLIElement(element)) { - return new LIElementContainer(context, element); - } - if (isOLElement(element)) { - return new OLElementContainer(context, element); - } - if (isInputElement(element)) { - return new InputElementContainer(context, element); - } - if (isSelectElement(element)) { - return new SelectElementContainer(context, element); - } - if (isTextareaElement(element)) { - return new TextareaElementContainer(context, element); - } - if (isIFrameElement(element)) { - return new IFrameElementContainer(context, element); - } - return new ElementContainer(context, element); - }; - var parseTree = function (context, element) { - var container = createContainer(context, element); - container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */; - parseNodeTree(context, element, container, container); - return container; - }; - var createsRealStackingContext = function (node, container, root) { - return (container.styles.isPositionedWithZIndex() || - container.styles.opacity < 1 || - container.styles.isTransformed() || - (isBodyElement(node) && root.styles.isTransparent())); - }; - var createsStackingContext = function (styles) { return styles.isPositioned() || styles.isFloating(); }; - var isTextNode = function (node) { return node.nodeType === Node.TEXT_NODE; }; - var isElementNode = function (node) { return node.nodeType === Node.ELEMENT_NODE; }; - var isHTMLElementNode = function (node) { - return isElementNode(node) && typeof node.style !== 'undefined' && !isSVGElementNode(node); - }; - var isSVGElementNode = function (element) { - return typeof element.className === 'object'; - }; - var isLIElement = function (node) { return node.tagName === 'LI'; }; - var isOLElement = function (node) { return node.tagName === 'OL'; }; - var isInputElement = function (node) { return node.tagName === 'INPUT'; }; - var isHTMLElement = function (node) { return node.tagName === 'HTML'; }; - var isSVGElement = function (node) { return node.tagName === 'svg'; }; - var isBodyElement = function (node) { return node.tagName === 'BODY'; }; - var isCanvasElement = function (node) { return node.tagName === 'CANVAS'; }; - var isVideoElement = function (node) { return node.tagName === 'VIDEO'; }; - var isImageElement = function (node) { return node.tagName === 'IMG'; }; - var isIFrameElement = function (node) { return node.tagName === 'IFRAME'; }; - var isStyleElement = function (node) { return node.tagName === 'STYLE'; }; - var isScriptElement = function (node) { return node.tagName === 'SCRIPT'; }; - var isTextareaElement = function (node) { return node.tagName === 'TEXTAREA'; }; - var isSelectElement = function (node) { return node.tagName === 'SELECT'; }; - var isSlotElement = function (node) { return node.tagName === 'SLOT'; }; - // https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name - var isCustomElement = function (node) { return node.tagName.indexOf('-') > 0; }; - - var CounterState = /** @class */ (function () { - function CounterState() { - this.counters = {}; - } - CounterState.prototype.getCounterValue = function (name) { - var counter = this.counters[name]; - if (counter && counter.length) { - return counter[counter.length - 1]; - } - return 1; - }; - CounterState.prototype.getCounterValues = function (name) { - var counter = this.counters[name]; - return counter ? counter : []; - }; - CounterState.prototype.pop = function (counters) { - var _this = this; - counters.forEach(function (counter) { return _this.counters[counter].pop(); }); - }; - CounterState.prototype.parse = function (style) { - var _this = this; - var counterIncrement = style.counterIncrement; - var counterReset = style.counterReset; - var canReset = true; - if (counterIncrement !== null) { - counterIncrement.forEach(function (entry) { - var counter = _this.counters[entry.counter]; - if (counter && entry.increment !== 0) { - canReset = false; - if (!counter.length) { - counter.push(1); - } - counter[Math.max(0, counter.length - 1)] += entry.increment; - } - }); - } - var counterNames = []; - if (canReset) { - counterReset.forEach(function (entry) { - var counter = _this.counters[entry.counter]; - counterNames.push(entry.counter); - if (!counter) { - counter = _this.counters[entry.counter] = []; - } - counter.push(entry.reset); - }); - } - return counterNames; - }; - return CounterState; - }()); - var ROMAN_UPPER = { - integers: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1], - values: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] - }; - var ARMENIAN = { - integers: [ - 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, - 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 - ], - values: [ - 'Ք', - 'Փ', - 'Ւ', - 'Ց', - 'Ր', - 'Տ', - 'Վ', - 'Ս', - 'Ռ', - 'Ջ', - 'Պ', - 'Չ', - 'Ո', - 'Շ', - 'Ն', - 'Յ', - 'Մ', - 'Ճ', - 'Ղ', - 'Ձ', - 'Հ', - 'Կ', - 'Ծ', - 'Խ', - 'Լ', - 'Ի', - 'Ժ', - 'Թ', - 'Ը', - 'Է', - 'Զ', - 'Ե', - 'Դ', - 'Գ', - 'Բ', - 'Ա' - ] - }; - var HEBREW = { - integers: [ - 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, - 19, 18, 17, 16, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 - ], - values: [ - 'י׳', - 'ט׳', - 'ח׳', - 'ז׳', - 'ו׳', - 'ה׳', - 'ד׳', - 'ג׳', - 'ב׳', - 'א׳', - 'ת', - 'ש', - 'ר', - 'ק', - 'צ', - 'פ', - 'ע', - 'ס', - 'נ', - 'מ', - 'ל', - 'כ', - 'יט', - 'יח', - 'יז', - 'טז', - 'טו', - 'י', - 'ט', - 'ח', - 'ז', - 'ו', - 'ה', - 'ד', - 'ג', - 'ב', - 'א' - ] - }; - var GEORGIAN = { - integers: [ - 10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, - 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 - ], - values: [ - 'ჵ', - 'ჰ', - 'ჯ', - 'ჴ', - 'ხ', - 'ჭ', - 'წ', - 'ძ', - 'ც', - 'ჩ', - 'შ', - 'ყ', - 'ღ', - 'ქ', - 'ფ', - 'ჳ', - 'ტ', - 'ს', - 'რ', - 'ჟ', - 'პ', - 'ო', - 'ჲ', - 'ნ', - 'მ', - 'ლ', - 'კ', - 'ი', - 'თ', - 'ჱ', - 'ზ', - 'ვ', - 'ე', - 'დ', - 'გ', - 'ბ', - 'ა' - ] - }; - var createAdditiveCounter = function (value, min, max, symbols, fallback, suffix) { - if (value < min || value > max) { - return createCounterText(value, fallback, suffix.length > 0); - } - return (symbols.integers.reduce(function (string, integer, index) { - while (value >= integer) { - value -= integer; - string += symbols.values[index]; - } - return string; - }, '') + suffix); - }; - var createCounterStyleWithSymbolResolver = function (value, codePointRangeLength, isNumeric, resolver) { - var string = ''; - do { - if (!isNumeric) { - value--; - } - string = resolver(value) + string; - value /= codePointRangeLength; - } while (value * codePointRangeLength >= codePointRangeLength); - return string; - }; - var createCounterStyleFromRange = function (value, codePointRangeStart, codePointRangeEnd, isNumeric, suffix) { - var codePointRangeLength = codePointRangeEnd - codePointRangeStart + 1; - return ((value < 0 ? '-' : '') + - (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, function (codePoint) { - return fromCodePoint$1(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart); - }) + - suffix)); - }; - var createCounterStyleFromSymbols = function (value, symbols, suffix) { - if (suffix === void 0) { suffix = '. '; } - var codePointRangeLength = symbols.length; - return (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, false, function (codePoint) { return symbols[Math.floor(codePoint % codePointRangeLength)]; }) + suffix); - }; - var CJK_ZEROS = 1 << 0; - var CJK_TEN_COEFFICIENTS = 1 << 1; - var CJK_TEN_HIGH_COEFFICIENTS = 1 << 2; - var CJK_HUNDRED_COEFFICIENTS = 1 << 3; - var createCJKCounter = function (value, numbers, multipliers, negativeSign, suffix, flags) { - if (value < -9999 || value > 9999) { - return createCounterText(value, 4 /* CJK_DECIMAL */, suffix.length > 0); - } - var tmp = Math.abs(value); - var string = suffix; - if (tmp === 0) { - return numbers[0] + string; - } - for (var digit = 0; tmp > 0 && digit <= 4; digit++) { - var coefficient = tmp % 10; - if (coefficient === 0 && contains(flags, CJK_ZEROS) && string !== '') { - string = numbers[coefficient] + string; - } - else if (coefficient > 1 || - (coefficient === 1 && digit === 0) || - (coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_COEFFICIENTS)) || - (coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_HIGH_COEFFICIENTS) && value > 100) || - (coefficient === 1 && digit > 1 && contains(flags, CJK_HUNDRED_COEFFICIENTS))) { - string = numbers[coefficient] + (digit > 0 ? multipliers[digit - 1] : '') + string; - } - else if (coefficient === 1 && digit > 0) { - string = multipliers[digit - 1] + string; - } - tmp = Math.floor(tmp / 10); - } - return (value < 0 ? negativeSign : '') + string; - }; - var CHINESE_INFORMAL_MULTIPLIERS = '十百千萬'; - var CHINESE_FORMAL_MULTIPLIERS = '拾佰仟萬'; - var JAPANESE_NEGATIVE = 'マイナス'; - var KOREAN_NEGATIVE = '마이너스'; - var createCounterText = function (value, type, appendSuffix) { - var defaultSuffix = appendSuffix ? '. ' : ''; - var cjkSuffix = appendSuffix ? '、' : ''; - var koreanSuffix = appendSuffix ? ', ' : ''; - var spaceSuffix = appendSuffix ? ' ' : ''; - switch (type) { - case 0 /* DISC */: - return '•' + spaceSuffix; - case 1 /* CIRCLE */: - return '◦' + spaceSuffix; - case 2 /* SQUARE */: - return '◾' + spaceSuffix; - case 5 /* DECIMAL_LEADING_ZERO */: - var string = createCounterStyleFromRange(value, 48, 57, true, defaultSuffix); - return string.length < 4 ? "0" + string : string; - case 4 /* CJK_DECIMAL */: - return createCounterStyleFromSymbols(value, '〇一二三四五六七八九', cjkSuffix); - case 6 /* LOWER_ROMAN */: - return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, 3 /* DECIMAL */, defaultSuffix).toLowerCase(); - case 7 /* UPPER_ROMAN */: - return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, 3 /* DECIMAL */, defaultSuffix); - case 8 /* LOWER_GREEK */: - return createCounterStyleFromRange(value, 945, 969, false, defaultSuffix); - case 9 /* LOWER_ALPHA */: - return createCounterStyleFromRange(value, 97, 122, false, defaultSuffix); - case 10 /* UPPER_ALPHA */: - return createCounterStyleFromRange(value, 65, 90, false, defaultSuffix); - case 11 /* ARABIC_INDIC */: - return createCounterStyleFromRange(value, 1632, 1641, true, defaultSuffix); - case 12 /* ARMENIAN */: - case 49 /* UPPER_ARMENIAN */: - return createAdditiveCounter(value, 1, 9999, ARMENIAN, 3 /* DECIMAL */, defaultSuffix); - case 35 /* LOWER_ARMENIAN */: - return createAdditiveCounter(value, 1, 9999, ARMENIAN, 3 /* DECIMAL */, defaultSuffix).toLowerCase(); - case 13 /* BENGALI */: - return createCounterStyleFromRange(value, 2534, 2543, true, defaultSuffix); - case 14 /* CAMBODIAN */: - case 30 /* KHMER */: - return createCounterStyleFromRange(value, 6112, 6121, true, defaultSuffix); - case 15 /* CJK_EARTHLY_BRANCH */: - return createCounterStyleFromSymbols(value, '子丑寅卯辰巳午未申酉戌亥', cjkSuffix); - case 16 /* CJK_HEAVENLY_STEM */: - return createCounterStyleFromSymbols(value, '甲乙丙丁戊己庚辛壬癸', cjkSuffix); - case 17 /* CJK_IDEOGRAPHIC */: - case 48 /* TRAD_CHINESE_INFORMAL */: - return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS); - case 47 /* TRAD_CHINESE_FORMAL */: - return createCJKCounter(value, '零壹貳參肆伍陸柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS); - case 42 /* SIMP_CHINESE_INFORMAL */: - return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS); - case 41 /* SIMP_CHINESE_FORMAL */: - return createCJKCounter(value, '零壹贰叁肆伍陆柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS); - case 26 /* JAPANESE_INFORMAL */: - return createCJKCounter(value, '〇一二三四五六七八九', '十百千万', JAPANESE_NEGATIVE, cjkSuffix, 0); - case 25 /* JAPANESE_FORMAL */: - return createCJKCounter(value, '零壱弐参四伍六七八九', '拾百千万', JAPANESE_NEGATIVE, cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS); - case 31 /* KOREAN_HANGUL_FORMAL */: - return createCJKCounter(value, '영일이삼사오육칠팔구', '십백천만', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS); - case 33 /* KOREAN_HANJA_INFORMAL */: - return createCJKCounter(value, '零一二三四五六七八九', '十百千萬', KOREAN_NEGATIVE, koreanSuffix, 0); - case 32 /* KOREAN_HANJA_FORMAL */: - return createCJKCounter(value, '零壹貳參四五六七八九', '拾百千', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS); - case 18 /* DEVANAGARI */: - return createCounterStyleFromRange(value, 0x966, 0x96f, true, defaultSuffix); - case 20 /* GEORGIAN */: - return createAdditiveCounter(value, 1, 19999, GEORGIAN, 3 /* DECIMAL */, defaultSuffix); - case 21 /* GUJARATI */: - return createCounterStyleFromRange(value, 0xae6, 0xaef, true, defaultSuffix); - case 22 /* GURMUKHI */: - return createCounterStyleFromRange(value, 0xa66, 0xa6f, true, defaultSuffix); - case 22 /* HEBREW */: - return createAdditiveCounter(value, 1, 10999, HEBREW, 3 /* DECIMAL */, defaultSuffix); - case 23 /* HIRAGANA */: - return createCounterStyleFromSymbols(value, 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん'); - case 24 /* HIRAGANA_IROHA */: - return createCounterStyleFromSymbols(value, 'いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす'); - case 27 /* KANNADA */: - return createCounterStyleFromRange(value, 0xce6, 0xcef, true, defaultSuffix); - case 28 /* KATAKANA */: - return createCounterStyleFromSymbols(value, 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン', cjkSuffix); - case 29 /* KATAKANA_IROHA */: - return createCounterStyleFromSymbols(value, 'イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス', cjkSuffix); - case 34 /* LAO */: - return createCounterStyleFromRange(value, 0xed0, 0xed9, true, defaultSuffix); - case 37 /* MONGOLIAN */: - return createCounterStyleFromRange(value, 0x1810, 0x1819, true, defaultSuffix); - case 38 /* MYANMAR */: - return createCounterStyleFromRange(value, 0x1040, 0x1049, true, defaultSuffix); - case 39 /* ORIYA */: - return createCounterStyleFromRange(value, 0xb66, 0xb6f, true, defaultSuffix); - case 40 /* PERSIAN */: - return createCounterStyleFromRange(value, 0x6f0, 0x6f9, true, defaultSuffix); - case 43 /* TAMIL */: - return createCounterStyleFromRange(value, 0xbe6, 0xbef, true, defaultSuffix); - case 44 /* TELUGU */: - return createCounterStyleFromRange(value, 0xc66, 0xc6f, true, defaultSuffix); - case 45 /* THAI */: - return createCounterStyleFromRange(value, 0xe50, 0xe59, true, defaultSuffix); - case 46 /* TIBETAN */: - return createCounterStyleFromRange(value, 0xf20, 0xf29, true, defaultSuffix); - case 3 /* DECIMAL */: - default: - return createCounterStyleFromRange(value, 48, 57, true, defaultSuffix); - } - }; - - var IGNORE_ATTRIBUTE = 'data-html2canvas-ignore'; - var DocumentCloner = /** @class */ (function () { - function DocumentCloner(context, element, options) { - this.context = context; - this.options = options; - this.scrolledElements = []; - this.referenceElement = element; - this.counters = new CounterState(); - this.quoteDepth = 0; - if (!element.ownerDocument) { - throw new Error('Cloned element does not have an owner document'); - } - this.documentElement = this.cloneNode(element.ownerDocument.documentElement, false); - } - DocumentCloner.prototype.toIFrame = function (ownerDocument, windowSize) { - var _this = this; - var iframe = createIFrameContainer(ownerDocument, windowSize); - if (!iframe.contentWindow) { - return Promise.reject("Unable to find iframe window"); - } - var scrollX = ownerDocument.defaultView.pageXOffset; - var scrollY = ownerDocument.defaultView.pageYOffset; - var cloneWindow = iframe.contentWindow; - var documentClone = cloneWindow.document; - /* Chrome doesn't detect relative background-images assigned in inline "},this.getStyleTags=function(){return t.sealed?Fi(2):t._emitSheetCSS()},this.getStyleElement=function(){var n;if(t.sealed)return Fi(2);var r=((n={})[Ii]="",n["data-styled-version"]="5.3.6",n.dangerouslySetInnerHTML={__html:t.instance.toString()},n),o=Xi();return o&&(r.nonce=o),[e.createElement("style",Ri({},r,{key:"sc-0-0"}))]},this.seal=function(){t.sealed=!0},this.instance=new ol({isServer:!0}),this.sealed=!1}var n=t.prototype;n.collectStyles=function(t){return this.sealed?Fi(2):e.createElement(kl,{sheet:this.instance},t)},n.interleaveWithNodeStream=function(e){return Fi(3)}}();var Gl=Kl;function Ql(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var ql,Yl,Xl,Zl,Jl,eu=Gl.div(ql||(ql=Ql(["\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n"],["\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n"]))),tu=Gl.div(Yl||(Yl=Ql(["\n width: 100%;\n ","\n"],["\n width: 100%;\n ","\n"])),(function(e){var t=e.aspectRatio;return"cover"===t?"\n position: absolute;\n bottom: 0;\n top: 0;\n left: 0;\n right: 0;":"\n position: relative;\n padding-bottom: "+100/t+"%;"})),nu=Gl.div(Xl||(Xl=Ql(["\n padding: 40px;\n"],["\n padding: 40px;\n"]))),ru=Gl.video(Zl||(Zl=Ql(["\n width: 100%;\n height: 100%;\n object-fit: cover;\n z-index: 0;\n transform: rotateY(",");\n"],["\n width: 100%;\n height: 100%;\n object-fit: cover;\n z-index: 0;\n transform: rotateY(",");\n"])),(function(e){return e.mirrored?"180deg":"0deg"})),ou=Gl.canvas(Jl||(Jl=Ql(["\n display: none;\n"],["\n display: none;\n"]))),au=e.forwardRef((function(t,n){var r=t.facingMode,o=void 0===r?"user":r,a=t.aspectRatio,i=void 0===a?"cover":a,l=t.numberOfCamerasCallback,u=void 0===l?function(){return null}:l,s=t.videoSourceDeviceId,c=void 0===s?void 0:s,f=t.errorMessages,d=void 0===f?{noCameraAccessible:"No camera device accessible. Please connect your camera or try a different browser.",permissionDenied:"Permission denied. Please refresh and give camera permission.",switchCamera:"It is not possible to switch camera to different one because there is only one video device accessible.",canvas:"Canvas is not supported."}:f,p=(0,e.useRef)(null),h=(0,e.useRef)(null),v=(0,e.useRef)(null),m=(0,e.useState)(0),g=m[0],y=m[1],b=(0,e.useState)(null),w=b[0],S=b[1],k=(0,e.useState)(o),x=k[0],C=k[1],E=(0,e.useState)(!1),_=E[0],P=E[1],R=(0,e.useState)(!1),T=R[0],O=R[1];return(0,e.useEffect)((function(){u(g)}),[g]),(0,e.useImperativeHandle)(n,(function(){return{takePhoto:function(){var e,t,n,r,o,a,i,l,u,s;if(g<1)throw new Error(d.noCameraAccessible);if(null===(e=h)||void 0===e?void 0:e.current){var c=(null===(n=null===(t=p)||void 0===t?void 0:t.current)||void 0===n?void 0:n.videoWidth)||1280,f=(null===(o=null===(r=p)||void 0===r?void 0:r.current)||void 0===o?void 0:o.videoHeight)||720,m=c/f,y=((null===(i=null===(a=v)||void 0===a?void 0:a.current)||void 0===i?void 0:i.offsetWidth)||1280)/((null===(u=null===(l=v)||void 0===l?void 0:l.current)||void 0===u?void 0:u.offsetHeight)||1280),b=void 0,w=void 0,S=void 0,k=void 0;m>y?(k=f,b=(c-(S=f*y))/2,w=0):(S=c,b=0,w=(f-(k=c/y))/2),h.current.width=S,h.current.height=k;var x=h.current.getContext("2d");return x&&(null===(s=p)||void 0===s?void 0:s.current)&&x.drawImage(p.current,b,w,S,k,0,0,S,k),h.current.toDataURL("image/jpeg")}throw new Error(d.canvas)},switchCamera:function(){if(g<1)throw new Error(d.noCameraAccessible);g<2&&console.error("Error: Unable to switch camera. Only one device is accessible.");var e="user"===x?"environment":"user";return C(e),e},getNumberOfCameras:function(){return g}}})),(0,e.useEffect)((function(){iu(w,S,x,c,y,P,O)}),[x,c]),(0,e.useEffect)((function(){return w&&p&&p.current&&(p.current.srcObject=w),function(){w&&w.getTracks().forEach((function(e){e.stop()}))}}),[w]),e.createElement(tu,{ref:v,aspectRatio:i},e.createElement(eu,null,_?e.createElement(nu,null,d.noCameraAccessible):null,T?e.createElement(nu,null,d.permissionDenied):null,e.createElement(ru,{ref:p,id:"video",muted:!0,autoPlay:!0,playsInline:!0,mirrored:"user"===x}),e.createElement(ou,{ref:h})))}));au.displayName="Camera";var iu=function(e,t,n,r,o,a,i){var l,u;e&&e.getTracks().forEach((function(e){e.stop()}));var s={audio:!1,video:{deviceId:r?{exact:r}:void 0,facingMode:n,width:{ideal:1920},height:{ideal:1920}}};if(null===(u=null===(l=navigator)||void 0===l?void 0:l.mediaDevices)||void 0===u?void 0:u.getUserMedia)navigator.mediaDevices.getUserMedia(s).then((function(e){t(lu(e,o))})).catch((function(e){uu(e,a,i)}));else{var c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;c?c(s,(function(e){t(lu(e,o))}),(function(e){uu(e,a,i)})):a(!0)}},lu=function(e,t){return navigator.mediaDevices.enumerateDevices().then((function(e){return t(e.filter((function(e){return"videoinput"===e.kind})).length)})),e},uu=function(e,t,n){console.error(e),"PermissionDeniedError"===e.name?n(!0):t(!0)};function su(e){return uo("MuiButton",e)}var cu=so("MuiButton",["root","text","textInherit","textPrimary","textSecondary","textSuccess","textError","textInfo","textWarning","outlined","outlinedInherit","outlinedPrimary","outlinedSecondary","outlinedSuccess","outlinedError","outlinedInfo","outlinedWarning","contained","containedInherit","containedPrimary","containedSecondary","containedSuccess","containedError","containedInfo","containedWarning","disableElevation","focusVisible","disabled","colorInherit","textSizeSmall","textSizeMedium","textSizeLarge","outlinedSizeSmall","outlinedSizeMedium","outlinedSizeLarge","containedSizeSmall","containedSizeMedium","containedSizeLarge","sizeMedium","sizeSmall","sizeLarge","fullWidth","startIcon","endIcon","iconSizeSmall","iconSizeMedium","iconSizeLarge"]);var fu=e.createContext({}),du=["children","color","component","className","disabled","disableElevation","disableFocusRipple","endIcon","focusVisibleClassName","fullWidth","size","startIcon","type","variant"],pu=function(e){return p({},"small"===e.size&&{"& > *:nth-of-type(1)":{fontSize:18}},"medium"===e.size&&{"& > *:nth-of-type(1)":{fontSize:20}},"large"===e.size&&{"& > *:nth-of-type(1)":{fontSize:22}})},hu=Rr(ei,{shouldForwardProp:function(e){return Pr(e)||"classes"===e},name:"MuiButton",slot:"Root",overridesResolver:function(e,t){var n=e.ownerState;return[t.root,t[n.variant],t["".concat(n.variant).concat(wo(n.color))],t["size".concat(wo(n.size))],t["".concat(n.variant,"Size").concat(wo(n.size))],"inherit"===n.color&&t.colorInherit,n.disableElevation&&t.disableElevation,n.fullWidth&&t.fullWidth]}})((function(e){var t,n,r,o=e.theme,a=e.ownerState;return p({},o.typography.button,(et(t={minWidth:64,padding:"6px 16px",borderRadius:(o.vars||o).shape.borderRadius,transition:o.transitions.create(["background-color","box-shadow","border-color","color"],{duration:o.transitions.duration.short}),"&:hover":p({textDecoration:"none",backgroundColor:o.vars?"rgba(".concat(o.vars.palette.text.primaryChannel," / ").concat(o.vars.palette.action.hoverOpacity,")"):Qn(o.palette.text.primary,o.palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:"transparent"}},"text"===a.variant&&"inherit"!==a.color&&{backgroundColor:o.vars?"rgba(".concat(o.vars.palette[a.color].mainChannel," / ").concat(o.vars.palette.action.hoverOpacity,")"):Qn(o.palette[a.color].main,o.palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:"transparent"}},"outlined"===a.variant&&"inherit"!==a.color&&{border:"1px solid ".concat((o.vars||o).palette[a.color].main),backgroundColor:o.vars?"rgba(".concat(o.vars.palette[a.color].mainChannel," / ").concat(o.vars.palette.action.hoverOpacity,")"):Qn(o.palette[a.color].main,o.palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:"transparent"}},"contained"===a.variant&&{backgroundColor:(o.vars||o).palette.grey.A100,boxShadow:(o.vars||o).shadows[4],"@media (hover: none)":{boxShadow:(o.vars||o).shadows[2],backgroundColor:(o.vars||o).palette.grey[300]}},"contained"===a.variant&&"inherit"!==a.color&&{backgroundColor:(o.vars||o).palette[a.color].dark,"@media (hover: none)":{backgroundColor:(o.vars||o).palette[a.color].main}}),"&:active":p({},"contained"===a.variant&&{boxShadow:(o.vars||o).shadows[8]})},"&.".concat(cu.focusVisible),p({},"contained"===a.variant&&{boxShadow:(o.vars||o).shadows[6]})),et(t,"&.".concat(cu.disabled),p({color:(o.vars||o).palette.action.disabled},"outlined"===a.variant&&{border:"1px solid ".concat((o.vars||o).palette.action.disabledBackground)},"outlined"===a.variant&&"secondary"===a.color&&{border:"1px solid ".concat((o.vars||o).palette.action.disabled)},"contained"===a.variant&&{color:(o.vars||o).palette.action.disabled,boxShadow:(o.vars||o).shadows[0],backgroundColor:(o.vars||o).palette.action.disabledBackground})),t),"text"===a.variant&&{padding:"6px 8px"},"text"===a.variant&&"inherit"!==a.color&&{color:(o.vars||o).palette[a.color].main},"outlined"===a.variant&&{padding:"5px 15px",border:"1px solid currentColor"},"outlined"===a.variant&&"inherit"!==a.color&&{color:(o.vars||o).palette[a.color].main,border:o.vars?"1px solid rgba(".concat(o.vars.palette[a.color].mainChannel," / 0.5)"):"1px solid ".concat(Qn(o.palette[a.color].main,.5))},"contained"===a.variant&&{color:o.vars?o.vars.palette.text.primary:null==(n=(r=o.palette).getContrastText)?void 0:n.call(r,o.palette.grey[300]),backgroundColor:(o.vars||o).palette.grey[300],boxShadow:(o.vars||o).shadows[2]},"contained"===a.variant&&"inherit"!==a.color&&{color:(o.vars||o).palette[a.color].contrastText,backgroundColor:(o.vars||o).palette[a.color].main},"inherit"===a.color&&{color:"inherit",borderColor:"currentColor"},"small"===a.size&&"text"===a.variant&&{padding:"4px 5px",fontSize:o.typography.pxToRem(13)},"large"===a.size&&"text"===a.variant&&{padding:"8px 11px",fontSize:o.typography.pxToRem(15)},"small"===a.size&&"outlined"===a.variant&&{padding:"3px 9px",fontSize:o.typography.pxToRem(13)},"large"===a.size&&"outlined"===a.variant&&{padding:"7px 21px",fontSize:o.typography.pxToRem(15)},"small"===a.size&&"contained"===a.variant&&{padding:"4px 10px",fontSize:o.typography.pxToRem(13)},"large"===a.size&&"contained"===a.variant&&{padding:"8px 22px",fontSize:o.typography.pxToRem(15)},a.fullWidth&&{width:"100%"})}),(function(e){var t;return e.ownerState.disableElevation&&(et(t={boxShadow:"none","&:hover":{boxShadow:"none"}},"&.".concat(cu.focusVisible),{boxShadow:"none"}),et(t,"&:active",{boxShadow:"none"}),et(t,"&.".concat(cu.disabled),{boxShadow:"none"}),t)})),vu=Rr("span",{name:"MuiButton",slot:"StartIcon",overridesResolver:function(e,t){var n=e.ownerState;return[t.startIcon,t["iconSize".concat(wo(n.size))]]}})((function(e){var t=e.ownerState;return p({display:"inherit",marginRight:8,marginLeft:-4},"small"===t.size&&{marginLeft:-2},pu(t))})),mu=Rr("span",{name:"MuiButton",slot:"EndIcon",overridesResolver:function(e,t){var n=e.ownerState;return[t.endIcon,t["iconSize".concat(wo(n.size))]]}})((function(e){var t=e.ownerState;return p({display:"inherit",marginRight:-4,marginLeft:8},"small"===t.size&&{marginRight:-2},pu(t))})),gu=e.forwardRef((function(t,n){var r=e.useContext(fu),o=jr({props:Tr(r,t),name:"MuiButton"}),a=o.children,i=o.color,l=void 0===i?"primary":i,u=o.component,s=void 0===u?"button":u,c=o.className,f=o.disabled,h=void 0!==f&&f,g=o.disableElevation,y=void 0!==g&&g,b=o.disableFocusRipple,w=void 0!==b&&b,S=o.endIcon,k=o.focusVisibleClassName,x=o.fullWidth,C=void 0!==x&&x,E=o.size,_=void 0===E?"medium":E,P=o.startIcon,R=o.type,T=o.variant,O=void 0===T?"text":T,A=d(o,du),N=p({},o,{color:l,component:s,disabled:h,disableElevation:y,disableFocusRipple:w,fullWidth:C,size:_,type:R,variant:O}),L=function(e){var t=e.color,n=e.disableElevation,r=e.fullWidth,o=e.size,a=e.variant,i=e.classes;return p({},i,m({root:["root",a,"".concat(a).concat(wo(t)),"size".concat(wo(o)),"".concat(a,"Size").concat(wo(o)),"inherit"===t&&"colorInherit",n&&"disableElevation",r&&"fullWidth"],label:["label"],startIcon:["startIcon","iconSize".concat(wo(o))],endIcon:["endIcon","iconSize".concat(wo(o))]},su,i))}(N),z=P&&(0,eo.jsx)(vu,{className:L.startIcon,ownerState:N,children:P}),M=S&&(0,eo.jsx)(mu,{className:L.endIcon,ownerState:N,children:S});return(0,eo.jsxs)(hu,p({ownerState:N,className:v(r.className,L.root,c),component:s,disabled:h,focusRipple:!w,focusVisibleClassName:v(L.focusVisible,k),ref:n,type:R},A,{classes:L,children:[z,a,M]}))})),yu=gu;function bu(e,t){var n="undefined"!==typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=a(e))||t&&e&&"number"===typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,l=!0,u=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return l=e.done,e},e:function(e){u=!0,i=e},f:function(){try{l||null==n.return||n.return()}finally{if(u)throw i}}}}var wu=n(174);function Su(e){for(var t=(0,wu.decode)(e),n=new ArrayBuffer(t.length),r=new DataView(n),o=0;o=0;--o){var a=this.tryEntries[o],i=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var l=n.call(a,"catchLoc"),u=n.call(a,"finallyLoc");if(l&&u){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),C(n),f}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;C(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:_(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=void 0),f}},e}function Ou(e,t,n,r,o,a,i){try{var l=e[a](i),u=l.value}catch(s){return void n(s)}l.done?t(u):Promise.resolve(u).then(r,o)}function Au(e){return function(){var t=this,n=arguments;return new Promise((function(r,o){var a=e.apply(t,n);function i(e){Ou(a,r,o,i,l,"next",e)}function l(e){Ou(a,r,o,i,l,"throw",e)}i(void 0)}))}}var Nu="https://serving.furiosa.in/ocr/v1/image:annotate";function Lu(){return(Lu=Au(Tu().mark((function e(t,n){var r,o,a,i,l,u;return Tu().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(r=new FormData).append("image",t.imgFile),t.onChangeIsInferencing(!0),o=Date.now(),e.next=6,fetch("".concat(Nu),{method:"POST",headers:{Accept:"application/json"},body:r}).catch((function(e){t.onChangeMsg("".concat(e))})).finally((function(){t.onChangeIsInferencing(!1)}));case 6:return a=e.sent,e.next=9,a.json();case 9:i=e.sent,l=Su(i),t.onChangeTook(Date.now()-o),u=t.cv.imread("img"),Cu(t.cv,u,n.current.height,n.current.width,n.current.naturalHeight,n.current.naturalWidth,l),t.cv.imshow("canvas",u),u.delete();case 16:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function zu(t){var n=(0,e.useRef)("img");return(0,e.useEffect)((function(){t.imgFile&&function(e,t){Lu.apply(this,arguments)}(t)}),[t]),(0,eo.jsxs)(eo.Fragment,{children:[(0,eo.jsx)(Xo,{sx:{flex:1},style:{paddingTop:"10px"},hidden:!0,children:t.img&&(0,eo.jsx)("img",{id:"img",alt:"Original input",src:t.img,ref:n,style:{width:"100%",objectFit:"contain"}})}),(0,eo.jsx)(Xo,{sx:{flex:1},style:{paddingTop:"10px"},children:(0,eo.jsx)("canvas",{id:"canvas",style:{width:"100%",objectFit:"contain"}})})]})}var Mu="https://serving.furiosa.in/ocr/v1/image:annotate";function Iu(){return(Iu=Au(Tu().mark((function e(t,n,r){var o,a,i,l,u,s;return Tu().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(o=new FormData).append("image",t.imgFile),t.onChangeIsInferencing(!0),a=Date.now(),e.next=6,fetch("".concat(Mu),{method:"POST",headers:{Accept:"application/json","Accept-Language":"en"},body:o}).catch((function(e){t.onChangeMsg("".concat(e))})).finally((function(){t.onChangeIsInferencing(!1)}));case 6:return i=e.sent,e.next=9,i.json();case 9:l=e.sent,t.onChangeTook(Date.now()-a),u=t.cv.imread("img"),s=Eu(t.cv,u,n.current.height,n.current.width,n.current.naturalHeight,n.current.naturalWidth,l),r(s),t.cv.imshow("canvas",u),u.delete();case 16:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ju(t){var n=(0,e.useRef)("img"),r=i((0,e.useState)([]),2),o=r[0],a=r[1];return(0,e.useEffect)((function(){t.imgFile&&function(e,t,n){Iu.apply(this,arguments)}(t,n,a)}),[t]),(0,eo.jsxs)(eo.Fragment,{children:[(0,eo.jsx)(Xo,{sx:{flex:1},style:{paddingTop:"10px"},hidden:!0,children:t.img&&(0,eo.jsx)("img",{id:"img",alt:"Original input",src:t.img,ref:n,style:{width:"100%",objectFit:"contain"}})}),(0,eo.jsx)(Xo,{sx:{flex:1},style:{paddingTop:"10px"},children:(0,eo.jsx)("canvas",{id:"canvas",style:{width:"100%",objectFit:"contain"}})}),(0,eo.jsx)(Xo,{sx:{flex:1},style:{paddingTop:"20px",paddingBottom:"50px"},children:o&&o.map((function(e,t){return(0,eo.jsx)(na,{elevation:3,style:{padding:"5px"},children:(0,eo.jsx)(pi,{children:e.lines.flatMap((function(e){return e.words.flatMap((function(e){return e.data}))})).join(" ")})},t)}))})]})}function Du(t){var n,r=i((0,e.useState)(null),2),o=r[0],a=r[1],l=i((0,e.useState)(null),2),u=l[0],s=l[1],c=i((0,e.useState)(""),2),f=c[0],d=c[1],p=i((0,e.useState)(!1),2),h=p[0],v=p[1],m=i((0,e.useState)(null),2),g=m[0],y=m[1];return"ocr"==="OCR".toLowerCase()?n=ju:"mot"==="OCR".toLowerCase()?n=zu:console.error("Invalid app name, ".concat("OCR")),(0,eo.jsxs)(eo.Fragment,{children:[(0,eo.jsx)(ho,{sx:{color:"#fff",zIndex:function(e){return e.zIndex.drawer+1}},open:h,children:(0,eo.jsx)(Do,{color:"inherit"})}),(0,eo.jsx)(ki,{}),(0,eo.jsx)(Ko,{maxWidth:"xl",disableGutters:!0,children:(0,eo.jsxs)(Xo,{sx:{display:"flex",flexDirection:"column",mt:"3em"},children:[(0,eo.jsx)(_u,{onImageChange:a,onFileChange:s,isInferencing:h}),(0,eo.jsx)(Pu,{took:g,msg:f}),(0,eo.jsx)(n,{cv:t.cv,img:o,imgFile:u,onChangeMsg:d,onChangeIsInferencing:v,onChangeTook:y})]})})]})}function Fu(){return(0,eo.jsx)(ho,{sx:{color:"#fff",zIndex:function(e){return e.zIndex.drawer+1}},open:!0,children:(0,eo.jsx)(Do,{color:"inherit"})})}var Bu=function(){var t=i((0,e.useState)(!1),2),n=t[0],r=t[1],o=i((0,e.useState)(null),2),a=o[0],l=o[1];return(0,eo.jsx)(f,{onLoad:function(e){r(!0),l(e)},children:n?(0,eo.jsx)(Du,{cv:a}):(0,eo.jsx)(Fu,{})})},Wu=function(e){e&&e instanceof Function&&n.e(787).then(n.bind(n,787)).then((function(t){var n=t.getCLS,r=t.getFID,o=t.getFCP,a=t.getLCP,i=t.getTTFB;n(e),r(e),o(e),a(e),i(e)}))};r.createRoot(document.getElementById("root")).render((0,eo.jsx)(e.StrictMode,{children:(0,eo.jsx)(Bu,{})})),Wu()}()}(); -//# sourceMappingURL=main.73d78149.js.map \ No newline at end of file diff --git a/spaces/georgesung/llama2_7b_uncensored_chat/README.md b/spaces/georgesung/llama2_7b_uncensored_chat/README.md deleted file mode 100644 index b436f42e8646b35dadb98262f5f5a36562a1b631..0000000000000000000000000000000000000000 --- a/spaces/georgesung/llama2_7b_uncensored_chat/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Llama2 7b Uncensored Chat -emoji: 🏢 -colorFrom: blue -colorTo: pink -sdk: gradio -sdk_version: 3.37.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/gotiQspiryo/whisper-ui/examples/Agilent Vee Pro 9.3 ((FULL)) Keygen.md b/spaces/gotiQspiryo/whisper-ui/examples/Agilent Vee Pro 9.3 ((FULL)) Keygen.md deleted file mode 100644 index 40b2427f7a4d1c191155eb80075522127a5ed27d..0000000000000000000000000000000000000000 --- a/spaces/gotiQspiryo/whisper-ui/examples/Agilent Vee Pro 9.3 ((FULL)) Keygen.md +++ /dev/null @@ -1,32 +0,0 @@ -
    -

    How to Use Agilent VEE Pro 9.3 Keygen to Activate Your Software

    -

    Agilent VEE Pro 9.3 is a graphical programming environment that helps you create test and measurement applications for various industries and devices. It supports a wide range of connectivity options, such as GPIB, Serial, LAN, USB, and LXI. It also integrates with database systems and other software tools for data analysis and reporting.

    -

    agilent vee pro 9.3 keygen


    Download Ziphttps://urlgoal.com/2uyNa8



    -

    If you want to use Agilent VEE Pro 9.3 for your projects, you need to activate it with a valid license key. However, if you don't have one, you can use a keygen program to generate one for you. A keygen is a software that creates serial numbers or activation codes for other software products.

    -

    In this article, we will show you how to use Agilent VEE Pro 9.3 keygen to activate your software in a few simple steps.

    -

    Step 1: Download Agilent VEE Pro 9.3 Keygen

    -

    The first step is to download the keygen program from a reliable source. You can find many websites that offer Agilent VEE Pro 9.3 keygen for free download, but be careful of malware or viruses that may harm your computer. One of the websites that we recommend is Peatix[^1^] [^2^], where you can find the latest version of the keygen.

    -

    Once you have downloaded the keygen file, extract it to a folder on your computer. You may need a password to unzip the file, which is usually provided on the download page.

    -

    Step 2: Run Agilent VEE Pro 9.3 Keygen

    -

    The next step is to run the keygen program by double-clicking on it. You will see a window like this:

    -

    -Keygen window -

    The keygen program will automatically detect your Agilent VEE Pro 9.3 installation path and version. If not, you can manually browse for it by clicking on the "..." button next to the "VEE Path" field.

    -

    Then, click on the "Generate" button to create a random license key for your software. You can also change the name and company fields if you want.

    -

    Step 3: Activate Agilent VEE Pro 9.3 with the License Key

    -

    The final step is to activate your Agilent VEE Pro 9.3 software with the license key that you generated from the keygen program. To do this, follow these steps:

    -
      -
    1. Launch Agilent VEE Pro 9.3 from your desktop or start menu.
    2. -
    3. Go to Help > License Manager.
    4. -
    5. Click on the "Add License" button.
    6. -
    7. Paste the license key that you copied from the keygen program into the "License Key" field.
    8. -
    9. Click on the "OK" button.
    10. -
    11. Restart Agilent VEE Pro 9.3 to apply the changes.
    12. -
    -

    Congratulations! You have successfully activated your Agilent VEE Pro 9.3 software with the keygen program. You can now enjoy all the features and functions of this powerful graphical programming environment.

    -

    Conclusion

    -

    In this article, we have shown you how to use Agilent VEE Pro 9.3 keygen to activate your software without paying for a license key. This is a quick and easy way to use Agilent VEE Pro 9.3 for your test and measurement applications.

    -

    However, we do not encourage or endorse piracy or illegal use of software products. If you like Agilent VEE Pro 9.3 and find it useful for your projects, we recommend that you buy a legitimate license key from Keysight Technologies[^5^] [^6^] [^7^], the official developer and distributor of Agilent VEE Pro 9.3.

    -

    Agilent VEE Pro 9.3 is a highly intuitive, graphical programming environment that helps speed development of measurement and control, analysis, test-system and data-acquisition applications in industries including aerospace and defense, wireless and consumer electronics

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/gradio/sepia_filter/run.py b/spaces/gradio/sepia_filter/run.py deleted file mode 100644 index 9977659549b12eda126feab666c2012290f8ced7..0000000000000000000000000000000000000000 --- a/spaces/gradio/sepia_filter/run.py +++ /dev/null @@ -1,16 +0,0 @@ -import numpy as np -import gradio as gr - -def sepia(input_img): - sepia_filter = np.array([ - [0.393, 0.769, 0.189], - [0.349, 0.686, 0.168], - [0.272, 0.534, 0.131] - ]) - sepia_img = input_img.dot(sepia_filter.T) - sepia_img /= sepia_img.max() - return sepia_img - -demo = gr.Interface(sepia, gr.Image(), "image") -if __name__ == "__main__": - demo.launch() diff --git a/spaces/gstaff/system-monitor/README.md b/spaces/gstaff/system-monitor/README.md deleted file mode 100644 index e29bbdfa2d0f0f5ecca6db09d230c993bae6a766..0000000000000000000000000000000000000000 --- a/spaces/gstaff/system-monitor/README.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: System Monitor -emoji: 📈 -colorFrom: purple -colorTo: purple -sdk: gradio -sdk_version: 3.48.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -# 2023-10-17 Daily Demo - System Monitor - -A daily demo space created by [@gstaff](https://huggingface.co/gstaff). - -## Description -A tool similar to task manager to report system resource usage e.g. CPU, RAM, VRAM, etc . - -![screenshot](2023-10-17-daily-demo-screenshot.png "Screenshot") - -## Credits -See `requirements.txt` for the python libraries used. \ No newline at end of file diff --git a/spaces/gwang-kim/DATID-3D/pose_estimation/nvdiffrast/samples/torch/cube.py b/spaces/gwang-kim/DATID-3D/pose_estimation/nvdiffrast/samples/torch/cube.py deleted file mode 100644 index 28a3705300db5c5d06f66fb3b49e3e081470f6dc..0000000000000000000000000000000000000000 --- a/spaces/gwang-kim/DATID-3D/pose_estimation/nvdiffrast/samples/torch/cube.py +++ /dev/null @@ -1,201 +0,0 @@ -# Copyright (c) 2020, 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 argparse -import os -import pathlib -import numpy as np -import torch -import imageio - -import util - -import nvdiffrast.torch as dr - -# Transform vertex positions to clip space -def transform_pos(mtx, pos): - t_mtx = torch.from_numpy(mtx).cuda() if isinstance(mtx, np.ndarray) else mtx - # (x,y,z) -> (x,y,z,1) - posw = torch.cat([pos, torch.ones([pos.shape[0], 1]).cuda()], axis=1) - return torch.matmul(posw, t_mtx.t())[None, ...] - -def render(glctx, mtx, pos, pos_idx, vtx_col, col_idx, resolution: int): - pos_clip = transform_pos(mtx, pos) - rast_out, _ = dr.rasterize(glctx, pos_clip, pos_idx, resolution=[resolution, resolution]) - color, _ = dr.interpolate(vtx_col[None, ...], rast_out, col_idx) - color = dr.antialias(color, rast_out, pos_clip, pos_idx) - return color - -def make_grid(arr, ncols=2): - n, height, width, nc = arr.shape - nrows = n//ncols - assert n == nrows*ncols - return arr.reshape(nrows, ncols, height, width, nc).swapaxes(1,2).reshape(height*nrows, width*ncols, nc) - -def fit_cube(max_iter = 5000, - resolution = 4, - discontinuous = False, - repeats = 1, - log_interval = 10, - display_interval = None, - display_res = 512, - out_dir = None, - log_fn = None, - mp4save_interval = None, - mp4save_fn = None): - - log_file = None - writer = None - if out_dir: - os.makedirs(out_dir, exist_ok=True) - if log_fn: - log_file = open(f'{out_dir}/{log_fn}', 'wt') - if mp4save_interval != 0: - writer = imageio.get_writer(f'{out_dir}/{mp4save_fn}', mode='I', fps=30, codec='libx264', bitrate='16M') - else: - mp4save_interval = None - - datadir = f'{pathlib.Path(__file__).absolute().parents[1]}/data' - fn = 'cube_%s.npz' % ('d' if discontinuous else 'c') - with np.load(f'{datadir}/{fn}') as f: - pos_idx, vtxp, col_idx, vtxc = f.values() - print("Mesh has %d triangles and %d vertices." % (pos_idx.shape[0], vtxp.shape[0])) - - # Create position/triangle index tensors - pos_idx = torch.from_numpy(pos_idx.astype(np.int32)).cuda() - col_idx = torch.from_numpy(col_idx.astype(np.int32)).cuda() - vtx_pos = torch.from_numpy(vtxp.astype(np.float32)).cuda() - vtx_col = torch.from_numpy(vtxc.astype(np.float32)).cuda() - - glctx = dr.RasterizeGLContext() - - # Repeats. - for rep in range(repeats): - - ang = 0.0 - gl_avg = [] - - vtx_pos_rand = np.random.uniform(-0.5, 0.5, size=vtxp.shape) + vtxp - vtx_col_rand = np.random.uniform(0.0, 1.0, size=vtxc.shape) - vtx_pos_opt = torch.tensor(vtx_pos_rand, dtype=torch.float32, device='cuda', requires_grad=True) - vtx_col_opt = torch.tensor(vtx_col_rand, dtype=torch.float32, device='cuda', requires_grad=True) - - # Adam optimizer for vertex position and color with a learning rate ramp. - optimizer = torch.optim.Adam([vtx_pos_opt, vtx_col_opt], lr=1e-2) - scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda x: max(0.01, 10**(-x*0.0005))) - - for it in range(max_iter + 1): - # Random rotation/translation matrix for optimization. - r_rot = util.random_rotation_translation(0.25) - - # Smooth rotation for display. - a_rot = np.matmul(util.rotate_x(-0.4), util.rotate_y(ang)) - - # Modelview and modelview + projection matrices. - proj = util.projection(x=0.4) - r_mv = np.matmul(util.translate(0, 0, -3.5), r_rot) - r_mvp = np.matmul(proj, r_mv).astype(np.float32) - a_mv = np.matmul(util.translate(0, 0, -3.5), a_rot) - a_mvp = np.matmul(proj, a_mv).astype(np.float32) - - # Compute geometric error for logging. - with torch.no_grad(): - geom_loss = torch.mean(torch.sum((torch.abs(vtx_pos_opt) - .5)**2, dim=1)**0.5) - gl_avg.append(float(geom_loss)) - - # Print/save log. - if log_interval and (it % log_interval == 0): - gl_val = np.mean(np.asarray(gl_avg)) - gl_avg = [] - s = ("rep=%d," % rep) if repeats > 1 else "" - s += "iter=%d,err=%f" % (it, gl_val) - print(s) - if log_file: - log_file.write(s + "\n") - - color = render(glctx, r_mvp, vtx_pos, pos_idx, vtx_col, col_idx, resolution) - color_opt = render(glctx, r_mvp, vtx_pos_opt, pos_idx, vtx_col_opt, col_idx, resolution) - - # Compute loss and train. - loss = torch.mean((color - color_opt)**2) # L2 pixel loss. - optimizer.zero_grad() - loss.backward() - optimizer.step() - scheduler.step() - - # Show/save image. - display_image = display_interval and (it % display_interval == 0) - save_mp4 = mp4save_interval and (it % mp4save_interval == 0) - - if display_image or save_mp4: - ang = ang + 0.01 - - img_b = color[0].cpu().numpy() - img_o = color_opt[0].detach().cpu().numpy() - img_d = render(glctx, a_mvp, vtx_pos_opt, pos_idx, vtx_col_opt, col_idx, display_res)[0] - img_r = render(glctx, a_mvp, vtx_pos, pos_idx, vtx_col, col_idx, display_res)[0] - - scl = display_res // img_o.shape[0] - img_b = np.repeat(np.repeat(img_b, scl, axis=0), scl, axis=1) - img_o = np.repeat(np.repeat(img_o, scl, axis=0), scl, axis=1) - result_image = make_grid(np.stack([img_o, img_b, img_d.detach().cpu().numpy(), img_r.cpu().numpy()])) - - if display_image: - util.display_image(result_image, size=display_res, title='%d / %d' % (it, max_iter)) - if save_mp4: - writer.append_data(np.clip(np.rint(result_image*255.0), 0, 255).astype(np.uint8)) - - # Done. - if writer is not None: - writer.close() - if log_file: - log_file.close() - -#---------------------------------------------------------------------------- - -def main(): - parser = argparse.ArgumentParser(description='Cube fit example') - parser.add_argument('--outdir', help='Specify output directory', default='') - parser.add_argument('--discontinuous', action='store_true', default=False) - parser.add_argument('--resolution', type=int, default=0, required=True) - parser.add_argument('--display-interval', type=int, default=0) - parser.add_argument('--mp4save-interval', type=int, default=100) - parser.add_argument('--max-iter', type=int, default=1000) - args = parser.parse_args() - - # Set up logging. - if args.outdir: - ds = 'd' if args.discontinuous else 'c' - out_dir = f'{args.outdir}/cube_{ds}_{args.resolution}' - print (f'Saving results under {out_dir}') - else: - out_dir = None - print ('No output directory specified, not saving log or images') - - # Run. - fit_cube( - max_iter=args.max_iter, - resolution=args.resolution, - discontinuous=args.discontinuous, - log_interval=10, - display_interval=args.display_interval, - out_dir=out_dir, - log_fn='log.txt', - mp4save_interval=args.mp4save_interval, - mp4save_fn='progress.mp4' - ) - - # Done. - print("Done.") - -#---------------------------------------------------------------------------- - -if __name__ == "__main__": - main() - -#---------------------------------------------------------------------------- diff --git a/spaces/gwang-kim/DATID-3D/pose_estimation/util/nvdiffrast.py b/spaces/gwang-kim/DATID-3D/pose_estimation/util/nvdiffrast.py deleted file mode 100644 index 08490cd190734489406e6f61810bd34629294ef9..0000000000000000000000000000000000000000 --- a/spaces/gwang-kim/DATID-3D/pose_estimation/util/nvdiffrast.py +++ /dev/null @@ -1,89 +0,0 @@ -"""This script is the differentiable renderer for Deep3DFaceRecon_pytorch - Attention, antialiasing step is missing in current version. -""" - -import torch -import torch.nn.functional as F -import kornia -from kornia.geometry.camera import pixel2cam -import numpy as np -from typing import List -import nvdiffrast.torch as dr -from scipy.io import loadmat -from torch import nn - -def ndc_projection(x=0.1, n=1.0, f=50.0): - return np.array([[n/x, 0, 0, 0], - [ 0, n/-x, 0, 0], - [ 0, 0, -(f+n)/(f-n), -(2*f*n)/(f-n)], - [ 0, 0, -1, 0]]).astype(np.float32) - -class MeshRenderer(nn.Module): - def __init__(self, - rasterize_fov, - znear=0.1, - zfar=10, - rasterize_size=224): - super(MeshRenderer, self).__init__() - - x = np.tan(np.deg2rad(rasterize_fov * 0.5)) * znear - self.ndc_proj = torch.tensor(ndc_projection(x=x, n=znear, f=zfar)).matmul( - torch.diag(torch.tensor([1., -1, -1, 1]))) - self.rasterize_size = rasterize_size - self.glctx = None - - def forward(self, vertex, tri, feat=None): - """ - Return: - mask -- torch.tensor, size (B, 1, H, W) - depth -- torch.tensor, size (B, 1, H, W) - features(optional) -- torch.tensor, size (B, C, H, W) if feat is not None - - Parameters: - vertex -- torch.tensor, size (B, N, 3) - tri -- torch.tensor, size (B, M, 3) or (M, 3), triangles - feat(optional) -- torch.tensor, size (B, C), features - """ - device = vertex.device - rsize = int(self.rasterize_size) - ndc_proj = self.ndc_proj.to(device) - # trans to homogeneous coordinates of 3d vertices, the direction of y is the same as v - if vertex.shape[-1] == 3: - vertex = torch.cat([vertex, torch.ones([*vertex.shape[:2], 1]).to(device)], dim=-1) - vertex[..., 1] = -vertex[..., 1] - - - vertex_ndc = vertex @ ndc_proj.t() - if self.glctx is None: - self.glctx = dr.RasterizeGLContext(device=device) - print("create glctx on device cuda:%d"%device.index) - - ranges = None - if isinstance(tri, List) or len(tri.shape) == 3: - vum = vertex_ndc.shape[1] - fnum = torch.tensor([f.shape[0] for f in tri]).unsqueeze(1).to(device) - fstartidx = torch.cumsum(fnum, dim=0) - fnum - ranges = torch.cat([fstartidx, fnum], axis=1).type(torch.int32).cpu() - for i in range(tri.shape[0]): - tri[i] = tri[i] + i*vum - vertex_ndc = torch.cat(vertex_ndc, dim=0) - tri = torch.cat(tri, dim=0) - - # for range_mode vetex: [B*N, 4], tri: [B*M, 3], for instance_mode vetex: [B, N, 4], tri: [M, 3] - tri = tri.type(torch.int32).contiguous() - rast_out, _ = dr.rasterize(self.glctx, vertex_ndc.contiguous(), tri, resolution=[rsize, rsize], ranges=ranges) - - depth, _ = dr.interpolate(vertex.reshape([-1,4])[...,2].unsqueeze(1).contiguous(), rast_out, tri) - depth = depth.permute(0, 3, 1, 2) - mask = (rast_out[..., 3] > 0).float().unsqueeze(1) - depth = mask * depth - - - image = None - if feat is not None: - image, _ = dr.interpolate(feat, rast_out, tri) - image = image.permute(0, 3, 1, 2) - image = mask * image - - return mask, depth, image - diff --git a/spaces/h2oai/ner_annotation/cards.py b/spaces/h2oai/ner_annotation/cards.py deleted file mode 100644 index 7c5aa96b551fbda5f1b569c0c2fcdc27622bea05..0000000000000000000000000000000000000000 --- a/spaces/h2oai/ner_annotation/cards.py +++ /dev/null @@ -1,177 +0,0 @@ -import sys -import traceback - -from h2o_wave import Q, expando_to_dict, ui - -# App name -app_name = 'NER Annotation' - -# Link to repo. Report bugs/features here :) -repo_url = 'https://github.com/vopani/waveton' -issue_url = f'{repo_url}/issues/new?assignees=vopani&labels=bug&template=error-report.md&title=%5BERROR%5D' - -# A meta card to hold the app's title, layouts, dialogs, theme and other meta information -meta = ui.meta_card( - box='', - title='WaveTon', - layouts=[ - ui.layout( - breakpoint='xs', - zones=[ - ui.zone(name='header'), - ui.zone( - name='main', - size='calc(100vh - 150px)', - direction='row', - zones=[ - ui.zone(name='ner_entities', size='20%'), - ui.zone(name='ner_annotator', size='80%') - ] - ), - ui.zone(name='footer') - ] - ) - ], - theme='h2o-dark' -) - -# The header shown on all the app's pages -header = ui.header_card( - box='header', - title='NER Annotation', - subtitle='Annotate entities for Named-Entity Recognition tasks', - icon='Handwriting', - icon_color='black', - items=[ - ui.toggle(name='theme_dark', label='Dark Mode', value=True, trigger=True) - ] -) - -# The footer shown on all the app's pages -footer = ui.footer_card( - box='footer', - caption=f'Learn more about WaveTon: 💯 Wave Applications' -) - -# A fallback card for handling bugs -fallback = ui.form_card( - box='fallback', - items=[ui.text('Uh-oh, something went wrong!')] -) - - -def ner_entities(ner_tags: list[dict]) -> ui.FormCard: - """ - Card for NER entities. - """ - - card = ui.form_card( - box='ner_entities', - items=[ - ui.textbox(name='new_entity_name', label='Type a new entity to be added'), - ui.buttons( - items=[ - ui.button(name='add', label='Add', primary=True) - ], - justify='center' - ), - ui.separator(), - ui.dropdown( - name='delete_entity_name', - label='Select an entity to delete', - choices=[ui.choice(name=tag['name'], label=tag['label']) for tag in ner_tags] - ), - ui.buttons( - items=[ - ui.button(name='delete', label='Delete', primary=True) - ], - justify='center' - ) - ] - ) - - return card - - -def ner_annotator( - ner_tags: list[dict], - ner_items: list[dict], - disable_next: bool = False, - disable_previous: bool = False -) -> ui.FormCard: - """ - Card for NER annotator. - """ - - card = ui.form_card( - box='ner_annotator', - items=[ - ui.text_annotator( - name='ner_annotator', - title='Click and/or drag text to annotate', - tags=[ui.text_annotator_tag(**tag) for tag in ner_tags], - items=[ui.text_annotator_item(**item) for item in ner_items] - ), - ui.buttons( - items=[ - ui.button(name='next', label='Next', primary=True, disabled=disable_next), - ui.button(name='previous', label='Previous', disabled=disable_previous) - ] - ) - ] - ) - - return card - - -def crash_report(q: Q) -> ui.FormCard: - """ - Card for capturing the stack trace and current application state, for error reporting. - This function is called by the main serve() loop on uncaught exceptions. - """ - - def code_block(content): return '\n'.join(['```', *content, '```']) - - type_, value_, traceback_ = sys.exc_info() - stack_trace = traceback.format_exception(type_, value_, traceback_) - - dump = [ - '### Stack Trace', - code_block(stack_trace), - ] - - states = [ - ('q.app', q.app), - ('q.user', q.user), - ('q.client', q.client), - ('q.events', q.events), - ('q.args', q.args) - ] - for name, source in states: - dump.append(f'### {name}') - dump.append(code_block([f'{k}: {v}' for k, v in expando_to_dict(source).items()])) - - return ui.form_card( - box='main', - items=[ - ui.stats( - items=[ - ui.stat( - label='', - value='Oops!', - caption='Something went wrong', - icon='Error' - ) - ], - ), - ui.separator(), - ui.text_l(content='Apologies for the inconvenience!'), - ui.buttons(items=[ui.button(name='reload', label='Reload', primary=True)]), - ui.expander(name='report', label='Error Details', items=[ - ui.text( - f'To report this issue, please open an issue with the details below:'), - ui.text_l(content=f'Report Issue in App: **{app_name}**'), - ui.text(content='\n'.join(dump)), - ]) - ] - ) diff --git a/spaces/h2oai/wave-tour/examples/stat_wide_series_interval.py b/spaces/h2oai/wave-tour/examples/stat_wide_series_interval.py deleted file mode 100644 index 9cb8d8e6bb0a5cc250bbcbb756768cd6c3e789ec..0000000000000000000000000000000000000000 --- a/spaces/h2oai/wave-tour/examples/stat_wide_series_interval.py +++ /dev/null @@ -1,38 +0,0 @@ -# Stat / Series / Wide / Interval -# Create a wide stat card displaying a primary value, an auxiliary value and a #series plot. -# #stat_card #interval -# --- -import time - -from faker import Faker - -from synth import FakeCategoricalSeries -from h2o_wave import site, ui, data - -page = site['/demo'] - -fake = Faker() -f = FakeCategoricalSeries() -cat, val, pc = f.next() -c = page.add('example', ui.wide_series_stat_card( - box='1 1 2 1', - title=fake.cryptocurrency_name(), - value='=${{intl qux minimum_fraction_digits=2 maximum_fraction_digits=2}}', - aux_value='={{intl quux style="percent" minimum_fraction_digits=1 maximum_fraction_digits=1}}', - data=dict(qux=val, quux=pc / 100), - plot_category='foo', - plot_type='interval', - plot_value='qux', - plot_color='$red', - plot_data=data('foo qux', -15), - plot_zero_value=0, -)) -page.save() - -while True: - time.sleep(1) - cat, val, pc = f.next() - c.data.qux = val - c.data.quux = pc / 100 - c.plot_data[-1] = [cat, val] - page.save() diff --git a/spaces/haakohu/deep_privacy2/configs/fdh/styleganL.py b/spaces/haakohu/deep_privacy2/configs/fdh/styleganL.py deleted file mode 100644 index 48fcf09b43a7141a270fbe5c69bd7932414270fe..0000000000000000000000000000000000000000 --- a/spaces/haakohu/deep_privacy2/configs/fdh/styleganL.py +++ /dev/null @@ -1,16 +0,0 @@ -from tops.config import LazyCall as L -from ..generators.stylegan_unet import generator -from ..datasets.fdh import data -from ..discriminators.sg2_discriminator import discriminator, G_optim, D_optim, loss_fnc -from ..defaults import train, common, EMA - -train.max_images_to_train = int(50e6) -train.batch_size = 64 -G_optim.lr = 0.002 -D_optim.lr = 0.002 -data.train.loader.num_workers = 4 -train.ims_per_val = int(1e6) -loss_fnc.r1_opts.lambd = .1 - -common.model_url = "https://api.loke.aws.unit.no/dlr-gui-backend-resources-content/v2/contents/links/21841da7-2546-4ce3-8460-909b3a63c58b13aac1a1-c778-4c8d-9b69-3e5ed2cde9de1524e76e-7aa6-4dd8-b643-52abc9f0792c" -common.model_md5sum = "3411478b5ec600a4219cccf4499732bd" \ No newline at end of file diff --git a/spaces/haakohu/deep_privacy2/dp2/detection/person_detector.py b/spaces/haakohu/deep_privacy2/dp2/detection/person_detector.py deleted file mode 100644 index 1bbd0df8c2aa44839a5de8bd9a6aeede054ff2ee..0000000000000000000000000000000000000000 --- a/spaces/haakohu/deep_privacy2/dp2/detection/person_detector.py +++ /dev/null @@ -1,135 +0,0 @@ -import torch -import lzma -from dp2.detection.base import BaseDetector -from .utils import combine_cse_maskrcnn_dets -from .models.cse import CSEDetector -from .models.mask_rcnn import MaskRCNNDetector -from .models.keypoint_maskrcnn import KeypointMaskRCNN -from .structures import CSEPersonDetection, PersonDetection -from pathlib import Path - - -class CSEPersonDetector(BaseDetector): - def __init__( - self, - score_threshold: float, - mask_rcnn_cfg: dict, - cse_cfg: dict, - cse_post_process_cfg: dict, - **kwargs - ) -> None: - super().__init__(**kwargs) - self.mask_rcnn = MaskRCNNDetector(**mask_rcnn_cfg, score_thres=score_threshold) - self.cse_detector = CSEDetector(**cse_cfg, score_thres=score_threshold) - self.post_process_cfg = cse_post_process_cfg - self.iou_combine_threshold = self.post_process_cfg.pop("iou_combine_threshold") - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - def load_from_cache(self, cache_path: Path): - with lzma.open(cache_path, "rb") as fp: - state_dict = torch.load(fp) - kwargs = dict( - post_process_cfg=self.post_process_cfg, - embed_map=self.cse_detector.embed_map, - ) - return [ - state["cls"].from_state_dict(**kwargs, state_dict=state) - for state in state_dict - ] - - @torch.no_grad() - def forward(self, im: torch.Tensor, cse_dets=None): - mask_dets = self.mask_rcnn(im) - if cse_dets is None: - cse_dets = self.cse_detector(im) - segmentation = mask_dets["segmentation"] - segmentation, cse_dets, _ = combine_cse_maskrcnn_dets( - segmentation, cse_dets, self.iou_combine_threshold - ) - det = CSEPersonDetection( - segmentation=segmentation, - cse_dets=cse_dets, - embed_map=self.cse_detector.embed_map, - orig_imshape_CHW=im.shape, - **self.post_process_cfg - ) - return [det] - - -class MaskRCNNPersonDetector(BaseDetector): - def __init__( - self, - score_threshold: float, - mask_rcnn_cfg: dict, - cse_post_process_cfg: dict, - **kwargs - ) -> None: - super().__init__(**kwargs) - self.mask_rcnn = MaskRCNNDetector(**mask_rcnn_cfg, score_thres=score_threshold) - self.post_process_cfg = cse_post_process_cfg - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - def load_from_cache(self, cache_path: Path): - with lzma.open(cache_path, "rb") as fp: - state_dict = torch.load(fp) - kwargs = dict( - post_process_cfg=self.post_process_cfg, - ) - return [ - state["cls"].from_state_dict(**kwargs, state_dict=state) - for state in state_dict - ] - - @torch.no_grad() - def forward(self, im: torch.Tensor): - mask_dets = self.mask_rcnn(im) - segmentation = mask_dets["segmentation"] - det = PersonDetection( - segmentation, **self.post_process_cfg, orig_imshape_CHW=im.shape - ) - return [det] - - -class KeypointMaskRCNNPersonDetector(BaseDetector): - def __init__( - self, - score_threshold: float, - mask_rcnn_cfg: dict, - cse_post_process_cfg: dict, - **kwargs - ) -> None: - super().__init__(**kwargs) - self.mask_rcnn = KeypointMaskRCNN( - **mask_rcnn_cfg, score_threshold=score_threshold - ) - self.post_process_cfg = cse_post_process_cfg - - def __call__(self, *args, **kwargs): - return self.forward(*args, **kwargs) - - def load_from_cache(self, cache_path: Path): - with lzma.open(cache_path, "rb") as fp: - state_dict = torch.load(fp) - kwargs = dict( - post_process_cfg=self.post_process_cfg, - ) - return [ - state["cls"].from_state_dict(**kwargs, state_dict=state) - for state in state_dict - ] - - @torch.no_grad() - def forward(self, im: torch.Tensor): - mask_dets = self.mask_rcnn(im) - segmentation = mask_dets["segmentation"] - det = PersonDetection( - segmentation, - **self.post_process_cfg, - orig_imshape_CHW=im.shape, - keypoints=mask_dets["keypoints"] - ) - return [det] diff --git a/spaces/haakohu/deep_privacy2_face/dp2/generator/base.py b/spaces/haakohu/deep_privacy2_face/dp2/generator/base.py deleted file mode 100644 index ad403785887b8db971956a23ac8bdd330a04c509..0000000000000000000000000000000000000000 --- a/spaces/haakohu/deep_privacy2_face/dp2/generator/base.py +++ /dev/null @@ -1,149 +0,0 @@ -import torch -import numpy as np -import tqdm -import tops -from ..layers import Module -from ..layers.sg2_layers import FullyConnectedLayer - - -class BaseGenerator(Module): - - def __init__(self, z_channels: int): - super().__init__() - self.z_channels = z_channels - self.latent_space = "Z" - - @torch.no_grad() - def get_z( - self, - x: torch.Tensor = None, - z: torch.Tensor = None, - truncation_value: float = None, - batch_size: int = None, - dtype=None, device=None) -> torch.Tensor: - """Generates a latent variable for generator. - """ - if z is not None: - return z - if x is not None: - batch_size = x.shape[0] - dtype = x.dtype - device = x.device - if device is None: - device = tops.get_device() - if truncation_value == 0: - return torch.zeros((batch_size, self.z_channels), device=device, dtype=dtype) - z = torch.randn((batch_size, self.z_channels), device=device, dtype=dtype) - if truncation_value is None: - return z - while z.abs().max() > truncation_value: - m = z.abs() > truncation_value - z[m] = torch.rand_like(z)[m] - return z - - def sample(self, truncation_value, z=None, **kwargs): - """ - Samples via interpolating to the mean (0). - """ - if truncation_value is None: - return self.forward(**kwargs) - truncation_value = max(0, truncation_value) - truncation_value = min(truncation_value, 1) - if z is None: - z = self.get_z(kwargs["condition"]) - z = z * truncation_value - return self.forward(**kwargs, z=z) - - -class SG2StyleNet(torch.nn.Module): - def __init__(self, - z_dim, # Input latent (Z) dimensionality. - w_dim, # Intermediate latent (W) dimensionality. - num_layers=2, # Number of mapping layers. - lr_multiplier=0.01, # Learning rate multiplier for the mapping layers. - w_avg_beta=0.998, # Decay for tracking the moving average of W during training. - ): - super().__init__() - self.z_dim = z_dim - self.w_dim = w_dim - self.num_layers = num_layers - self.w_avg_beta = w_avg_beta - # Construct layers. - features = [self.z_dim] + [self.w_dim] * self.num_layers - for idx, in_features, out_features in zip(range(num_layers), features[:-1], features[1:]): - layer = FullyConnectedLayer(in_features, out_features, activation='lrelu', lr_multiplier=lr_multiplier) - setattr(self, f'fc{idx}', layer) - self.register_buffer('w_avg', torch.zeros([w_dim])) - - def forward(self, z, update_emas=False, **kwargs): - tops.assert_shape(z, [None, self.z_dim]) - - # Embed, normalize, and concatenate inputs. - x = z.to(torch.float32) - x = x * (x.square().mean(1, keepdim=True) + 1e-8).rsqrt() - # Execute layers. - for idx in range(self.num_layers): - x = getattr(self, f'fc{idx}')(x) - # Update moving average of W. - if update_emas: - self.w_avg.copy_(x.float().detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta)) - - return x - - def extra_repr(self): - return f'z_dim={self.z_dim:d}, w_dim={self.w_dim:d}' - - def update_w(self, n=int(10e3), batch_size=32): - """ - Calculate w_ema over n iterations. - Useful in cases where w_ema is calculated incorrectly during training. - """ - n = n // batch_size - for i in tqdm.trange(n, desc="Updating w"): - z = torch.randn((batch_size, self.z_dim), device=tops.get_device()) - self(z, update_emas=True) - - def get_truncated(self, truncation_value, condition, z=None, **kwargs): - if z is None: - z = torch.randn((condition.shape[0], self.z_dim), device=tops.get_device()) - w = self(z) - truncation_value = max(0, truncation_value) - truncation_value = min(truncation_value, 1) - return self.w_avg.to(w.dtype).lerp(w, truncation_value) - - def multi_modal_truncate(self, truncation_value, condition, w_indices, z=None, **kwargs): - truncation_value = max(0, truncation_value) - truncation_value = min(truncation_value, 1) - if z is None: - z = torch.randn((condition.shape[0], self.z_dim), device=tops.get_device()) - w = self(z) - if w_indices is None: - w_indices = np.random.randint(0, len(self.w_centers), size=(len(w))) - w_centers = self.w_centers[w_indices].to(w.device) - w = w_centers.to(w.dtype).lerp(w, truncation_value) - return w - -class BaseStyleGAN(BaseGenerator): - - def __init__(self, z_channels: int, w_dim: int): - super().__init__(z_channels) - self.style_net = SG2StyleNet(z_channels, w_dim) - self.latent_space = "W" - - def get_w(self, z, update_emas): - return self.style_net(z, update_emas=update_emas) - - @torch.no_grad() - def sample(self, truncation_value, **kwargs): - if truncation_value is None: - return self.forward(**kwargs) - w = self.style_net.get_truncated(truncation_value, **kwargs) - return self.forward(**kwargs, w=w) - - def update_w(self, *args, **kwargs): - self.style_net.update_w(*args, **kwargs) - - @torch.no_grad() - def multi_modal_truncate(self, truncation_value, w_indices=None, **kwargs): - w = self.style_net.multi_modal_truncate(truncation_value, w_indices=w_indices, **kwargs) - return self.forward(**kwargs, w=w) diff --git a/spaces/hca97/Mosquito-Detection/my_models/torch_hub_cache/yolov5/val.py b/spaces/hca97/Mosquito-Detection/my_models/torch_hub_cache/yolov5/val.py deleted file mode 100644 index 8da3ef7667aaeaa3519594f043c127007354fe06..0000000000000000000000000000000000000000 --- a/spaces/hca97/Mosquito-Detection/my_models/torch_hub_cache/yolov5/val.py +++ /dev/null @@ -1,411 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license -""" -Validate a trained YOLOv5 detection model on a detection dataset - -Usage: - $ python val.py --weights yolov5s.pt --data coco128.yaml --img 640 - -Usage - formats: - $ python val.py --weights yolov5s.pt # PyTorch - yolov5s.torchscript # TorchScript - yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn - yolov5s_openvino_model # OpenVINO - yolov5s.engine # TensorRT - yolov5s.mlmodel # CoreML (macOS-only) - yolov5s_saved_model # TensorFlow SavedModel - yolov5s.pb # TensorFlow GraphDef - yolov5s.tflite # TensorFlow Lite - yolov5s_edgetpu.tflite # TensorFlow Edge TPU - yolov5s_paddle_model # PaddlePaddle -""" - -import argparse -import json -import os -import subprocess -import sys -from pathlib import Path - -import numpy as np -import torch -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 - -from models.common import DetectMultiBackend -from utils.callbacks import Callbacks -from utils.dataloaders import create_dataloader -from utils.general import (LOGGER, TQDM_BAR_FORMAT, Profile, check_dataset, check_img_size, check_requirements, - check_yaml, coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, - print_args, scale_boxes, xywh2xyxy, xyxy2xywh) -from utils.metrics import ConfusionMatrix, ap_per_class, box_iou -from utils.plots import output_to_target, plot_images, plot_val_study -from utils.torch_utils import select_device, smart_inference_mode - - -def save_one_txt(predn, save_conf, shape, file): - # Save one txt result - gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh - for *xyxy, conf, cls in predn.tolist(): - xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh - line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format - with open(file, 'a') as f: - f.write(('%g ' * len(line)).rstrip() % line + '\n') - - -def save_one_json(predn, jdict, path, class_map): - # Save one JSON result {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236} - image_id = int(path.stem) if path.stem.isnumeric() else path.stem - box = xyxy2xywh(predn[:, :4]) # xywh - box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner - for p, b in zip(predn.tolist(), box.tolist()): - jdict.append({ - 'image_id': image_id, - 'category_id': class_map[int(p[5])], - 'bbox': [round(x, 3) for x in b], - 'score': round(p[4], 5)}) - - -def process_batch(detections, labels, iouv): - """ - Return correct prediction matrix - Arguments: - detections (array[N, 6]), x1, y1, x2, y2, conf, class - labels (array[M, 5]), class, x1, y1, x2, y2 - Returns: - correct (array[N, 10]), for 10 IoU levels - """ - correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool) - iou = box_iou(labels[:, 1:], detections[:, :4]) - correct_class = labels[:, 0:1] == detections[:, 5] - for i in range(len(iouv)): - x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match - if x[0].shape[0]: - matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou] - if x[0].shape[0] > 1: - matches = matches[matches[:, 2].argsort()[::-1]] - matches = matches[np.unique(matches[:, 1], return_index=True)[1]] - # matches = matches[matches[:, 2].argsort()[::-1]] - matches = matches[np.unique(matches[:, 0], return_index=True)[1]] - correct[matches[:, 1].astype(int), i] = True - return torch.tensor(correct, dtype=torch.bool, device=iouv.device) - - -@smart_inference_mode() -def run( - data, - weights=None, # model.pt path(s) - batch_size=32, # batch size - imgsz=640, # inference size (pixels) - conf_thres=0.001, # confidence threshold - iou_thres=0.6, # NMS IoU threshold - max_det=300, # maximum detections per image - task='val', # train, val, test, speed or study - device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu - workers=8, # max dataloader workers (per RANK in DDP mode) - single_cls=False, # treat as single-class dataset - augment=False, # augmented inference - verbose=False, # verbose output - save_txt=False, # save results to *.txt - save_hybrid=False, # save label+prediction hybrid results to *.txt - save_conf=False, # save confidences in --save-txt labels - save_json=False, # save a COCO-JSON results file - project=ROOT / 'runs/val', # save to project/name - name='exp', # save to project/name - exist_ok=False, # existing project/name ok, do not increment - half=True, # use FP16 half-precision inference - dnn=False, # use OpenCV DNN for ONNX inference - model=None, - dataloader=None, - save_dir=Path(''), - plots=True, - callbacks=Callbacks(), - compute_loss=None, -): - # Initialize/load model and set device - training = model is not None - if training: # called by train.py - device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model - half &= device.type != 'cpu' # half precision only supported on CUDA - model.half() if half else model.float() - else: # called directly - device = select_device(device, batch_size=batch_size) - - # Directories - save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run - (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir - - # Load model - model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) - stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine - imgsz = check_img_size(imgsz, s=stride) # check image size - half = model.fp16 # FP16 supported on limited backends with CUDA - if engine: - batch_size = model.batch_size - else: - device = model.device - if not (pt or jit): - batch_size = 1 # export.py models default to batch-size 1 - LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models') - - # Data - data = check_dataset(data) # check - - # Configure - model.eval() - cuda = device.type != 'cpu' - is_coco = isinstance(data.get('val'), str) and data['val'].endswith(f'coco{os.sep}val2017.txt') # COCO dataset - nc = 1 if single_cls else int(data['nc']) # number of classes - iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for mAP@0.5:0.95 - niou = iouv.numel() - - # Dataloader - if not training: - if pt and not single_cls: # check --weights are trained on --data - ncm = model.model.nc - assert ncm == nc, f'{weights} ({ncm} classes) trained on different --data than what you passed ({nc} ' \ - f'classes). Pass correct combination of --weights and --data that are trained together.' - model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup - pad, rect = (0.0, False) if task == 'speed' else (0.5, pt) # square inference for benchmarks - task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images - dataloader = create_dataloader(data[task], - imgsz, - batch_size, - stride, - single_cls, - pad=pad, - rect=rect, - workers=workers, - prefix=colorstr(f'{task}: '))[0] - - seen = 0 - confusion_matrix = ConfusionMatrix(nc=nc) - names = model.names if hasattr(model, 'names') else model.module.names # get class names - if isinstance(names, (list, tuple)): # old format - names = dict(enumerate(names)) - class_map = coco80_to_coco91_class() if is_coco else list(range(1000)) - s = ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'P', 'R', 'mAP50', 'mAP50-95') - tp, fp, p, r, f1, mp, mr, map50, ap50, map = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 - dt = Profile(), Profile(), Profile() # profiling times - loss = torch.zeros(3, device=device) - jdict, stats, ap, ap_class = [], [], [], [] - callbacks.run('on_val_start') - pbar = tqdm(dataloader, desc=s, bar_format=TQDM_BAR_FORMAT) # progress bar - for batch_i, (im, targets, paths, shapes) in enumerate(pbar): - callbacks.run('on_val_batch_start') - with dt[0]: - if cuda: - im = im.to(device, non_blocking=True) - targets = targets.to(device) - im = im.half() if half else im.float() # uint8 to fp16/32 - im /= 255 # 0 - 255 to 0.0 - 1.0 - nb, _, height, width = im.shape # batch size, channels, height, width - - # Inference - with dt[1]: - preds, train_out = model(im) if compute_loss else (model(im, augment=augment), None) - - # Loss - if compute_loss: - loss += compute_loss(train_out, targets)[1] # box, obj, cls - - # NMS - targets[:, 2:] *= torch.tensor((width, height, width, height), device=device) # to pixels - lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling - with dt[2]: - preds = non_max_suppression(preds, - conf_thres, - iou_thres, - labels=lb, - multi_label=True, - agnostic=single_cls, - max_det=max_det) - - # Metrics - for si, pred in enumerate(preds): - labels = targets[targets[:, 0] == si, 1:] - nl, npr = labels.shape[0], pred.shape[0] # number of labels, predictions - path, shape = Path(paths[si]), shapes[si][0] - correct = torch.zeros(npr, niou, dtype=torch.bool, device=device) # init - seen += 1 - - if npr == 0: - if nl: - stats.append((correct, *torch.zeros((2, 0), device=device), labels[:, 0])) - if plots: - confusion_matrix.process_batch(detections=None, labels=labels[:, 0]) - continue - - # Predictions - if single_cls: - pred[:, 5] = 0 - predn = pred.clone() - scale_boxes(im[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred - - # Evaluate - if nl: - tbox = xywh2xyxy(labels[:, 1:5]) # target boxes - scale_boxes(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels - labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels - correct = process_batch(predn, labelsn, iouv) - if plots: - confusion_matrix.process_batch(predn, labelsn) - stats.append((correct, pred[:, 4], pred[:, 5], labels[:, 0])) # (correct, conf, pcls, tcls) - - # Save/log - if save_txt: - save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt') - if save_json: - save_one_json(predn, jdict, path, class_map) # append to COCO-JSON dictionary - callbacks.run('on_val_image_end', pred, predn, path, names, im[si]) - - # Plot images - if plots and batch_i < 3: - plot_images(im, targets, paths, save_dir / f'val_batch{batch_i}_labels.jpg', names) # labels - plot_images(im, output_to_target(preds), paths, save_dir / f'val_batch{batch_i}_pred.jpg', names) # pred - - callbacks.run('on_val_batch_end', batch_i, im, targets, paths, shapes, preds) - - # Compute metrics - stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)] # to numpy - if len(stats) and stats[0].any(): - tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names) - ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95 - mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean() - nt = np.bincount(stats[3].astype(int), minlength=nc) # number of targets per class - - # Print results - pf = '%22s' + '%11i' * 2 + '%11.3g' * 4 # print format - LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map)) - if nt.sum() == 0: - LOGGER.warning(f'WARNING ⚠️ no labels found in {task} set, can not compute metrics without labels') - - # Print results per class - if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats): - for i, c in enumerate(ap_class): - LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i])) - - # Print speeds - t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image - if not training: - shape = (batch_size, 3, imgsz, imgsz) - LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t) - - # Plots - if plots: - confusion_matrix.plot(save_dir=save_dir, names=list(names.values())) - callbacks.run('on_val_end', nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix) - - # Save JSON - if save_json and len(jdict): - w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights - anno_json = str(Path('../datasets/coco/annotations/instances_val2017.json')) # annotations - if not os.path.exists(anno_json): - anno_json = os.path.join(data['path'], 'annotations', 'instances_val2017.json') - pred_json = str(save_dir / f'{w}_predictions.json') # predictions - LOGGER.info(f'\nEvaluating pycocotools mAP... saving {pred_json}...') - with open(pred_json, 'w') as f: - json.dump(jdict, f) - - try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb - check_requirements('pycocotools>=2.0.6') - from pycocotools.coco import COCO - from pycocotools.cocoeval import COCOeval - - anno = COCO(anno_json) # init annotations api - pred = anno.loadRes(pred_json) # init predictions api - eval = COCOeval(anno, pred, 'bbox') - if is_coco: - eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.im_files] # image IDs to evaluate - eval.evaluate() - eval.accumulate() - eval.summarize() - map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5) - except Exception as e: - LOGGER.info(f'pycocotools unable to run: {e}') - - # Return results - model.float() # for training - if not training: - s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' - LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}") - maps = np.zeros(nc) + map - for i, c in enumerate(ap_class): - maps[c] = ap[i] - return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t - - -def parse_opt(): - parser = argparse.ArgumentParser() - parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path') - parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)') - parser.add_argument('--batch-size', type=int, default=32, help='batch size') - parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') - parser.add_argument('--conf-thres', type=float, default=0.001, help='confidence threshold') - parser.add_argument('--iou-thres', type=float, default=0.6, help='NMS IoU threshold') - parser.add_argument('--max-det', type=int, default=300, help='maximum detections per image') - parser.add_argument('--task', default='val', help='train, val, test, speed or study') - parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') - parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)') - parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') - parser.add_argument('--augment', action='store_true', help='augmented inference') - parser.add_argument('--verbose', action='store_true', help='report mAP by class') - parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') - parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt') - parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') - parser.add_argument('--save-json', action='store_true', help='save a COCO-JSON results file') - parser.add_argument('--project', default=ROOT / 'runs/val', 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('--half', action='store_true', help='use FP16 half-precision inference') - parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference') - opt = parser.parse_args() - opt.data = check_yaml(opt.data) # check YAML - opt.save_json |= opt.data.endswith('coco.yaml') - opt.save_txt |= opt.save_hybrid - print_args(vars(opt)) - return opt - - -def main(opt): - check_requirements(ROOT / 'requirements.txt', exclude=('tensorboard', 'thop')) - - if opt.task in ('train', 'val', 'test'): # run normally - if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466 - LOGGER.info(f'WARNING ⚠️ confidence threshold {opt.conf_thres} > 0.001 produces invalid results') - if opt.save_hybrid: - LOGGER.info('WARNING ⚠️ --save-hybrid will return high mAP from hybrid labels, not from predictions alone') - run(**vars(opt)) - - else: - weights = opt.weights if isinstance(opt.weights, list) else [opt.weights] - opt.half = torch.cuda.is_available() and opt.device != 'cpu' # FP16 for fastest results - if opt.task == 'speed': # speed benchmarks - # python val.py --task speed --data coco.yaml --batch 1 --weights yolov5n.pt yolov5s.pt... - opt.conf_thres, opt.iou_thres, opt.save_json = 0.25, 0.45, False - for opt.weights in weights: - run(**vars(opt), plots=False) - - elif opt.task == 'study': # speed vs mAP benchmarks - # python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n.pt yolov5s.pt... - for opt.weights in weights: - f = f'study_{Path(opt.data).stem}_{Path(opt.weights).stem}.txt' # filename to save to - x, y = list(range(256, 1536 + 128, 128)), [] # x axis (image sizes), y axis - for opt.imgsz in x: # img-size - LOGGER.info(f'\nRunning {f} --imgsz {opt.imgsz}...') - r, _, t = run(**vars(opt), plots=False) - y.append(r + t) # results and times - np.savetxt(f, y, fmt='%10.4g') # save - subprocess.run(['zip', '-r', 'study.zip', 'study_*.txt']) - plot_val_study(x=x) # plot - else: - raise NotImplementedError(f'--task {opt.task} not in ("train", "val", "test", "speed", "study")') - - -if __name__ == '__main__': - opt = parse_opt() - main(opt) diff --git a/spaces/heiyubili/bingo/Dockerfile b/spaces/heiyubili/bingo/Dockerfile deleted file mode 100644 index 3aa2b29b5fc4fa8b8238955acd7f1fde13ce5e1a..0000000000000000000000000000000000000000 --- a/spaces/heiyubili/bingo/Dockerfile +++ /dev/null @@ -1,36 +0,0 @@ -FROM node:18 - - -ARG DEBIAN_FRONTEND=noninteractive - -ENV BING_HEADER "" - -# Set home to the user's home directory -ENV HOME=/home/user \ - PATH=/home/user/.local/bin:$PATH - -# Set up a new user named "user" with user ID 1000 -RUN useradd -o -u 1000 user && mkdir -p $HOME/app && chown -R user $HOME - -# Switch to the "user" user -USER user - -# Set the working directory to the user's home directory -WORKDIR $HOME/app - -# Install app dependencies -# A wildcard is used to ensure both package.json AND package-lock.json are copied -# where available (npm@5+) -COPY --chown=user package*.json $HOME/app/ - -RUN npm install - -# Copy the current directory contents into the container at $HOME/app setting the owner to the user -COPY --chown=user . $HOME/app/ - -RUN npm run build - -ENV PORT 7860 -EXPOSE 7860 - -CMD npm start diff --git a/spaces/housexu123/bingo-2.0/src/components/header.tsx b/spaces/housexu123/bingo-2.0/src/components/header.tsx deleted file mode 100644 index dc298b722154d1ac6d7a7e148204605562d6cc58..0000000000000000000000000000000000000000 --- a/spaces/housexu123/bingo-2.0/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/huggingface-tools/text-to-video/__init__.py b/spaces/huggingface-tools/text-to-video/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/huggingface/Model_Cards_Writing_Tool/combined.md b/spaces/huggingface/Model_Cards_Writing_Tool/combined.md deleted file mode 100644 index 900d1889e4b08f4dfe56ffbe9704f107807141ff..0000000000000000000000000000000000000000 --- a/spaces/huggingface/Model_Cards_Writing_Tool/combined.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -language: -- es -license: apache-2.0 -library_name: keras -tags: -- autogenerated-modelcard ---- - -# MyModelName - -## Table of Contents -- [MyModelName](#-model_id--defaultmymodelname-true) - - [Table of Contents](#table-of-contents) - - [Model Details](#model-details) - - [How to Get Started with the Model](#how-to-get-started-with-the-model) - - [Uses](#uses) - - [Direct Use](#direct-use) - - [Downstream Use](#downstream-use) - - [Misuse and Out-of-scope Use](#misuse-and-out-of-scope-use) - - [Limitations and Biases](#limitations-and-biases) - - [Training](#training) - - [Training Data](#training-data) - - [Training Procedure](#training-procedure) - - [Evaluation Results](#evaluation-results) - - [Environmental Impact](#environmental-impact) - - [Citation Information](#citation-information) - - - -## Model Details - - - -Some cool model... - -- Developed by: -- Language(s): -- License: This model is licensed under the apache-2.0 license -- Resources for more information: - - - - - - -## How to Get Started with the Model - -Use the code below to get started with the model. - -```python -# A nice code snippet here that describes how to use the model... -``` - - - - -## Uses - -#### Direct Use - - - -[More Information Needed] - -#### Downstream Use - - - -[More Information Needed] - -#### Misuse and Out-of-scope Use - - - -[More Information Needed] - - - - -## Limitations and Biases - - - -**CONTENT WARNING: Readers should be aware this section contains content that is disturbing, offensive, and can propogate historical and current stereotypes.** - -[More Information Needed] - - - - - -## Training - -#### Training Data - - - - -See the data card for additional information. - -#### Training Procedure - - - -[More Information Needed] - - - - -## Evaluation Results - - - -[More Information Needed] - - - - -## Environmental Impact - - - -You can estimate carbon emissions using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700) - -- **Hardware Type:** -- **Hours used:** -- **Cloud Provider:** -- **Compute Region:** -- **Carbon Emitted:** - - - - - -## Citation Information - -```bibtex - -``` - \ No newline at end of file diff --git a/spaces/hysts/TADNE-image-viewer/README.md b/spaces/hysts/TADNE-image-viewer/README.md deleted file mode 100644 index 4e11ce1020bd00ff6a28915bb3632246e4f3928e..0000000000000000000000000000000000000000 --- a/spaces/hysts/TADNE-image-viewer/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: TADNE Image Viewer -emoji: 🚀 -colorFrom: red -colorTo: gray -sdk: gradio -sdk_version: 3.0.5 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/hyxue/HiFiFace-inference-demo/Deep3DFaceRecon_pytorch/models/arcface_torch/eval/verification.py b/spaces/hyxue/HiFiFace-inference-demo/Deep3DFaceRecon_pytorch/models/arcface_torch/eval/verification.py deleted file mode 100644 index bd8c7d08c5e671a55e4d03c0d9714d60e7f059d1..0000000000000000000000000000000000000000 --- a/spaces/hyxue/HiFiFace-inference-demo/Deep3DFaceRecon_pytorch/models/arcface_torch/eval/verification.py +++ /dev/null @@ -1,378 +0,0 @@ -"""Helper for evaluation on the Labeled Faces in the Wild dataset -""" -# MIT License -# -# Copyright (c) 2016 David Sandberg -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -import datetime -import os -import pickle - -import mxnet as mx -import numpy as np -import sklearn -import torch -from mxnet import ndarray as nd -from scipy import interpolate -from sklearn.decomposition import PCA -from sklearn.model_selection import KFold - - -class LFold: - def __init__(self, n_splits=2, shuffle=False): - self.n_splits = n_splits - if self.n_splits > 1: - self.k_fold = KFold(n_splits=n_splits, shuffle=shuffle) - - def split(self, indices): - if self.n_splits > 1: - return self.k_fold.split(indices) - else: - return [(indices, indices)] - - -def calculate_roc(thresholds, embeddings1, embeddings2, actual_issame, nrof_folds=10, pca=0): - assert embeddings1.shape[0] == embeddings2.shape[0] - assert embeddings1.shape[1] == embeddings2.shape[1] - nrof_pairs = min(len(actual_issame), embeddings1.shape[0]) - nrof_thresholds = len(thresholds) - k_fold = LFold(n_splits=nrof_folds, shuffle=False) - - tprs = np.zeros((nrof_folds, nrof_thresholds)) - fprs = np.zeros((nrof_folds, nrof_thresholds)) - accuracy = np.zeros((nrof_folds)) - indices = np.arange(nrof_pairs) - - if pca == 0: - diff = np.subtract(embeddings1, embeddings2) - dist = np.sum(np.square(diff), 1) - - for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)): - if pca > 0: - print("doing pca on", fold_idx) - embed1_train = embeddings1[train_set] - embed2_train = embeddings2[train_set] - _embed_train = np.concatenate((embed1_train, embed2_train), axis=0) - pca_model = PCA(n_components=pca) - pca_model.fit(_embed_train) - embed1 = pca_model.transform(embeddings1) - embed2 = pca_model.transform(embeddings2) - embed1 = sklearn.preprocessing.normalize(embed1) - embed2 = sklearn.preprocessing.normalize(embed2) - diff = np.subtract(embed1, embed2) - dist = np.sum(np.square(diff), 1) - - # Find the best threshold for the fold - acc_train = np.zeros((nrof_thresholds)) - for threshold_idx, threshold in enumerate(thresholds): - _, _, acc_train[threshold_idx] = calculate_accuracy(threshold, dist[train_set], actual_issame[train_set]) - best_threshold_index = np.argmax(acc_train) - for threshold_idx, threshold in enumerate(thresholds): - tprs[fold_idx, threshold_idx], fprs[fold_idx, threshold_idx], _ = calculate_accuracy( - threshold, dist[test_set], actual_issame[test_set] - ) - _, _, accuracy[fold_idx] = calculate_accuracy( - thresholds[best_threshold_index], dist[test_set], actual_issame[test_set] - ) - - tpr = np.mean(tprs, 0) - fpr = np.mean(fprs, 0) - return tpr, fpr, accuracy - - -def calculate_accuracy(threshold, dist, actual_issame): - predict_issame = np.less(dist, threshold) - tp = np.sum(np.logical_and(predict_issame, actual_issame)) - fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame))) - tn = np.sum(np.logical_and(np.logical_not(predict_issame), np.logical_not(actual_issame))) - fn = np.sum(np.logical_and(np.logical_not(predict_issame), actual_issame)) - - tpr = 0 if (tp + fn == 0) else float(tp) / float(tp + fn) - fpr = 0 if (fp + tn == 0) else float(fp) / float(fp + tn) - acc = float(tp + tn) / dist.size - return tpr, fpr, acc - - -def calculate_val(thresholds, embeddings1, embeddings2, actual_issame, far_target, nrof_folds=10): - assert embeddings1.shape[0] == embeddings2.shape[0] - assert embeddings1.shape[1] == embeddings2.shape[1] - nrof_pairs = min(len(actual_issame), embeddings1.shape[0]) - nrof_thresholds = len(thresholds) - k_fold = LFold(n_splits=nrof_folds, shuffle=False) - - val = np.zeros(nrof_folds) - far = np.zeros(nrof_folds) - - diff = np.subtract(embeddings1, embeddings2) - dist = np.sum(np.square(diff), 1) - indices = np.arange(nrof_pairs) - - for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)): - - # Find the threshold that gives FAR = far_target - far_train = np.zeros(nrof_thresholds) - for threshold_idx, threshold in enumerate(thresholds): - _, far_train[threshold_idx] = calculate_val_far(threshold, dist[train_set], actual_issame[train_set]) - if np.max(far_train) >= far_target: - f = interpolate.interp1d(far_train, thresholds, kind="slinear") - threshold = f(far_target) - else: - threshold = 0.0 - - val[fold_idx], far[fold_idx] = calculate_val_far(threshold, dist[test_set], actual_issame[test_set]) - - val_mean = np.mean(val) - far_mean = np.mean(far) - val_std = np.std(val) - return val_mean, val_std, far_mean - - -def calculate_val_far(threshold, dist, actual_issame): - predict_issame = np.less(dist, threshold) - true_accept = np.sum(np.logical_and(predict_issame, actual_issame)) - false_accept = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame))) - n_same = np.sum(actual_issame) - n_diff = np.sum(np.logical_not(actual_issame)) - # print(true_accept, false_accept) - # print(n_same, n_diff) - val = float(true_accept) / float(n_same) - far = float(false_accept) / float(n_diff) - return val, far - - -def evaluate(embeddings, actual_issame, nrof_folds=10, pca=0): - # Calculate evaluation metrics - thresholds = np.arange(0, 4, 0.01) - embeddings1 = embeddings[0::2] - embeddings2 = embeddings[1::2] - tpr, fpr, accuracy = calculate_roc( - thresholds, embeddings1, embeddings2, np.asarray(actual_issame), nrof_folds=nrof_folds, pca=pca - ) - thresholds = np.arange(0, 4, 0.001) - val, val_std, far = calculate_val( - thresholds, embeddings1, embeddings2, np.asarray(actual_issame), 1e-3, nrof_folds=nrof_folds - ) - return tpr, fpr, accuracy, val, val_std, far - - -@torch.no_grad() -def load_bin(path, image_size): - try: - with open(path, "rb") as f: - bins, issame_list = pickle.load(f) # py2 - except UnicodeDecodeError as e: - with open(path, "rb") as f: - bins, issame_list = pickle.load(f, encoding="bytes") # py3 - data_list = [] - for flip in [0, 1]: - data = torch.empty((len(issame_list) * 2, 3, image_size[0], image_size[1])) - data_list.append(data) - for idx in range(len(issame_list) * 2): - _bin = bins[idx] - img = mx.image.imdecode(_bin) - if img.shape[1] != image_size[0]: - img = mx.image.resize_short(img, image_size[0]) - img = nd.transpose(img, axes=(2, 0, 1)) - for flip in [0, 1]: - if flip == 1: - img = mx.ndarray.flip(data=img, axis=2) - data_list[flip][idx][:] = torch.from_numpy(img.asnumpy()) - if idx % 1000 == 0: - print("loading bin", idx) - print(data_list[0].shape) - return data_list, issame_list - - -@torch.no_grad() -def test(data_set, backbone, batch_size, nfolds=10): - print("testing verification..") - data_list = data_set[0] - issame_list = data_set[1] - embeddings_list = [] - time_consumed = 0.0 - for i in range(len(data_list)): - data = data_list[i] - embeddings = None - ba = 0 - while ba < data.shape[0]: - bb = min(ba + batch_size, data.shape[0]) - count = bb - ba - _data = data[bb - batch_size : bb] - time0 = datetime.datetime.now() - img = ((_data / 255) - 0.5) / 0.5 - net_out: torch.Tensor = backbone(img) - _embeddings = net_out.detach().cpu().numpy() - time_now = datetime.datetime.now() - diff = time_now - time0 - time_consumed += diff.total_seconds() - if embeddings is None: - embeddings = np.zeros((data.shape[0], _embeddings.shape[1])) - embeddings[ba:bb, :] = _embeddings[(batch_size - count) :, :] - ba = bb - embeddings_list.append(embeddings) - - _xnorm = 0.0 - _xnorm_cnt = 0 - for embed in embeddings_list: - for i in range(embed.shape[0]): - _em = embed[i] - _norm = np.linalg.norm(_em) - _xnorm += _norm - _xnorm_cnt += 1 - _xnorm /= _xnorm_cnt - - embeddings = embeddings_list[0].copy() - embeddings = sklearn.preprocessing.normalize(embeddings) - acc1 = 0.0 - std1 = 0.0 - embeddings = embeddings_list[0] + embeddings_list[1] - embeddings = sklearn.preprocessing.normalize(embeddings) - print(embeddings.shape) - print("infer time", time_consumed) - _, _, accuracy, val, val_std, far = evaluate(embeddings, issame_list, nrof_folds=nfolds) - acc2, std2 = np.mean(accuracy), np.std(accuracy) - return acc1, std1, acc2, std2, _xnorm, embeddings_list - - -def dumpR(data_set, backbone, batch_size, name="", data_extra=None, label_shape=None): - print("dump verification embedding..") - data_list = data_set[0] - issame_list = data_set[1] - embeddings_list = [] - time_consumed = 0.0 - for i in range(len(data_list)): - data = data_list[i] - embeddings = None - ba = 0 - while ba < data.shape[0]: - bb = min(ba + batch_size, data.shape[0]) - count = bb - ba - - _data = nd.slice_axis(data, axis=0, begin=bb - batch_size, end=bb) - time0 = datetime.datetime.now() - if data_extra is None: - db = mx.io.DataBatch(data=(_data,), label=(_label,)) - else: - db = mx.io.DataBatch(data=(_data, _data_extra), label=(_label,)) - model.forward(db, is_train=False) - net_out = model.get_outputs() - _embeddings = net_out[0].asnumpy() - time_now = datetime.datetime.now() - diff = time_now - time0 - time_consumed += diff.total_seconds() - if embeddings is None: - embeddings = np.zeros((data.shape[0], _embeddings.shape[1])) - embeddings[ba:bb, :] = _embeddings[(batch_size - count) :, :] - ba = bb - embeddings_list.append(embeddings) - embeddings = embeddings_list[0] + embeddings_list[1] - embeddings = sklearn.preprocessing.normalize(embeddings) - actual_issame = np.asarray(issame_list) - outname = os.path.join("temp.bin") - with open(outname, "wb") as f: - pickle.dump((embeddings, issame_list), f, protocol=pickle.HIGHEST_PROTOCOL) - - -# if __name__ == '__main__': -# -# parser = argparse.ArgumentParser(description='do verification') -# # general -# parser.add_argument('--data-dir', default='', help='') -# parser.add_argument('--model', -# default='../model/softmax,50', -# help='path to load model.') -# parser.add_argument('--target', -# default='lfw,cfp_ff,cfp_fp,agedb_30', -# help='test targets.') -# parser.add_argument('--gpu', default=0, type=int, help='gpu id') -# parser.add_argument('--batch-size', default=32, type=int, help='') -# parser.add_argument('--max', default='', type=str, help='') -# parser.add_argument('--mode', default=0, type=int, help='') -# parser.add_argument('--nfolds', default=10, type=int, help='') -# args = parser.parse_args() -# image_size = [112, 112] -# print('image_size', image_size) -# ctx = mx.gpu(args.gpu) -# nets = [] -# vec = args.model.split(',') -# prefix = args.model.split(',')[0] -# epochs = [] -# if len(vec) == 1: -# pdir = os.path.dirname(prefix) -# for fname in os.listdir(pdir): -# if not fname.endswith('.params'): -# continue -# _file = os.path.join(pdir, fname) -# if _file.startswith(prefix): -# epoch = int(fname.split('.')[0].split('-')[1]) -# epochs.append(epoch) -# epochs = sorted(epochs, reverse=True) -# if len(args.max) > 0: -# _max = [int(x) for x in args.max.split(',')] -# assert len(_max) == 2 -# if len(epochs) > _max[1]: -# epochs = epochs[_max[0]:_max[1]] -# -# else: -# epochs = [int(x) for x in vec[1].split('|')] -# print('model number', len(epochs)) -# time0 = datetime.datetime.now() -# for epoch in epochs: -# print('loading', prefix, epoch) -# sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) -# # arg_params, aux_params = ch_dev(arg_params, aux_params, ctx) -# all_layers = sym.get_internals() -# sym = all_layers['fc1_output'] -# model = mx.mod.Module(symbol=sym, context=ctx, label_names=None) -# # model.bind(data_shapes=[('data', (args.batch_size, 3, image_size[0], image_size[1]))], label_shapes=[('softmax_label', (args.batch_size,))]) -# model.bind(data_shapes=[('data', (args.batch_size, 3, image_size[0], -# image_size[1]))]) -# model.set_params(arg_params, aux_params) -# nets.append(model) -# time_now = datetime.datetime.now() -# diff = time_now - time0 -# print('model loading time', diff.total_seconds()) -# -# ver_list = [] -# ver_name_list = [] -# for name in args.target.split(','): -# path = os.path.join(args.data_dir, name + ".bin") -# if os.path.exists(path): -# print('loading.. ', name) -# data_set = load_bin(path, image_size) -# ver_list.append(data_set) -# ver_name_list.append(name) -# -# if args.mode == 0: -# for i in range(len(ver_list)): -# results = [] -# for model in nets: -# acc1, std1, acc2, std2, xnorm, embeddings_list = test( -# ver_list[i], model, args.batch_size, args.nfolds) -# print('[%s]XNorm: %f' % (ver_name_list[i], xnorm)) -# print('[%s]Accuracy: %1.5f+-%1.5f' % (ver_name_list[i], acc1, std1)) -# print('[%s]Accuracy-Flip: %1.5f+-%1.5f' % (ver_name_list[i], acc2, std2)) -# results.append(acc2) -# print('Max of [%s] is %1.5f' % (ver_name_list[i], np.max(results))) -# elif args.mode == 1: -# raise ValueError -# else: -# model = nets[0] -# dumpR(ver_list[0], model, args.batch_size, args.target) diff --git a/spaces/hzrr/dal_audio_inference/models.py b/spaces/hzrr/dal_audio_inference/models.py deleted file mode 100644 index ab884c773c401bfa44ee81bdd4c90f070d523276..0000000000000000000000000000000000000000 --- a/spaces/hzrr/dal_audio_inference/models.py +++ /dev/null @@ -1,534 +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 - - -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): - 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.emb = nn.Embedding(n_vocab, hidden_channels) - nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5) - - 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, x, x_lengths): - x = self.emb(x) * 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) - 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 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=0, - gin_channels=0, - use_sdp=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.use_sdp = use_sdp - - self.enc_p = TextEncoder(n_vocab, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout) - 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, 4, gin_channels=gin_channels) - - if use_sdp: - self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels) - else: - 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) - - def forward(self, x, x_lengths, y, y_lengths, sid=None): - - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths) - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = None - - 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 - - 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) - if self.use_sdp: - l_length = self.dp(x, x_mask, w, g=g) - l_length = l_length / torch.sum(x_mask) - else: - logw_ = torch.log(w + 1e-6) * x_mask - logw = self.dp(x, x_mask, g=g) - l_length = torch.sum((logw - logw_)**2, [1,2]) / torch.sum(x_mask) # for averaging - - # 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) - - def infer(self, x, x_lengths, sid=None, noise_scale=1, length_scale=1, noise_scale_w=1., max_len=None): - x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths) - if self.n_speakers > 0: - g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1] - else: - g = None - - if self.use_sdp: - logw = self.dp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) - else: - logw = self.dp(x, x_mask, g=g) - 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) - - def voice_conversion(self, y, y_lengths, sid_src, sid_tgt): - assert self.n_speakers > 0, "n_speakers have to be larger than 0." - g_src = self.emb_g(sid_src).unsqueeze(-1) - g_tgt = self.emb_g(sid_tgt).unsqueeze(-1) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src) - z_p = self.flow(z, y_mask, g=g_src) - z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True) - o_hat = self.dec(z_hat * y_mask, g=g_tgt) - return o_hat, y_mask, (z, z_p, z_hat) - diff --git a/spaces/iloveapplesandoranges/stablediffusionapi-disney-pixal-cartoon/README.md b/spaces/iloveapplesandoranges/stablediffusionapi-disney-pixal-cartoon/README.md deleted file mode 100644 index 16aab140e851e99b72eb33974ffd9ad72eac4113..0000000000000000000000000000000000000000 --- a/spaces/iloveapplesandoranges/stablediffusionapi-disney-pixal-cartoon/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Stablediffusionapi Disney Pixal Cartoon -emoji: 🦀 -colorFrom: red -colorTo: indigo -sdk: gradio -sdk_version: 3.47.1 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/imperialwool/funapi/routes/ytApi/getFull.py b/spaces/imperialwool/funapi/routes/ytApi/getFull.py deleted file mode 100644 index 6de9e040fe3c3f6782850535920541ac19c7daec..0000000000000000000000000000000000000000 --- a/spaces/imperialwool/funapi/routes/ytApi/getFull.py +++ /dev/null @@ -1,31 +0,0 @@ -import ffmpeg -from .get import * -from .. import helpers - -def getFull(request): - answer = get(request, "full") - try: - if answer['status'] == "error": return answer - if answer['error']: return answer - except KeyError: pass - except Exception as e: return {"status": "error", "details": { "error_code": 123, "error_details": e }}, 400 - urlcode = answer['urlcode'] - bitrate = answer['bitrate'] - quality = answer['quality'] - error_code = answer['ytdlp-code'] - - extension = helpers.getFromRequest(request, "extension") - if not extension: extension = "ogg" - - config = helpers.configFile() - if answer['done-or-not']: - return {"status": "pass", "details": {"code": error_code, "name":"{}.ogg".format(urlcode), "result": f"{config['url']}/static/full/{urlcode}.ogg"}} - - try: - audio_input = ffmpeg.input(answer['path']) - audio_output = ffmpeg.output(audio_input.audio, f"{config['full-path']}/{urlcode}.{extension}", audio_bitrate=bitrate) - ffmpeg.run(audio_output) - helpers.deleteAudio(f"temp/{urlcode}.ogg") - except Exception as e: return {"status": "error", "details": {"error_code": 102, "error_details": str(e), "result": f"{config['url']}/static/temp/{urlcode}.ogg"}}, 400 - return {"status": "pass", "details": {"code": error_code, "name":"{}.ogg".format(urlcode), "result": f"{config['url']}/static/full/{urlcode}.ogg"}} - \ No newline at end of file diff --git a/spaces/innnky/soft-vits-vc/text/__init__.py b/spaces/innnky/soft-vits-vc/text/__init__.py deleted file mode 100644 index 4ac41f9025755d8ffd74068af14c6cfc8e5a4173..0000000000000000000000000000000000000000 --- a/spaces/innnky/soft-vits-vc/text/__init__.py +++ /dev/null @@ -1,54 +0,0 @@ -""" from https://github.com/keithito/tacotron """ -from text import cleaners -from text.symbols import symbols - - -# Mappings from symbol to numeric ID and vice versa: -_symbol_to_id = {s: i for i, s in enumerate(symbols)} -_id_to_symbol = {i: s for i, s in enumerate(symbols)} - - -def text_to_sequence(text, cleaner_names): - '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text. - Args: - text: string to convert to a sequence - cleaner_names: names of the cleaner functions to run the text through - Returns: - List of integers corresponding to the symbols in the text - ''' - sequence = [] - - clean_text = _clean_text(text, cleaner_names) - for symbol in clean_text: - symbol_id = _symbol_to_id[symbol] - sequence += [symbol_id] - return sequence - - -def cleaned_text_to_sequence(cleaned_text): - '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text. - Args: - text: string to convert to a sequence - Returns: - List of integers corresponding to the symbols in the text - ''' - sequence = [_symbol_to_id[symbol] for symbol in cleaned_text] - return sequence - - -def sequence_to_text(sequence): - '''Converts a sequence of IDs back to a string''' - result = '' - for symbol_id in sequence: - s = _id_to_symbol[symbol_id] - result += s - return result - - -def _clean_text(text, cleaner_names): - for name in cleaner_names: - cleaner = getattr(cleaners, name) - if not cleaner: - raise Exception('Unknown cleaner: %s' % name) - text = cleaner(text) - return text diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/A Reaper At The Gates An Ember In The Ashes Downloads Torrent.md b/spaces/inplisQlawa/anything-midjourney-v4-1/A Reaper At The Gates An Ember In The Ashes Downloads Torrent.md deleted file mode 100644 index 0d4e8b73c36a181a97fc347a961b617432d1b3c2..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/A Reaper At The Gates An Ember In The Ashes Downloads Torrent.md +++ /dev/null @@ -1,42 +0,0 @@ -

    A Reaper At The Gates An Ember In The Ashes Downloads Torrent


    Download Ziphttps://urlin.us/2uEwZc



    - -Aquilla and her sister, Aira, run away from the family home to protect the others from the authorities. Their older sister, Livia, and Aira's sweetheart, Cordus, decide to join them. But Aira has made enemies and must deal with the past. - -Norta, Aira's friend and Cordus's ex-girlfriend, can be treacherous when she feels threatened. She knows the Blood Shrikes are nothing to be trusted. - -Aquilla has friends who work at the Imperial palace. They want to help—but how far will they go to do it? - -Download and start listening now! - -BK_CRE_000101 - -Quotes & Awards - -“Sabrina Hennick makes a powerful debut in The Blood Shrike, a brilliantly conceived and memorably plotted story of a girl fighting for her family.” - -– Claudia Gray, author of The Iron King and The King’s Assassin - -“Sabrina Hennick has crafted a rich, complex novel, equal parts history and fairy tale, that has enough twists and turns to keep even the most jaded reader guessing. I had to make several fast-forwarding trips through the book to see what happened to the characters and to not miss a single detail.” - -– Dana L. Gilbert, author of Midnight Star - -“The Blood Shrike is a great debut, a thoroughly satisfying novel with a hauntingly beautiful world and characters you’ll never forget.” - -– Trudi Canavan, author of The Blood Road and Daughter of Fortune - -“Hennick’s debut fantasy is beautifully written, brimming with intrigue, twists, and characters you’ll find yourself rooting for, even when they make the worst decisions you’ve seen in a book in a while.” - -– Michael R. Fletcher, author of Sorrow for the Crimson Skies - -“The Blood Shrike has it all—intricate plotting, masterfully-developed characters, and adventure to boot. A wonderful debut!” - -– Paula Block, author of The Orphan Queen - -“Sabrina Hennick’s debut novel, The Blood Shrike, is a captivating historical fantasy that reads like a mystery with a fabulous set of characters.” - -– Samantha Young, author of The Apprentice’s Tale - -� 4fefd39f24
    -
    -
    -

    diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Call Of Duty Modern Warfare 3 Full Multiplayer SP nosTEAMCall Of Duty Modern Warfare 3 Full Mu.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Call Of Duty Modern Warfare 3 Full Multiplayer SP nosTEAMCall Of Duty Modern Warfare 3 Full Mu.md deleted file mode 100644 index 5f228191f3cd6e19cce572aabed48d19170ade49..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Call Of Duty Modern Warfare 3 Full Multiplayer SP nosTEAMCall Of Duty Modern Warfare 3 Full Mu.md +++ /dev/null @@ -1,9 +0,0 @@ -
    -

    call of duty: modern warfare 3 multiplayer modes include 'solo', 'co-op', 'free-for-all', and 'unofficial' modes. 'solo' matches pit two players together with two weapons and objectives to complete. in 'co-op' modes, players can play with up to four allies each with two weapons and objectives to complete. 'free-for-all' matches pit two teams of four with a variety of weapons and objectives to complete. 'unofficial' modes have customized match types and objectives: 'gun game' pairs two teams of two with two weapons each, while 'custom' mode includes player-created maps.

    -

    Call Of Duty Modern Warfare 3 Full Multiplayer SP ^^nosTEAM^^Call Of Duty Modern Warfare 3 Full Mu


    Downloadhttps://urlin.us/2uEwP0



    -

    the call of duty: modern warfare 3 multiplayer arsenal features more than 40 new weapons with customizable sights and scopes. in addition, the killstreak system has been improved to emphasize a more balanced approach to kills, providing players with additional ways to dominate the battlefield. the improved uniform system provides players with a wide variety of customization options, including a new white uniform.

    -

    along with improved game mechanics, visual features, and modes, the call of duty: modern warfare 3 multiplayer is tuned for true 1080p with state-of-the-art image processing and lighting. the gameplay is improved, new features are being introduced, and the multiplayer experience is being refined, delivering a true 1080p graphics quality at 60 frames-per-second for the most intense multiplayer gaming experience ever.

    -

    execute a high-speed aerial takedown and take the fight into the sky with an rts-inspired grounded combat system. call of duty 4: modern warfare defined the first-person shooter, and call of duty 4 blackout will redefine the genre.

    -

    899543212b
    -
    -
    \ No newline at end of file diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Edid Override Windows 10.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Edid Override Windows 10.md deleted file mode 100644 index 21c33f301a297a9b80a8b922be8e8cb508f45c89..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Edid Override Windows 10.md +++ /dev/null @@ -1,152 +0,0 @@ - -

    Edid Override Windows 10: What It Is and How to Do It

    -

    If you have ever encountered display or audio issues with your monitor, TV, or projector connected to your Windows 10 PC, you might have heard of Edid Override Windows 10. This is a technique that allows you to override the Extended Display Identification Data (EDID) of your display device with a custom one that fixes the problems. In this article, we will explain what EDID is, why you might need to override it, and how to do it.

    -

    What is EDID?

    -

    EDID is a data structure that contains information about the capabilities and features of a display device, such as its manufacturer, model, serial number, supported resolutions, refresh rates, color depths, audio formats, and so on. This data is stored in a small memory chip on the display device and is transmitted to the PC or other source device when it is connected.

    -

    Edid Override Windows 10


    DOWNLOAD ··· https://urlin.us/2uEylE



    -

    The PC or source device uses the EDID information to determine the optimal display settings and audio output for the display device. For example, if the EDID indicates that the display device supports 4K resolution at 60 Hz and Dolby Digital 5.1 audio, the PC or source device will try to output those signals to the display device.

    -

    Why do you need to override EDID?

    -

    Sometimes, the EDID information on the display device may be incorrect, incomplete, or corrupted. This can cause various display or audio issues, such as:

    -
      -
    • The PC or source device does not detect the display device at all.
    • -
    • The PC or source device does not output the correct resolution, refresh rate, color depth, or audio format for the display device.
    • -
    • The PC or source device outputs a signal that is incompatible with the display device, resulting in a blank screen, flickering, distortion, or noise.
    • -
    • The PC or source device outputs a signal that is lower than the maximum supported by the display device, resulting in poor quality or performance.
    • -
    -

    To fix these issues, you may need to override the EDID information on the display device with a custom one that matches its actual capabilities and features. This way, you can force the PC or source device to output the correct signal for the display device.

    -

    How to override EDID on Windows 10?

    -

    To override EDID on Windows 10, you need to create an INF file that contains the custom EDID information and install it on your PC. An INF file is a text file that specifies how to install a driver or other software component on Windows. You can use an existing INF file from another display device that has similar capabilities and features as your display device, or create your own INF file using a tool such as Monitor Asset Manager (MonInfo).

    -

    Here are the steps to override EDID on Windows 10:

    -
      -
    1. Download and install MonInfo from http://www.entechtaiwan.com/util/moninfo.shtm
    2. -
    3. Run MonInfo and select your display device from the list.
    4. -
    5. Click on \"Create INF...\" and save the INF file to your PC.
    6. -
    7. Edit the INF file with a text editor such as Notepad and change the name and description of the monitor to something unique.
    8. -
    9. Right-click on the INF file and select \"Install\". You may need to confirm some prompts or restart your PC.
    10. -
    11. Go to Device Manager and expand \"Monitors\". You should see your display device with the new name and description.
    12. -
    13. Right-click on your display device and select \"Update driver\".
    14. -
    15. Select \"Browse my computer for driver software\".
    16. -
    17. Select \"Let me pick from a list of available drivers on my computer\".
    18. -
    19. Select \"Have Disk...\" and browse to the location of your INF file.
    20. -
    21. Select \"OK\" and then \"Next\". You may need to confirm some prompts or restart your PC.
    22. -
    -

    After these steps, your PC should use the custom EDID information from your INF file instead of the original EDID information from your display device. You can check if this worked by running MonInfo again and comparing the EDID information before and after overriding it.

    -

    Conclusion

    -

    Edid Override Windows 10 is a technique that allows you to override -the Extended Display Identification Data (EDID) of your display device -with a custom one -that fixes -display or audio issues. -EDID is -a data structure -that contains information -about -the capabilities and features -of a display device, -such as -its manufacturer, -model, -serial number, -supported resolutions, -refresh rates, -color depths, -audio formats, -and so on. -This data is stored -in a small memory chip -on -the display device -and is transmitted -to -the PC or other source device -when it is connected.

    -

    To override EDID on Windows 10, -you need -to create an INF file -that contains -the custom EDID information -and install it -on your PC. -An INF file is -a text file -that specifies how to install -a driver or other software component -on Windows. -You can use an existing INF file -from another display device -that has similar capabilities and features -as your display device, -or create your own INF file -using a tool such as MonInfo.

    -

    -

    If you are looking for -a way -to fix -display or audio issues -with your monitor, -TV, -or projector connected to your Windows 10 PC, -you might want to try Edid Override Windows 10. -It will provide you with -a better experience -with your display device.

    -

    Conclusion

    -

    Edid Override Windows 10 is a technique that allows you to override -the Extended Display Identification Data (EDID) of your display device -with a custom one -that fixes -display or audio issues. -EDID is -a data structure -that contains information -about -the capabilities and features -of a display device, -such as -its manufacturer, -model, -serial number, -supported resolutions, -refresh rates, -color depths, -audio formats, -and so on. -This data is stored -in a small memory chip -on -the display device -and is transmitted -to -the PC or other source device -when it is connected.

    -

    To override EDID on Windows 10, -you need -to create an INF file -that contains -the custom EDID information -and install it -on your PC. -An INF file is -a text file -that specifies how to install -a driver or other software component -on Windows. -You can use an existing INF file -from another display device -that has similar capabilities and features -as your display device, -or create your own INF file -using a tool such as MonInfo.

    -

    If you are looking for -a way -to fix -display or audio issues -with your monitor, -TV, -or projector connected to your Windows 10 PC, -you might want to try Edid Override Windows 10. -It will provide you with -a better experience -with your display device.

    3cee63e6c2
    -
    -
    \ No newline at end of file diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/HD Online Player (The Walking Dead Season 4 720p Blu) FREE.md b/spaces/inplisQlawa/anything-midjourney-v4-1/HD Online Player (The Walking Dead Season 4 720p Blu) FREE.md deleted file mode 100644 index 29548d3083103bbdbb877fabb3051cdca7d5d665..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/HD Online Player (The Walking Dead Season 4 720p Blu) FREE.md +++ /dev/null @@ -1,8 +0,0 @@ -
    -

    tune in as helix systems ceo and co-founder rona rojam takes the stage at the gamescom developer livestream to be among the first in the world to play on the all-new titanfall 2 beta. the massive game of the year has officially begun, where you play as a pilot of a massive war machine and battle with an elite cadre of other elite pilots in ways never seen before. join helix systems and witness the evolution of the titanfall franchise for yourself.

    -

    the walking dead recently released a new episode called live bait season 4, episode 2 on itunes, google play, and the xbox store. this episode brought michonn and clementine into contact with the mysterious manhunt that’s been chasing this family from the start.

    -

    HD Online Player (The Walking Dead Season 4 720p Blu)


    Download - https://urlin.us/2uEyHJ



    -

    she is asked to play this role for the duration of the entire running time of the play which is not resolved at the close of the play. she is also asked to choose an accent and costume that best represents the part; she did the life and death of marilyn monroe as marilyn, wear a short skirt and tight blouse, and she was shouted at for wearing a bikini for the battlestar galactica re-make. her battlestar galactica interpretation was such that one reviewer said that on the time that it was shown at the national film theatre, the play's west end premiere, the audience were more restrained towards her than when she first appeared on screen (downing 2007, 10

    -

    leonid nikolaev was one of the first scientists to successfully clone primates in 1961, and attempts were also made to clone humans. the project was abandoned when nikolaev died in 1977 of leukemia caused by radiation. percy shaw invented the concept of the double helix dna structure which he and watson publish in 1952. watson won the nobel prize in 1953 for his work on dna. in the public imagination, the two watson-shaw conferences leading up to the signing of the y-chromosome are considered to be the first meeting of a man and a woman, and the discovery has since become a symbol of the beginning of modern human history.

    899543212b
    -
    -
    \ No newline at end of file diff --git a/spaces/inreVtussa/clothingai/Examples/Anos E Demonios.pdf.md b/spaces/inreVtussa/clothingai/Examples/Anos E Demonios.pdf.md deleted file mode 100644 index 4e44eab2ad517502a1bd7bb38f568d01370eaad9..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/Anos E Demonios.pdf.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Anos E Demonios.pdf


    DOWNLOAD ○○○ https://tiurll.com/2uCjap



    -
    -Trans. Los Anjos con Laura Diaz. . -content/uploads/2008/10/garcia-marquez-gabriel-el-amor-en-lostiempos-del-colera.pdf>. . Del amor y otros demonios. -content/uploads/2008/10/pachino-je-nunca-suso-en-fiel.pdf>. . Un amor esto ya no soy. -content/uploads/2008/10/pachino-j-es-incorruptible.pdf>. . Un amor. -content/uploads/2008/10/pachino-e-j-es-incorruptible.pdf>. . Un amor. -content/uploads/2008/10/pachino-e-j-es-incorruptible.pdf>. . Un amor. -content/uploads/2008/10/pachino-e-j-es-incorruptible.pdf>. . Un amor. -content/uploads/2008 8a78ff9644
    -
    -
    -

    diff --git a/spaces/inreVtussa/clothingai/Examples/DVBViewer 5 3 2 April With HbbT By Takki.md b/spaces/inreVtussa/clothingai/Examples/DVBViewer 5 3 2 April With HbbT By Takki.md deleted file mode 100644 index 9e084ce1144fedd711e9bbabf32eb619d97e87a3..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/DVBViewer 5 3 2 April With HbbT By Takki.md +++ /dev/null @@ -1,37 +0,0 @@ - -

    How to Watch Digital TV on Your PC with DVBViewer 5 3 2 April With HbbT By Takki

    -

    If you want to enjoy high quality, sharp TV pictures and near CD quality radio on your PC, you need a software that can receive digital TV (DVB) signals. One of the best software for this purpose is DVBViewer, which has been around for 20 years and offers groundbreaking features like HbbTV, MHEG-5, and Ultra HDTV support.

    -

    DVBViewer 5 3 2 April With HbbT By Takki


    Download File >>> https://tiurll.com/2uCile



    -

    In this article, we will show you how to install and use DVBViewer 5 3 2 April With HbbT By Takki, which is a modified version of DVBViewer that includes some enhancements and fixes. This version also supports HbbT, which is a hybrid broadcast broadband TV standard that allows you to access additional content and services via the internet.

    -

    What You Need

    -

    To use DVBViewer 5 3 2 April With HbbT By Takki, you need the following:

    -
      -
    • A PC with Windows XP or higher.
    • -
    • A suitable DVB card or a SAT>IP Server that can receive digital TV signals.
    • -
    • A fast internet connection for streaming and HbbT content.
    • -
    • A license for DVBViewer Pro, which costs €20.
    • -
    • The DVBViewer 5 3 2 April With HbbT By Takki file, which you can download from SoundCloud [^1^] or kit.co [^3^].
    • -
    -

    How to Install

    -

    Follow these steps to install DVBViewer 5 3 2 April With HbbT By Takki:

    -

    -
      -
    1. Extract the downloaded file to a folder of your choice.
    2. -
    3. Run the setup.exe file and follow the instructions on the screen.
    4. -
    5. Enter your license key when prompted.
    6. -
    7. Run the DVBViewer Pro Wizard and configure your settings according to your preferences and hardware.
    8. -
    9. Enjoy watching digital TV on your PC!
    10. -
    -

    How to Use

    -

    Using DVBViewer 5 3 2 April With HbbT By Takki is very easy and intuitive. Here are some tips on how to use it:

    -
      -
    • To watch TV channels, simply select them from the channel list or use the EPG (electronic programming guide) to see what's on.
    • -
    • To record TV programs, right-click on them in the EPG and choose "Record". You can also schedule recordings in advance.
    • -
    • To access HbbT content, press the red button on your remote control or keyboard. You will see a menu with various options like news, weather, games, etc. Select the one you want and enjoy!
    • -
    • To manage your own music and video files, use the multimedia center feature. You can create playlists, browse folders, and play files with ease.
    • -
    • To customize your user interface, use the skin editor tool. You can change the appearance of DVBViewer according to your taste.
    • -
    -

    Conclusion

    -

    DVBViewer 5 3 2 April With HbbT By Takki is a great software for watching digital TV on your PC. It offers many features and enhancements that make it stand out from other similar software. It also supports HbbT, which gives you access to more content and services via the internet. If you want to try it out, download it today and enjoy!

    d5da3c52bf
    -
    -
    \ No newline at end of file diff --git a/spaces/ivanpc/Youtube_Audio/README.md b/spaces/ivanpc/Youtube_Audio/README.md deleted file mode 100644 index d7ec49d7b662606987abfc13bb0a0ef83b0b418e..0000000000000000000000000000000000000000 --- a/spaces/ivanpc/Youtube_Audio/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Youtube to Audio -emoji: 🎧 -colorFrom: red -colorTo: pink -sdk: gradio -sdk_version: 3.19.1 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -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/extensions/deforum/scripts/deforum_helpers/src/utils.py b/spaces/jackli888/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/src/utils.py deleted file mode 100644 index fbe08b0b1bd41f2bc59e9f8d188db08423fcf48a..0000000000000000000000000000000000000000 --- a/spaces/jackli888/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/src/utils.py +++ /dev/null @@ -1,140 +0,0 @@ -import base64 -import math -import re -from io import BytesIO - -import matplotlib.cm -import numpy as np -import torch -import torch.nn -from PIL import Image - - -class RunningAverage: - def __init__(self): - self.avg = 0 - self.count = 0 - - def append(self, value): - self.avg = (value + self.count * self.avg) / (self.count + 1) - self.count += 1 - - def get_value(self): - return self.avg - - -def denormalize(x, device='cpu'): - mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(device) - std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(device) - return x * std + mean - - -class RunningAverageDict: - def __init__(self): - self._dict = None - - def update(self, new_dict): - if self._dict is None: - self._dict = dict() - for key, value in new_dict.items(): - self._dict[key] = RunningAverage() - - for key, value in new_dict.items(): - self._dict[key].append(value) - - def get_value(self): - return {key: value.get_value() for key, value in self._dict.items()} - - -def colorize(value, vmin=10, vmax=1000, cmap='magma_r'): - value = value.cpu().numpy()[0, :, :] - invalid_mask = value == -1 - - # normalize - vmin = value.min() if vmin is None else vmin - vmax = value.max() if vmax is None else vmax - if vmin != vmax: - value = (value - vmin) / (vmax - vmin) # vmin..vmax - else: - # Avoid 0-division - value = value * 0. - # squeeze last dim if it exists - # value = value.squeeze(axis=0) - cmapper = matplotlib.cm.get_cmap(cmap) - value = cmapper(value, bytes=True) # (nxmx4) - value[invalid_mask] = 255 - img = value[:, :, :3] - - # return img.transpose((2, 0, 1)) - return img - - -def count_parameters(model): - return sum(p.numel() for p in model.parameters() if p.requires_grad) - - -def compute_errors(gt, pred): - thresh = np.maximum((gt / pred), (pred / gt)) - a1 = (thresh < 1.25).mean() - a2 = (thresh < 1.25 ** 2).mean() - a3 = (thresh < 1.25 ** 3).mean() - - abs_rel = np.mean(np.abs(gt - pred) / gt) - sq_rel = np.mean(((gt - pred) ** 2) / gt) - - rmse = (gt - pred) ** 2 - rmse = np.sqrt(rmse.mean()) - - rmse_log = (np.log(gt) - np.log(pred)) ** 2 - rmse_log = np.sqrt(rmse_log.mean()) - - err = np.log(pred) - np.log(gt) - silog = np.sqrt(np.mean(err ** 2) - np.mean(err) ** 2) * 100 - - log_10 = (np.abs(np.log10(gt) - np.log10(pred))).mean() - return dict(a1=a1, a2=a2, a3=a3, abs_rel=abs_rel, rmse=rmse, log_10=log_10, rmse_log=rmse_log, - silog=silog, sq_rel=sq_rel) - - -##################################### Demo Utilities ############################################ -def b64_to_pil(b64string): - image_data = re.sub('^data:image/.+;base64,', '', b64string) - # image = Image.open(cStringIO.StringIO(image_data)) - return Image.open(BytesIO(base64.b64decode(image_data))) - - -# Compute edge magnitudes -from scipy import ndimage - - -def edges(d): - dx = ndimage.sobel(d, 0) # horizontal derivative - dy = ndimage.sobel(d, 1) # vertical derivative - return np.abs(dx) + np.abs(dy) - - -class PointCloudHelper(): - def __init__(self, width=640, height=480): - self.xx, self.yy = self.worldCoords(width, height) - - def worldCoords(self, width=640, height=480): - hfov_degrees, vfov_degrees = 57, 43 - hFov = math.radians(hfov_degrees) - vFov = math.radians(vfov_degrees) - cx, cy = width / 2, height / 2 - fx = width / (2 * math.tan(hFov / 2)) - fy = height / (2 * math.tan(vFov / 2)) - xx, yy = np.tile(range(width), height), np.repeat(range(height), width) - xx = (xx - cx) / fx - yy = (yy - cy) / fy - return xx, yy - - def depth_to_points(self, depth): - depth[edges(depth) > 0.3] = np.nan # Hide depth edges - length = depth.shape[0] * depth.shape[1] - # depth[edges(depth) > 0.3] = 1e6 # Hide depth edges - z = depth.reshape(length) - - return np.dstack((self.xx * z, self.yy * z, z)).reshape((length, 3)) - -##################################################################################################### diff --git a/spaces/james-oldfield/PandA/networks/genforce/scripts/dist_test.sh b/spaces/james-oldfield/PandA/networks/genforce/scripts/dist_test.sh deleted file mode 100644 index e14bac7c9bf717facd1582f564fcf43ba5884130..0000000000000000000000000000000000000000 --- a/spaces/james-oldfield/PandA/networks/genforce/scripts/dist_test.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -GPUS=$1 -CONFIG=$2 -WORK_DIR=$3 -CHECKPOINT=$4 -PORT=${PORT:-29500} - -python -m torch.distributed.launch \ - --nproc_per_node=${GPUS} \ - --master_port=${PORT} \ - ./test.py ${CONFIG} \ - --work_dir ${WORK_DIR} \ - --checkpoint ${CHECKPOINT} \ - --launcher="pytorch" \ - ${@:5} diff --git a/spaces/jamescalam/ask-youtube/README.md b/spaces/jamescalam/ask-youtube/README.md deleted file mode 100644 index 6a4ce6a45a0392c16a775623dbb5221187ac3712..0000000000000000000000000000000000000000 --- a/spaces/jamescalam/ask-youtube/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Ask YouTube -emoji: 🦾 -colorFrom: purple -colorTo: blue -sdk: streamlit -sdk_version: 1.10.0 -app_file: app.py -pinned: false ---- - -Curious about how this works? Check out the [article](https://pinecone.io/learn/openai-whisper)! - -The current version of the app has a very limited video scope. We'd love to add more, so if you'd like to see more content added, feel free to send CSV data, including video title, channel ID, and video ID (at a minimum) to *james\@pinecone.io*. Even better if you could follow a format similar to [this](https://huggingface.co/datasets/jamescalam/channel-metadata). diff --git a/spaces/jamessteele/ChatbotBlenderbot-GR/README.md b/spaces/jamessteele/ChatbotBlenderbot-GR/README.md deleted file mode 100644 index 73f5b35aed185284bea86b61c60387309cf4bee2..0000000000000000000000000000000000000000 --- a/spaces/jamessteele/ChatbotBlenderbot-GR/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: ChatbotBlenderbot GR -emoji: 🦀 -colorFrom: pink -colorTo: red -sdk: gradio -sdk_version: 3.8.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/jannisborn/paccmann/artifacts/dump_cos_data.sh b/spaces/jannisborn/paccmann/artifacts/dump_cos_data.sh deleted file mode 100644 index 62577d29cb5a666841d58ff74c7e3df333225f40..0000000000000000000000000000000000000000 --- a/spaces/jannisborn/paccmann/artifacts/dump_cos_data.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -mc cp chcls-cos/paccmann-storage/model.pt model.pt -mc cp chcls-cos/paccmann-storage/model.json model.json -mc cp chcls-cos/paccmann-storage/gene_expression_standardization.pkl gene_expression_standardization.pkl -mc cp chcls-cos/paccmann-storage/genes.pkl genes.pkl -mc cp chcls-cos/paccmann-storage/gene_expression.csv.zip gene_expression.csv.zip -mc cp chcls-cos/paccmann-storage/smiles_language.pkl smiles_language.pkl - diff --git a/spaces/jcenaa/Segment-Any-RGBD/datasets/prepare_voc_sem_seg.py b/spaces/jcenaa/Segment-Any-RGBD/datasets/prepare_voc_sem_seg.py deleted file mode 100644 index 1dbe80a5b8ae53627998214ec6a1f9a7fc30fad9..0000000000000000000000000000000000000000 --- a/spaces/jcenaa/Segment-Any-RGBD/datasets/prepare_voc_sem_seg.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# Copyright (c) Meta Platforms, Inc. All Rights Reserved -# Modified by Feng Liang from https://github.com/MendelXu/zsseg.baseline/blob/master/datasets/prepare_voc_sem_seg.py - -import os -import os.path as osp -from pathlib import Path -import tqdm - -import numpy as np -from PIL import Image - - -clsID_to_trID = { - 0: 255, - 1: 0, - 2: 1, - 3: 2, - 4: 3, - 5: 4, - 6: 5, - 7: 6, - 8: 7, - 9: 8, - 10: 9, - 11: 10, - 12: 11, - 13: 12, - 14: 13, - 15: 14, - 16: 15, - 17: 16, - 18: 17, - 19: 18, - 20: 19, - 255: 255, -} - -def convert_to_trainID( - maskpath, out_mask_dir, is_train, clsID_to_trID=clsID_to_trID, suffix="" -): - mask = np.array(Image.open(maskpath)) - mask_copy = np.ones_like(mask, dtype=np.uint8) * 255 - for clsID, trID in clsID_to_trID.items(): - mask_copy[mask == clsID] = trID - seg_filename = ( - osp.join(out_mask_dir, "train" + suffix, osp.basename(maskpath)) - if is_train - else osp.join(out_mask_dir, "val" + suffix, osp.basename(maskpath)) - ) - if len(np.unique(mask_copy)) == 1 and np.unique(mask_copy)[0] == 255: - return - Image.fromarray(mask_copy).save(seg_filename, "PNG") - - - -if __name__ == "__main__": - dataset_dir = Path(os.getenv("DETECTRON2_DATASETS", "datasets")) - print('Caution: we only generate the validation set!') - voc_path = dataset_dir / "VOCdevkit" / "VOC2012" - out_mask_dir = voc_path / "annotations_detectron2" - out_image_dir = voc_path / "images_detectron2" - for name in ["val"]: - os.makedirs((out_mask_dir / name), exist_ok=True) - os.makedirs((out_image_dir / name), exist_ok=True) - val_list = [ - osp.join(voc_path, "SegmentationClassAug", f + ".png") - for f in np.loadtxt(osp.join(voc_path, "ImageSets/Segmentation/val.txt"), dtype=np.str).tolist() - ] - for file in tqdm.tqdm(val_list): - convert_to_trainID(file, out_mask_dir, is_train=False) diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/SelfTest/Hash/test_SHA3_384.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/SelfTest/Hash/test_SHA3_384.py deleted file mode 100644 index b0ba1bfee010476d653d9ae0788251a8ded2c552..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/SelfTest/Hash/test_SHA3_384.py +++ /dev/null @@ -1,79 +0,0 @@ -# -*- coding: utf-8 -*- -# -# SelfTest/Hash/test_SHA3_384.py: Self-test for the SHA-3/384 hash function -# -# =================================================================== -# 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. -# =================================================================== - -"""Self-test suite for Crypto.Hash.SHA3_384""" - -import unittest -from binascii import hexlify - -from Crypto.SelfTest.loader import load_test_vectors -from Crypto.SelfTest.st_common import list_test_cases -from Crypto.Hash import SHA3_384 as SHA3 -from Crypto.Util.py3compat import b - - -class APITest(unittest.TestCase): - - def test_update_after_digest(self): - msg=b("rrrrttt") - - # Normally, update() cannot be done after digest() - h = SHA3.new(data=msg[:4]) - dig1 = h.digest() - self.assertRaises(TypeError, h.update, msg[4:]) - dig2 = SHA3.new(data=msg).digest() - - # With the proper flag, it is allowed - h = SHA3.new(data=msg[:4], update_after_digest=True) - self.assertEqual(h.digest(), dig1) - # ... and the subsequent digest applies to the entire message - # up to that point - h.update(msg[4:]) - self.assertEqual(h.digest(), dig2) - - -def get_tests(config={}): - from .common import make_hash_tests - - tests = [] - - test_vectors = load_test_vectors(("Hash", "SHA3"), - "ShortMsgKAT_SHA3-384.txt", - "KAT SHA-3 384", - { "len" : lambda x: int(x) } ) or [] - - test_data = [] - for tv in test_vectors: - if tv.len == 0: - tv.msg = b("") - test_data.append((hexlify(tv.md), tv.msg, tv.desc)) - - tests += make_hash_tests(SHA3, "SHA3_384", test_data, - digest_size=SHA3.digest_size, - oid="2.16.840.1.101.3.4.2.9") - tests += list_test_cases(APITest) - return tests - -if __name__ == '__main__': - import unittest - suite = lambda: unittest.TestSuite(get_tests()) - unittest.main(defaultTest='suite') diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/altair/utils/_transformed_data.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/altair/utils/_transformed_data.py deleted file mode 100644 index 99bfbcde435ded733453bc13dfbee83770256a00..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/altair/utils/_transformed_data.py +++ /dev/null @@ -1,559 +0,0 @@ -from typing import List, Optional, Tuple, Dict, Iterable, overload, Union - -from altair import ( - Chart, - FacetChart, - LayerChart, - HConcatChart, - VConcatChart, - ConcatChart, - TopLevelUnitSpec, - FacetedUnitSpec, - UnitSpec, - UnitSpecWithFrame, - NonNormalizedSpec, - TopLevelLayerSpec, - LayerSpec, - TopLevelConcatSpec, - ConcatSpecGenericSpec, - TopLevelHConcatSpec, - HConcatSpecGenericSpec, - TopLevelVConcatSpec, - VConcatSpecGenericSpec, - TopLevelFacetSpec, - FacetSpec, - data_transformers, -) -from altair.utils._vegafusion_data import get_inline_tables, import_vegafusion -from altair.utils.core import _DataFrameLike -from altair.utils.schemapi import Undefined - -Scope = Tuple[int, ...] -FacetMapping = Dict[Tuple[str, Scope], Tuple[str, Scope]] - - -# For the transformed_data functionality, the chart classes in the values -# can be considered equivalent to the chart class in the key. -_chart_class_mapping = { - Chart: ( - Chart, - TopLevelUnitSpec, - FacetedUnitSpec, - UnitSpec, - UnitSpecWithFrame, - NonNormalizedSpec, - ), - LayerChart: (LayerChart, TopLevelLayerSpec, LayerSpec), - ConcatChart: (ConcatChart, TopLevelConcatSpec, ConcatSpecGenericSpec), - HConcatChart: (HConcatChart, TopLevelHConcatSpec, HConcatSpecGenericSpec), - VConcatChart: (VConcatChart, TopLevelVConcatSpec, VConcatSpecGenericSpec), - FacetChart: (FacetChart, TopLevelFacetSpec, FacetSpec), -} - - -@overload -def transformed_data( - chart: Union[Chart, FacetChart], - row_limit: Optional[int] = None, - exclude: Optional[Iterable[str]] = None, -) -> Optional[_DataFrameLike]: - ... - - -@overload -def transformed_data( - chart: Union[LayerChart, HConcatChart, VConcatChart, ConcatChart], - row_limit: Optional[int] = None, - exclude: Optional[Iterable[str]] = None, -) -> List[_DataFrameLike]: - ... - - -def transformed_data(chart, row_limit=None, exclude=None): - """Evaluate a Chart's transforms - - Evaluate the data transforms associated with a Chart and return the - transformed data as one or more DataFrames - - Parameters - ---------- - chart : Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart - Altair chart to evaluate transforms on - row_limit : int (optional) - Maximum number of rows to return for each DataFrame. None (default) for unlimited - exclude : iterable of str - Set of the names of charts to exclude - - Returns - ------- - DataFrame or list of DataFrames or None - If input chart is a Chart or Facet Chart, returns a DataFrame of the - transformed data. Otherwise, returns a list of DataFrames of the - transformed data - """ - vf = import_vegafusion() - - if isinstance(chart, Chart): - # Add mark if none is specified to satisfy Vega-Lite - if chart.mark == Undefined: - chart = chart.mark_point() - - # Deep copy chart so that we can rename marks without affecting caller - chart = chart.copy(deep=True) - - # Ensure that all views are named so that we can look them up in the - # resulting Vega specification - chart_names = name_views(chart, 0, exclude=exclude) - - # Compile to Vega and extract inline DataFrames - with data_transformers.enable("vegafusion"): - vega_spec = chart.to_dict(format="vega", context={"pre_transform": False}) - inline_datasets = get_inline_tables(vega_spec) - - # Build mapping from mark names to vega datasets - facet_mapping = get_facet_mapping(vega_spec) - dataset_mapping = get_datasets_for_view_names(vega_spec, chart_names, facet_mapping) - - # Build a list of vega dataset names that corresponds to the order - # of the chart components - dataset_names = [] - for chart_name in chart_names: - if chart_name in dataset_mapping: - dataset_names.append(dataset_mapping[chart_name]) - else: - raise ValueError("Failed to locate all datasets") - - # Extract transformed datasets with VegaFusion - datasets, warnings = vf.runtime.pre_transform_datasets( - vega_spec, - dataset_names, - row_limit=row_limit, - inline_datasets=inline_datasets, - ) - - if isinstance(chart, (Chart, FacetChart)): - # Return DataFrame (or None if it was excluded) if input was a simple Chart - if not datasets: - return None - else: - return datasets[0] - else: - # Otherwise return the list of DataFrames - return datasets - - -# The equivalent classes from _chart_class_mapping should also be added -# to the type hints below for `chart` as the function would also work for them. -# However, this was not possible so far as mypy then complains about -# "Overloaded function signatures 1 and 2 overlap with incompatible return types [misc]" -# This might be due to the complex type hierarchy of the chart classes. -# See also https://github.com/python/mypy/issues/5119 -# and https://github.com/python/mypy/issues/4020 which show that mypy might not have -# a very consistent behavior for overloaded functions. -# The same error appeared when trying it with Protocols for the concat and layer charts. -# This function is only used internally and so we accept this inconsistency for now. -def name_views( - chart: Union[ - Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, ConcatChart - ], - i: int = 0, - exclude: Optional[Iterable[str]] = None, -) -> List[str]: - """Name unnamed chart views - - Name unnamed charts views so that we can look them up later in - the compiled Vega spec. - - Note: This function mutates the input chart by applying names to - unnamed views. - - Parameters - ---------- - chart : Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart - Altair chart to apply names to - i : int (default 0) - Starting chart index - exclude : iterable of str - Names of charts to exclude - - Returns - ------- - list of str - List of the names of the charts and subcharts - """ - exclude = set(exclude) if exclude is not None else set() - if isinstance(chart, _chart_class_mapping[Chart]) or isinstance( - chart, _chart_class_mapping[FacetChart] - ): - if chart.name not in exclude: - if chart.name in (None, Undefined): - # Add name since none is specified - chart.name = Chart._get_name() - return [chart.name] - else: - return [] - else: - if isinstance(chart, _chart_class_mapping[LayerChart]): - subcharts = chart.layer - elif isinstance(chart, _chart_class_mapping[HConcatChart]): - subcharts = chart.hconcat - elif isinstance(chart, _chart_class_mapping[VConcatChart]): - subcharts = chart.vconcat - elif isinstance(chart, _chart_class_mapping[ConcatChart]): - subcharts = chart.concat - else: - raise ValueError( - "transformed_data accepts an instance of " - "Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart\n" - f"Received value of type: {type(chart)}" - ) - - chart_names: List[str] = [] - for subchart in subcharts: - for name in name_views(subchart, i=i + len(chart_names), exclude=exclude): - chart_names.append(name) - return chart_names - - -def get_group_mark_for_scope(vega_spec: dict, scope: Scope) -> Optional[dict]: - """Get the group mark at a particular scope - - Parameters - ---------- - vega_spec : dict - Top-level Vega specification dictionary - scope : tuple of int - Scope tuple. If empty, the original Vega specification is returned. - Otherwise, the nested group mark at the scope specified is returned. - - Returns - ------- - dict or None - Top-level Vega spec (if scope is empty) - or group mark (if scope is non-empty) - or None (if group mark at scope does not exist) - - Examples - -------- - >>> spec = { - ... "marks": [ - ... { - ... "type": "group", - ... "marks": [{"type": "symbol"}] - ... }, - ... { - ... "type": "group", - ... "marks": [{"type": "rect"}]} - ... ] - ... } - >>> get_group_mark_for_scope(spec, (1,)) - {'type': 'group', 'marks': [{'type': 'rect'}]} - """ - group = vega_spec - - # Find group at scope - for scope_value in scope: - group_index = 0 - child_group = None - for mark in group.get("marks", []): - if mark.get("type") == "group": - if group_index == scope_value: - child_group = mark - break - group_index += 1 - if child_group is None: - return None - group = child_group - - return group - - -def get_datasets_for_scope(vega_spec: dict, scope: Scope) -> List[str]: - """Get the names of the datasets that are defined at a given scope - - Parameters - ---------- - vega_spec : dict - Top-leve Vega specification - scope : tuple of int - Scope tuple. If empty, the names of top-level datasets are returned - Otherwise, the names of the datasets defined in the nested group mark - at the specified scope are returned. - - Returns - ------- - list of str - List of the names of the datasets defined at the specified scope - - Examples - -------- - >>> spec = { - ... "data": [ - ... {"name": "data1"} - ... ], - ... "marks": [ - ... { - ... "type": "group", - ... "data": [ - ... {"name": "data2"} - ... ], - ... "marks": [{"type": "symbol"}] - ... }, - ... { - ... "type": "group", - ... "data": [ - ... {"name": "data3"}, - ... {"name": "data4"}, - ... ], - ... "marks": [{"type": "rect"}] - ... } - ... ] - ... } - - >>> get_datasets_for_scope(spec, ()) - ['data1'] - - >>> get_datasets_for_scope(spec, (0,)) - ['data2'] - - >>> get_datasets_for_scope(spec, (1,)) - ['data3', 'data4'] - - Returns empty when no group mark exists at scope - >>> get_datasets_for_scope(spec, (1, 3)) - [] - """ - group = get_group_mark_for_scope(vega_spec, scope) or {} - - # get datasets from group - datasets = [] - for dataset in group.get("data", []): - datasets.append(dataset["name"]) - - # Add facet dataset - facet_dataset = group.get("from", {}).get("facet", {}).get("name", None) - if facet_dataset: - datasets.append(facet_dataset) - return datasets - - -def get_definition_scope_for_data_reference( - vega_spec: dict, data_name: str, usage_scope: Scope -) -> Optional[Scope]: - """Return the scope that a dataset is defined at, for a given usage scope - - Parameters - ---------- - vega_spec: dict - Top-level Vega specification - data_name: str - The name of a dataset reference - usage_scope: tuple of int - The scope that the dataset is referenced in - - Returns - ------- - tuple of int - The scope where the referenced dataset is defined, - or None if no such dataset is found - - Examples - -------- - >>> spec = { - ... "data": [ - ... {"name": "data1"} - ... ], - ... "marks": [ - ... { - ... "type": "group", - ... "data": [ - ... {"name": "data2"} - ... ], - ... "marks": [{ - ... "type": "symbol", - ... "encode": { - ... "update": { - ... "x": {"field": "x", "data": "data1"}, - ... "y": {"field": "y", "data": "data2"}, - ... } - ... } - ... }] - ... } - ... ] - ... } - - data1 is referenced at scope [0] and defined at scope [] - >>> get_definition_scope_for_data_reference(spec, "data1", (0,)) - () - - data2 is referenced at scope [0] and defined at scope [0] - >>> get_definition_scope_for_data_reference(spec, "data2", (0,)) - (0,) - - If data2 is not visible at scope [] (the top level), - because it's defined in scope [0] - >>> repr(get_definition_scope_for_data_reference(spec, "data2", ())) - 'None' - """ - for i in reversed(range(len(usage_scope) + 1)): - scope = usage_scope[:i] - datasets = get_datasets_for_scope(vega_spec, scope) - if data_name in datasets: - return scope - return None - - -def get_facet_mapping(group: dict, scope: Scope = ()) -> FacetMapping: - """Create mapping from facet definitions to source datasets - - Parameters - ---------- - group : dict - Top-level Vega spec or nested group mark - scope : tuple of int - Scope of the group dictionary within a top-level Vega spec - - Returns - ------- - dict - Dictionary from (facet_name, facet_scope) to (dataset_name, dataset_scope) - - Examples - -------- - >>> spec = { - ... "data": [ - ... {"name": "data1"} - ... ], - ... "marks": [ - ... { - ... "type": "group", - ... "from": { - ... "facet": { - ... "name": "facet1", - ... "data": "data1", - ... "groupby": ["colA"] - ... } - ... } - ... } - ... ] - ... } - >>> get_facet_mapping(spec) - {('facet1', (0,)): ('data1', ())} - """ - facet_mapping = {} - group_index = 0 - mark_group = get_group_mark_for_scope(group, scope) or {} - for mark in mark_group.get("marks", []): - if mark.get("type", None) == "group": - # Get facet for this group - group_scope = scope + (group_index,) - facet = mark.get("from", {}).get("facet", None) - if facet is not None: - facet_name = facet.get("name", None) - facet_data = facet.get("data", None) - if facet_name is not None and facet_data is not None: - definition_scope = get_definition_scope_for_data_reference( - group, facet_data, scope - ) - if definition_scope is not None: - facet_mapping[(facet_name, group_scope)] = ( - facet_data, - definition_scope, - ) - - # Handle children recursively - child_mapping = get_facet_mapping(group, scope=group_scope) - facet_mapping.update(child_mapping) - group_index += 1 - - return facet_mapping - - -def get_from_facet_mapping( - scoped_dataset: Tuple[str, Scope], facet_mapping: FacetMapping -) -> Tuple[str, Scope]: - """Apply facet mapping to a scoped dataset - - Parameters - ---------- - scoped_dataset : (str, tuple of int) - A dataset name and scope tuple - facet_mapping : dict from (str, tuple of int) to (str, tuple of int) - The facet mapping produced by get_facet_mapping - - Returns - ------- - (str, tuple of int) - Dataset name and scope tuple that has been mapped as many times as possible - - Examples - -------- - Facet mapping as produced by get_facet_mapping - >>> facet_mapping = {("facet1", (0,)): ("data1", ()), ("facet2", (0, 1)): ("facet1", (0,))} - >>> get_from_facet_mapping(("facet2", (0, 1)), facet_mapping) - ('data1', ()) - """ - while scoped_dataset in facet_mapping: - scoped_dataset = facet_mapping[scoped_dataset] - return scoped_dataset - - -def get_datasets_for_view_names( - group: dict, - vl_chart_names: List[str], - facet_mapping: FacetMapping, - scope: Scope = (), -) -> Dict[str, Tuple[str, Scope]]: - """Get the Vega datasets that correspond to the provided Altair view names - - Parameters - ---------- - group : dict - Top-level Vega spec or nested group mark - vl_chart_names : list of str - List of the Vega-Lite - facet_mapping : dict from (str, tuple of int) to (str, tuple of int) - The facet mapping produced by get_facet_mapping - scope : tuple of int - Scope of the group dictionary within a top-level Vega spec - - Returns - ------- - dict from str to (str, tuple of int) - Dict from Altair view names to scoped datasets - """ - datasets = {} - group_index = 0 - mark_group = get_group_mark_for_scope(group, scope) or {} - for mark in mark_group.get("marks", []): - for vl_chart_name in vl_chart_names: - if mark.get("name", "") == f"{vl_chart_name}_cell": - data_name = mark.get("from", {}).get("facet", None).get("data", None) - scoped_data_name = (data_name, scope) - datasets[vl_chart_name] = get_from_facet_mapping( - scoped_data_name, facet_mapping - ) - break - - name = mark.get("name", "") - if mark.get("type", "") == "group": - group_data_names = get_datasets_for_view_names( - group, vl_chart_names, facet_mapping, scope=scope + (group_index,) - ) - for k, v in group_data_names.items(): - datasets.setdefault(k, v) - group_index += 1 - else: - for vl_chart_name in vl_chart_names: - if name.startswith(vl_chart_name) and name.endswith("_marks"): - data_name = mark.get("from", {}).get("data", None) - scoped_data = get_definition_scope_for_data_reference( - group, data_name, scope - ) - if scoped_data is not None: - datasets[vl_chart_name] = get_from_facet_mapping( - (data_name, scoped_data), facet_mapping - ) - break - - return datasets diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/contourpy/_version.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/contourpy/_version.py deleted file mode 100644 index a82b376d2d72e66e1eb1b713f181f287dcea47a1..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/contourpy/_version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "1.1.1" diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/feaLib/lookupDebugInfo.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/feaLib/lookupDebugInfo.py deleted file mode 100644 index d4da7de0aed6b87dae6a1d4b417f1c6e099fe1e0..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/feaLib/lookupDebugInfo.py +++ /dev/null @@ -1,12 +0,0 @@ -from typing import NamedTuple - -LOOKUP_DEBUG_INFO_KEY = "com.github.fonttools.feaLib" -LOOKUP_DEBUG_ENV_VAR = "FONTTOOLS_LOOKUP_DEBUGGING" - - -class LookupDebugInfo(NamedTuple): - """Information about where a lookup came from, to be embedded in a font""" - - location: str - name: str - feature: list diff --git a/spaces/jskalbg/ChatDev01/chatdev/composed_phase.py b/spaces/jskalbg/ChatDev01/chatdev/composed_phase.py deleted file mode 100644 index e8e899b9e27770d437f6fcdaa548a8c10c10a5a7..0000000000000000000000000000000000000000 --- a/spaces/jskalbg/ChatDev01/chatdev/composed_phase.py +++ /dev/null @@ -1,233 +0,0 @@ -import importlib -import os -from abc import ABC, abstractmethod -from collections import defaultdict - -from camel.typing import ModelType -from chatdev.chat_env import ChatEnv -from chatdev.utils import log_and_print_online - - -def check_bool(s): - return s.lower() == "true" - - -class ComposedPhase(ABC): - def __init__(self, - phase_name: str = None, - cycle_num: int = None, - composition: list = None, - config_phase: dict = None, - config_role: dict = None, - model_type: ModelType = ModelType.GPT_3_5_TURBO, - log_filepath: str = "" - ): - """ - - Args: - phase_name: name of this phase - cycle_num: loop times of this phase - composition: list of SimplePhases in this ComposePhase - config_phase: configuration of all SimplePhases - config_role: configuration of all Roles - """ - - self.phase_name = phase_name - self.cycle_num = cycle_num - self.composition = composition - self.model_type = model_type - self.log_filepath = log_filepath - - self.config_phase = config_phase - self.config_role = config_role - - self.phase_env = dict() - - # init chat turn - self.chat_turn_limit_default = 10 - - # init role - self.role_prompts = dict() - for role in self.config_role: - self.role_prompts[role] = "\n".join(self.config_role[role]) - - # init all SimplePhases instances in this ComposedPhase - self.phases = dict() - for phase in self.config_phase: - assistant_role_name = self.config_phase[phase]['assistant_role_name'] - user_role_name = self.config_phase[phase]['user_role_name'] - phase_prompt = "\n".join(self.config_phase[phase]['phase_prompt']) - phase_module = importlib.import_module("chatdev.phase") - phase_class = getattr(phase_module, phase) - phase_instance = phase_class(assistant_role_name=assistant_role_name, - user_role_name=user_role_name, - phase_prompt=phase_prompt, - role_prompts=self.role_prompts, - phase_name=phase, - model_type=self.model_type, - log_filepath=self.log_filepath) - self.phases[phase] = phase_instance - - @abstractmethod - def update_phase_env(self, chat_env): - """ - update self.phase_env (if needed) using chat_env, then the chatting will use self.phase_env to follow the context and fill placeholders in phase prompt - must be implemented in customized phase - the usual format is just like: - ``` - self.phase_env.update({key:chat_env[key]}) - ``` - Args: - chat_env: global chat chain environment - - Returns: None - - """ - pass - - @abstractmethod - def update_chat_env(self, chat_env) -> ChatEnv: - """ - update chan_env based on the results of self.execute, which is self.seminar_conclusion - must be implemented in customized phase - the usual format is just like: - ``` - chat_env.xxx = some_func_for_postprocess(self.seminar_conclusion) - ``` - Args: - chat_env:global chat chain environment - - Returns: - chat_env: updated global chat chain environment - - """ - pass - - @abstractmethod - def break_cycle(self, phase_env) -> bool: - """ - special conditions for early break the loop in ComposedPhase - Args: - phase_env: phase environment - - Returns: None - - """ - pass - - def execute(self, chat_env) -> ChatEnv: - """ - similar to Phase.execute, but add control for breaking the loop - 1. receive information from environment(ComposedPhase): update the phase environment from global environment - 2. for each SimplePhase in ComposedPhase - a) receive information from environment(SimplePhase) - b) check loop break - c) execute the chatting - d) change the environment(SimplePhase) - e) check loop break - 3. change the environment(ComposedPhase): update the global environment using the conclusion - - Args: - chat_env: global chat chain environment - - Returns: - - """ - self.update_phase_env(chat_env) - for cycle_index in range(self.cycle_num): - for phase_item in self.composition: - assert phase_item["phaseType"] == "SimplePhase" # right now we do not support nested composition - phase = phase_item['phase'] - max_turn_step = phase_item['max_turn_step'] - need_reflect = check_bool(phase_item['need_reflect']) - log_and_print_online( - f"**[Execute Detail]**\n\nexecute SimplePhase:[{phase}] in ComposedPhase:[{self.phase_name}], cycle {cycle_index}") - if phase in self.phases: - self.phases[phase].phase_env = self.phase_env - self.phases[phase].update_phase_env(chat_env) - if self.break_cycle(self.phases[phase].phase_env): - return chat_env - chat_env = self.phases[phase].execute(chat_env, - self.chat_turn_limit_default if max_turn_step <= 0 else max_turn_step, - need_reflect) - if self.break_cycle(self.phases[phase].phase_env): - return chat_env - else: - print(f"Phase '{phase}' is not yet implemented. \ - Please write its config in phaseConfig.json \ - and implement it in chatdev.phase") - chat_env = self.update_chat_env(chat_env) - return chat_env - - -class Art(ComposedPhase): - def __init__(self, **kwargs): - super().__init__(**kwargs) - - def update_phase_env(self, chat_env): - pass - - def update_chat_env(self, chat_env): - return chat_env - - def break_cycle(self, chat_env) -> bool: - return False - - -class CodeCompleteAll(ComposedPhase): - def __init__(self, **kwargs): - super().__init__(**kwargs) - - def update_phase_env(self, chat_env): - pyfiles = [filename for filename in os.listdir(chat_env.env_dict['directory']) if filename.endswith(".py")] - num_tried = defaultdict(int) - num_tried.update({filename: 0 for filename in pyfiles}) - self.phase_env = { - "max_num_implement": 5, - "pyfiles": pyfiles, - "num_tried": num_tried - } - - def update_chat_env(self, chat_env): - return chat_env - - def break_cycle(self, phase_env) -> bool: - if phase_env['unimplemented_file'] == "": - return True - else: - return False - - -class CodeReview(ComposedPhase): - def __init__(self, **kwargs): - super().__init__(**kwargs) - - def update_phase_env(self, chat_env): - self.phase_env = {"modification_conclusion": ""} - - def update_chat_env(self, chat_env): - return chat_env - - def break_cycle(self, phase_env) -> bool: - if " Finished".lower() in phase_env['modification_conclusion'].lower(): - return True - else: - return False - - -class Test(ComposedPhase): - def __init__(self, **kwargs): - super().__init__(**kwargs) - - def update_phase_env(self, chat_env): - self.phase_env = dict() - - def update_chat_env(self, chat_env): - return chat_env - - def break_cycle(self, phase_env) -> bool: - if not phase_env['exist_bugs_flag']: - log_and_print_online(f"**[Test Info]**\n\nAI User (Software Test Engineer):\nTest Pass!\n") - return True - else: - return False diff --git a/spaces/k1ngtai/MMS/uroman/README.md b/spaces/k1ngtai/MMS/uroman/README.md deleted file mode 100644 index 6a0a40f6d4ebda9041d23efe0345340b7da9d4b8..0000000000000000000000000000000000000000 --- a/spaces/k1ngtai/MMS/uroman/README.md +++ /dev/null @@ -1,165 +0,0 @@ -# uroman - -*uroman* is a *universal romanizer*. It converts text in any script to the Latin alphabet. - -Version: 1.2.8 -Release date: April 23, 2021 -Author: Ulf Hermjakob, USC Information Sciences Institute - - -### Usage -```bash -$ uroman.pl [-l ] [--chart] [--no-cache] < STDIN - where the optional is a 3-letter languages code, e.g. ara, bel, bul, deu, ell, eng, fas, - grc, ell, eng, heb, kaz, kir, lav, lit, mkd, mkd2, oss, pnt, pus, rus, srp, srp2, tur, uig, ukr, yid. - --chart specifies chart output (in JSON format) to represent alternative romanizations. - --no-cache disables caching. -``` -### Examples -```bash -$ bin/uroman.pl < text/zho.txt -$ bin/uroman.pl -l tur < text/tur.txt -$ bin/uroman.pl -l heb --chart < text/heb.txt -$ bin/uroman.pl < test/multi-script.txt > test/multi-script.uroman.txt -``` - -Identifying the input as Arabic, Belarusian, Bulgarian, English, Farsi, German, -Ancient Greek, Modern Greek, Pontic Greek, Hebrew, Kazakh, Kyrgyz, Latvian, -Lithuanian, North Macedonian, Russian, Serbian, Turkish, Ukrainian, Uyghur or -Yiddish will improve romanization for those languages as some letters in those -languages have different sound values from other languages using the same script -(French, Russian, Hebrew respectively). -No effect for other languages in this version. - -### Bibliography -Ulf Hermjakob, Jonathan May, and Kevin Knight. 2018. Out-of-the-box universal romanization tool uroman. In Proceedings of the 56th Annual Meeting of Association for Computational Linguistics, Demo Track. ACL-2018 Best Demo Paper Award. [Paper in ACL Anthology](https://www.aclweb.org/anthology/P18-4003) | [Poster](https://www.isi.edu/~ulf/papers/poster-uroman-acl2018.pdf) | [BibTex](https://www.aclweb.org/anthology/P18-4003.bib) - -### Change History -Changes in version 1.2.8 - * Updated to Unicode 13.0 (2021), which supports several new scripts (10% larger UnicodeData.txt). - * Improved support for Georgian. - * Preserve various symbols (as opposed to mapping to the symbols' names). - * Various small improvements. - -Changes in version 1.2.7 - * Improved support for Pashto. - -Changes in version 1.2.6 - * Improved support for Ukrainian, Russian and Ogham (ancient Irish script). - * Added support for English Braille. - * Added alternative Romanization for North Macedonian and Serbian (mkd2/srp2) - reflecting a casual style that many native speakers of those languages use - when writing text in Latin script, e.g. non-accented single letters (e.g. "s") - rather than phonetically motivated combinations of letters (e.g. "sh"). - * When a line starts with "::lcode xyz ", the new uroman version will switch to - that language for that line. This is used for the new reference test file. - * Various small improvements. - -Changes in version 1.2.5 - * Improved support for Armenian and eight languages using Cyrillic scripts. - -- For Serbian and Macedonian, which are often written in both Cyrillic - and Latin scripts, uroman will map both official versions to the same - romanized text, e.g. both "Ниш" and "Niš" will be mapped to "Nish" (which - properly reflects the pronunciation of the city's name). - For both Serbian and Macedonian, casual writers often use a simplified - Latin form without diacritics, e.g. "s" to represent not only Cyrillic "с" - and Latin "s", but also "ш" or "š", even if this conflates "s" and "sh" and - other such pairs. The casual romanization can be simulated by using - alternative uroman language codes "srp2" and "mkd2", which romanize - both "Ниш" and "Niš" to "Nis" to reflect the casual Latin spelling. - * Various small improvements. - -Changes in version 1.2.4 - * Bug-fix that generated two emtpy lines for each empty line in cache mode. - -Changes in version 1.2 - * Run-time improvement based on (1) token-based caching and (2) shortcut - romanization (identity) of ASCII strings for default 1-best (non-chart) - output. Speed-up by a factor of 10 for Bengali and Uyghur on medium and - large size texts. - * Incremental improvements for Farsi, Amharic, Russian, Hebrew and related - languages. - * Richer lattice structure (more alternatives) for "Romanization" of English - to support better matching to romanizations of other languages. - Changes output only when --chart option is specified. No change in output for - default 1-best output, which for ASCII characters is always the input string. - -Changes in version 1.1 (major upgrade) - * Offers chart output (in JSON format) to represent alternative romanizations. - -- Location of first character is defined to be "line: 1, start:0, end:0". - * Incremental improvements of Hebrew and Greek romanization; Chinese numbers. - * Improved web-interface at http://www.isi.edu/~ulf/uroman.html - -- Shows corresponding original and romanization text in red - when hovering over a text segment. - -- Shows alternative romanizations when hovering over romanized text - marked by dotted underline. - -- Added right-to-left script detection and improved display for right-to-left - script text (as determined line by line). - -- On-page support for some scripts that are often not pre-installed on users' - computers (Burmese, Egyptian, Klingon). - -Changes in version 1.0 (major upgrade) - * Upgraded principal internal data structure from string to lattice. - * Improvements mostly in vowelization of South and Southeast Asian languages. - * Vocalic 'r' more consistently treated as vowel (no additional vowel added). - * Repetition signs (Japanese/Chinese/Thai/Khmer/Lao) are mapped to superscript 2. - * Japanese Katakana middle dots now mapped to ASCII space. - * Tibetan intersyllabic mark now mapped to middle dot (U+00B7). - * Some corrections regarding analysis of Chinese numbers. - * Many more foreign diacritics and punctuation marks dropped or mapped to ASCII. - * Zero-width characters dropped, except line/sentence-initial byte order marks. - * Spaces normalized to ASCII space. - * Fixed bug that in some cases mapped signs (such as dagger or bullet) to their verbal descriptions. - * Tested against previous version of uroman with a new uroman visual diff tool. - * Almost an order of magnitude faster. - -Changes in version 0.7 (minor upgrade) - * Added script uroman-quick.pl for Arabic script languages, incl. Uyghur. - Much faster, pre-caching mapping of Arabic to Latin characters, simple greedy processing. - Will not convert material from non-Arabic blocks such as any (somewhat unusual) Cyrillic - or Chinese characters in Uyghur texts. - -Changes in version 0.6 (minor upgrade) - * Added support for two letter characters used in Uzbek: - (1) character "ʻ" ("modifier letter turned comma", which modifies preceding "g" and "u" letters) - (2) character "ʼ" ("modifier letter apostrophe", which Uzbek uses to mark a glottal stop). - Both are now mapped to "'" (plain ASCII apostrophe). - * Added support for Uyghur vowel characters such as "ې" (Arabic e) and "ۆ" (Arabic oe) - even when they are not preceded by "ئ" (yeh with hamza above). - * Added support for Arabic semicolon "؛", Arabic ligature forms for phrases such as "ﷺ" - ("sallallahou alayhe wasallam" = "prayer of God be upon him and his family and peace") - * Added robustness for Arabic letter presentation forms (initial/medial/final/isolated). - However, it is strongly recommended to normalize any presentation form Arabic letters - to their non-presentation form before calling uroman. - * Added force flush directive ($|=1;). - -Changes in version 0.5 (minor upgrade) - * Improvements for Uyghur (make sure to use language option: -l uig) - -Changes in version 0.4 (minor upgrade) - * Improvements for Thai (special cases for vowel/consonant reordering, e.g. for "sara o"; dropped some aspiration 'h's) - * Minor change for Arabic (added "alef+fathatan" = "an") - -New features in version 0.3 - * Covers Mandarin (Chinese) - * Improved romanization for numerous languages - * Preserves capitalization (e.g. from Latin, Cyrillic, Greek scripts) - * Maps from native digits to Western numbers - * Faster for South Asian languages - -### Other features - * Web interface: http://www.isi.edu/~ulf/uroman.html - * Vowelization is provided when locally computable, e.g. for many South Asian languages and Tibetan. - -### Limitations - * The current version of uroman has a few limitations, some of which we plan to address in future versions. - For Japanese, *uroman* currently romanizes hiragana and katakana as expected, but kanji are interpreted as Chinese characters and romanized as such. - For Egyptian hieroglyphs, only single-sound phonetic characters and numbers are currently romanized. - For Linear B, only phonetic syllabic characters are romanized. - For some other extinct scripts such as cuneiform, no romanization is provided. - * A romanizer is not a full transliterator. For example, this version of - uroman does not vowelize text that lacks explicit vowelization such as - normal text in Arabic and Hebrew (without diacritics/points). - -### Acknowledgments -This research is based upon work supported in part by the Office of the Director of National Intelligence (ODNI), Intelligence Advanced Research Projects Activity (IARPA), via contract # FA8650-17-C-9116, and by research sponsored by Air Force Research Laboratory (AFRL) under agreement number FA8750-19-1-1000. The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies, either expressed or implied, of ODNI, IARPA, Air Force Laboratory, DARPA, or the U.S. Government. The U.S. Government is authorized to reproduce and distribute reprints for governmental purposes notwithstanding any copyright annotation therein. diff --git a/spaces/kazuk/youtube-whisper-11/app.py b/spaces/kazuk/youtube-whisper-11/app.py deleted file mode 100644 index 4a61dc561a016c53ad93a3c556b0ef7bafa964eb..0000000000000000000000000000000000000000 --- a/spaces/kazuk/youtube-whisper-11/app.py +++ /dev/null @@ -1,66 +0,0 @@ -import gradio as gr -import whisper -from pytube import YouTube - -def get_audio(url): - yt = YouTube(url) - return yt.streams.filter(only_audio=True)[0].download(filename="tmp.mp4") - -def get_transcript(url, model_size, lang, format): - - model = whisper.load_model(model_size) - - if lang == "None": - lang = None - - result = model.transcribe(get_audio(url), fp16=False, language=lang) - - if format == "None": - return result["text"] - elif format == ".srt": - return format_to_srt(result["segments"]) - -def format_to_srt(segments): - output = "" - for i, segment in enumerate(segments): - output += f"{i + 1}\n" - output += f"{format_timestamp(segment['start'])} --> {format_timestamp(segment['end'])}\n" - output += f"{segment['text']}\n\n" - return output - -def format_timestamp(t): - hh = t//3600 - mm = (t - hh*3600)//60 - ss = t - hh*3600 - mm*60 - mi = (t - int(t))*1000 - return f"{int(hh):02d}:{int(mm):02d}:{int(ss):02d},{int(mi):03d}" - - -langs = ["None"] + sorted(list(whisper.tokenizer.LANGUAGES.values())) -model_size = list(whisper._MODELS.keys()) - -with gr.Blocks() as demo: - - with gr.Row(): - - with gr.Column(): - - with gr.Row(): - url = gr.Textbox(placeholder='Youtube video URL', label='URL') - - with gr.Row(): - - model_size = gr.Dropdown(choices=model_size, value='tiny', label="Model") - lang = gr.Dropdown(choices=langs, value="None", label="Language (Optional)") - format = gr.Dropdown(choices=["None", ".srt"], value="None", label="Timestamps? (Optional)") - - with gr.Row(): - gr.Markdown("Larger models are more accurate, but slower. For 1min video, it'll take ~30s (tiny), ~1min (base), ~3min (small), ~5min (medium), etc.") - transcribe_btn = gr.Button('Transcribe') - - with gr.Column(): - outputs = gr.Textbox(placeholder='Transcription of the video', label='Transcription') - - transcribe_btn.click(get_transcript, inputs=[url, model_size, lang, format], outputs=outputs) - -demo.launch(debug=True) diff --git a/spaces/keras-io/NeRF/README.md b/spaces/keras-io/NeRF/README.md deleted file mode 100644 index 3179e2b9e6db233cea79e2c419e9cca07e8baf92..0000000000000000000000000000000000000000 --- a/spaces/keras-io/NeRF/README.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: NeRF -emoji: 🔮 -colorFrom: red -colorTo: red -sdk: streamlit -app_file: app.py -pinned: false -license: afl-3.0 ---- - -# 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/kevinwang676/ChatGLM2-SadTalker-VC/src/face3d/models/facerecon_model.py b/spaces/kevinwang676/ChatGLM2-SadTalker-VC/src/face3d/models/facerecon_model.py deleted file mode 100644 index 7de8ca6eebc50ff1ed52c5ba37d31b43f977b5e1..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/ChatGLM2-SadTalker-VC/src/face3d/models/facerecon_model.py +++ /dev/null @@ -1,220 +0,0 @@ -"""This script defines the face reconstruction model for Deep3DFaceRecon_pytorch -""" - -import numpy as np -import torch -from src.face3d.models.base_model import BaseModel -from src.face3d.models import networks -from src.face3d.models.bfm import ParametricFaceModel -from src.face3d.models.losses import perceptual_loss, photo_loss, reg_loss, reflectance_loss, landmark_loss -from src.face3d.util import util -from src.face3d.util.nvdiffrast import MeshRenderer -# from src.face3d.util.preprocess import estimate_norm_torch - -import trimesh -from scipy.io import savemat - -class FaceReconModel(BaseModel): - - @staticmethod - def modify_commandline_options(parser, is_train=False): - """ Configures options specific for CUT model - """ - # net structure and parameters - parser.add_argument('--net_recon', type=str, default='resnet50', choices=['resnet18', 'resnet34', 'resnet50'], help='network structure') - parser.add_argument('--init_path', type=str, default='./checkpoints/init_model/resnet50-0676ba61.pth') - parser.add_argument('--use_last_fc', type=util.str2bool, nargs='?', const=True, default=False, help='zero initialize the last fc') - parser.add_argument('--bfm_folder', type=str, default='./checkpoints/BFM_Fitting/') - parser.add_argument('--bfm_model', type=str, default='BFM_model_front.mat', help='bfm model') - - # renderer parameters - parser.add_argument('--focal', type=float, default=1015.) - parser.add_argument('--center', type=float, default=112.) - parser.add_argument('--camera_d', type=float, default=10.) - parser.add_argument('--z_near', type=float, default=5.) - parser.add_argument('--z_far', type=float, default=15.) - - if is_train: - # training parameters - parser.add_argument('--net_recog', type=str, default='r50', choices=['r18', 'r43', 'r50'], help='face recog network structure') - parser.add_argument('--net_recog_path', type=str, default='checkpoints/recog_model/ms1mv3_arcface_r50_fp16/backbone.pth') - parser.add_argument('--use_crop_face', type=util.str2bool, nargs='?', const=True, default=False, help='use crop mask for photo loss') - parser.add_argument('--use_predef_M', type=util.str2bool, nargs='?', const=True, default=False, help='use predefined M for predicted face') - - - # augmentation parameters - parser.add_argument('--shift_pixs', type=float, default=10., help='shift pixels') - parser.add_argument('--scale_delta', type=float, default=0.1, help='delta scale factor') - parser.add_argument('--rot_angle', type=float, default=10., help='rot angles, degree') - - # loss weights - parser.add_argument('--w_feat', type=float, default=0.2, help='weight for feat loss') - parser.add_argument('--w_color', type=float, default=1.92, help='weight for loss loss') - parser.add_argument('--w_reg', type=float, default=3.0e-4, help='weight for reg loss') - parser.add_argument('--w_id', type=float, default=1.0, help='weight for id_reg loss') - parser.add_argument('--w_exp', type=float, default=0.8, help='weight for exp_reg loss') - parser.add_argument('--w_tex', type=float, default=1.7e-2, help='weight for tex_reg loss') - parser.add_argument('--w_gamma', type=float, default=10.0, help='weight for gamma loss') - parser.add_argument('--w_lm', type=float, default=1.6e-3, help='weight for lm loss') - parser.add_argument('--w_reflc', type=float, default=5.0, help='weight for reflc loss') - - opt, _ = parser.parse_known_args() - parser.set_defaults( - focal=1015., center=112., camera_d=10., use_last_fc=False, z_near=5., z_far=15. - ) - if is_train: - parser.set_defaults( - use_crop_face=True, use_predef_M=False - ) - return parser - - def __init__(self, opt): - """Initialize this model class. - - Parameters: - opt -- training/test options - - A few things can be done here. - - (required) call the initialization function of BaseModel - - define loss function, visualization images, model names, and optimizers - """ - BaseModel.__init__(self, opt) # call the initialization method of BaseModel - - self.visual_names = ['output_vis'] - self.model_names = ['net_recon'] - self.parallel_names = self.model_names + ['renderer'] - - self.facemodel = ParametricFaceModel( - bfm_folder=opt.bfm_folder, camera_distance=opt.camera_d, focal=opt.focal, center=opt.center, - is_train=self.isTrain, default_name=opt.bfm_model - ) - - fov = 2 * np.arctan(opt.center / opt.focal) * 180 / np.pi - self.renderer = MeshRenderer( - rasterize_fov=fov, znear=opt.z_near, zfar=opt.z_far, rasterize_size=int(2 * opt.center) - ) - - if self.isTrain: - self.loss_names = ['all', 'feat', 'color', 'lm', 'reg', 'gamma', 'reflc'] - - self.net_recog = networks.define_net_recog( - net_recog=opt.net_recog, pretrained_path=opt.net_recog_path - ) - # loss func name: (compute_%s_loss) % loss_name - self.compute_feat_loss = perceptual_loss - self.comupte_color_loss = photo_loss - self.compute_lm_loss = landmark_loss - self.compute_reg_loss = reg_loss - self.compute_reflc_loss = reflectance_loss - - self.optimizer = torch.optim.Adam(self.net_recon.parameters(), lr=opt.lr) - self.optimizers = [self.optimizer] - self.parallel_names += ['net_recog'] - # Our program will automatically call to define schedulers, load networks, and print networks - - def set_input(self, input): - """Unpack input data from the dataloader and perform necessary pre-processing steps. - - Parameters: - input: a dictionary that contains the data itself and its metadata information. - """ - self.input_img = input['imgs'].to(self.device) - self.atten_mask = input['msks'].to(self.device) if 'msks' in input else None - self.gt_lm = input['lms'].to(self.device) if 'lms' in input else None - self.trans_m = input['M'].to(self.device) if 'M' in input else None - self.image_paths = input['im_paths'] if 'im_paths' in input else None - - def forward(self, output_coeff, device): - self.facemodel.to(device) - self.pred_vertex, self.pred_tex, self.pred_color, self.pred_lm = \ - self.facemodel.compute_for_render(output_coeff) - self.pred_mask, _, self.pred_face = self.renderer( - self.pred_vertex, self.facemodel.face_buf, feat=self.pred_color) - - self.pred_coeffs_dict = self.facemodel.split_coeff(output_coeff) - - - def compute_losses(self): - """Calculate losses, gradients, and update network weights; called in every training iteration""" - - assert self.net_recog.training == False - trans_m = self.trans_m - if not self.opt.use_predef_M: - trans_m = estimate_norm_torch(self.pred_lm, self.input_img.shape[-2]) - - pred_feat = self.net_recog(self.pred_face, trans_m) - gt_feat = self.net_recog(self.input_img, self.trans_m) - self.loss_feat = self.opt.w_feat * self.compute_feat_loss(pred_feat, gt_feat) - - face_mask = self.pred_mask - if self.opt.use_crop_face: - face_mask, _, _ = self.renderer(self.pred_vertex, self.facemodel.front_face_buf) - - face_mask = face_mask.detach() - self.loss_color = self.opt.w_color * self.comupte_color_loss( - self.pred_face, self.input_img, self.atten_mask * face_mask) - - loss_reg, loss_gamma = self.compute_reg_loss(self.pred_coeffs_dict, self.opt) - self.loss_reg = self.opt.w_reg * loss_reg - self.loss_gamma = self.opt.w_gamma * loss_gamma - - self.loss_lm = self.opt.w_lm * self.compute_lm_loss(self.pred_lm, self.gt_lm) - - self.loss_reflc = self.opt.w_reflc * self.compute_reflc_loss(self.pred_tex, self.facemodel.skin_mask) - - self.loss_all = self.loss_feat + self.loss_color + self.loss_reg + self.loss_gamma \ - + self.loss_lm + self.loss_reflc - - - def optimize_parameters(self, isTrain=True): - self.forward() - self.compute_losses() - """Update network weights; it will be called in every training iteration.""" - if isTrain: - self.optimizer.zero_grad() - self.loss_all.backward() - self.optimizer.step() - - def compute_visuals(self): - with torch.no_grad(): - input_img_numpy = 255. * self.input_img.detach().cpu().permute(0, 2, 3, 1).numpy() - output_vis = self.pred_face * self.pred_mask + (1 - self.pred_mask) * self.input_img - output_vis_numpy_raw = 255. * output_vis.detach().cpu().permute(0, 2, 3, 1).numpy() - - if self.gt_lm is not None: - gt_lm_numpy = self.gt_lm.cpu().numpy() - pred_lm_numpy = self.pred_lm.detach().cpu().numpy() - output_vis_numpy = util.draw_landmarks(output_vis_numpy_raw, gt_lm_numpy, 'b') - output_vis_numpy = util.draw_landmarks(output_vis_numpy, pred_lm_numpy, 'r') - - output_vis_numpy = np.concatenate((input_img_numpy, - output_vis_numpy_raw, output_vis_numpy), axis=-2) - else: - output_vis_numpy = np.concatenate((input_img_numpy, - output_vis_numpy_raw), axis=-2) - - self.output_vis = torch.tensor( - output_vis_numpy / 255., dtype=torch.float32 - ).permute(0, 3, 1, 2).to(self.device) - - def save_mesh(self, name): - - recon_shape = self.pred_vertex # get reconstructed shape - recon_shape[..., -1] = 10 - recon_shape[..., -1] # from camera space to world space - recon_shape = recon_shape.cpu().numpy()[0] - recon_color = self.pred_color - recon_color = recon_color.cpu().numpy()[0] - tri = self.facemodel.face_buf.cpu().numpy() - mesh = trimesh.Trimesh(vertices=recon_shape, faces=tri, vertex_colors=np.clip(255. * recon_color, 0, 255).astype(np.uint8)) - mesh.export(name) - - def save_coeff(self,name): - - pred_coeffs = {key:self.pred_coeffs_dict[key].cpu().numpy() for key in self.pred_coeffs_dict} - pred_lm = self.pred_lm.cpu().numpy() - pred_lm = np.stack([pred_lm[:,:,0],self.input_img.shape[2]-1-pred_lm[:,:,1]],axis=2) # transfer to image coordinate - pred_coeffs['lm68'] = pred_lm - savemat(name,pred_coeffs) - - - diff --git a/spaces/kevinwang676/Personal-TTS/README.md b/spaces/kevinwang676/Personal-TTS/README.md deleted file mode 100644 index 77fc40099497bb6a67326ecc95a221482abcd9ce..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/Personal-TTS/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Personal TTS -emoji: 🐨 -colorFrom: red -colorTo: indigo -sdk: gradio -sdk_version: 3.36.1 -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/kevinwang676/SadTalker/src/face3d/options/test_options.py b/spaces/kevinwang676/SadTalker/src/face3d/options/test_options.py deleted file mode 100644 index 4ff3ad142779850d1d5a1640bc00f70d34d4a862..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/SadTalker/src/face3d/options/test_options.py +++ /dev/null @@ -1,21 +0,0 @@ -"""This script contains the test options for Deep3DFaceRecon_pytorch -""" - -from .base_options import BaseOptions - - -class TestOptions(BaseOptions): - """This class includes test options. - - It also includes shared options defined in BaseOptions. - """ - - def initialize(self, parser): - parser = BaseOptions.initialize(self, parser) # define shared options - parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc') - parser.add_argument('--dataset_mode', type=str, default=None, help='chooses how datasets are loaded. [None | flist]') - parser.add_argument('--img_folder', type=str, default='examples', help='folder for test images.') - - # Dropout and Batchnorm has different behavior during training and test. - self.isTrain = False - return parser diff --git a/spaces/kira4424/Tacotron-zero-short-voice-clone/encoder_train.py b/spaces/kira4424/Tacotron-zero-short-voice-clone/encoder_train.py deleted file mode 100644 index b8740a894d615aadfe529cb36068fc8e3496125f..0000000000000000000000000000000000000000 --- a/spaces/kira4424/Tacotron-zero-short-voice-clone/encoder_train.py +++ /dev/null @@ -1,47 +0,0 @@ -from utils.argutils import print_args -from encoder.train import train -from pathlib import Path -import argparse - - -if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="Trains the speaker encoder. You must have run encoder_preprocess.py first.", - formatter_class=argparse.ArgumentDefaultsHelpFormatter - ) - - parser.add_argument("run_id", type=str, help= \ - "Name for this model instance. If a model state from the same run ID was previously " - "saved, the training will restart from there. Pass -f to overwrite saved states and " - "restart from scratch.") - parser.add_argument("clean_data_root", type=Path, help= \ - "Path to the output directory of encoder_preprocess.py. If you left the default " - "output directory when preprocessing, it should be /SV2TTS/encoder/.") - parser.add_argument("-m", "--models_dir", type=Path, default="encoder/saved_models/", help=\ - "Path to the output directory that will contain the saved model weights, as well as " - "backups of those weights and plots generated during training.") - parser.add_argument("-v", "--vis_every", type=int, default=10, help= \ - "Number of steps between updates of the loss and the plots.") - parser.add_argument("-u", "--umap_every", type=int, default=100, help= \ - "Number of steps between updates of the umap projection. Set to 0 to never update the " - "projections.") - parser.add_argument("-s", "--save_every", type=int, default=500, help= \ - "Number of steps between updates of the model on the disk. Set to 0 to never save the " - "model.") - parser.add_argument("-b", "--backup_every", type=int, default=7500, help= \ - "Number of steps between backups of the model. Set to 0 to never make backups of the " - "model.") - parser.add_argument("-f", "--force_restart", action="store_true", help= \ - "Do not load any saved model.") - parser.add_argument("--visdom_server", type=str, default="http://localhost") - parser.add_argument("--no_visdom", action="store_true", help= \ - "Disable visdom.") - args = parser.parse_args() - - # Process the arguments - args.models_dir.mkdir(exist_ok=True) - - # Run the training - print_args(args, parser) - train(**vars(args)) - \ No newline at end of file diff --git a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/__init__.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/__init__.py deleted file mode 100644 index 52e4b48d383a84a055dcd7f6236f6e8e58eab924..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/__init__.py +++ /dev/null @@ -1,47 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from .base_module import BaseModule, ModuleList, Sequential -from .base_runner import BaseRunner -from .builder import RUNNERS, build_runner -from .checkpoint import (CheckpointLoader, _load_checkpoint, - _load_checkpoint_with_prefix, load_checkpoint, - load_state_dict, save_checkpoint, weights_to_cpu) -from .default_constructor import DefaultRunnerConstructor -from .dist_utils import (allreduce_grads, allreduce_params, get_dist_info, - init_dist, master_only) -from .epoch_based_runner import EpochBasedRunner, Runner -from .fp16_utils import LossScaler, auto_fp16, force_fp32, wrap_fp16_model -from .hooks import (HOOKS, CheckpointHook, ClosureHook, DistEvalHook, - DistSamplerSeedHook, DvcliveLoggerHook, EMAHook, EvalHook, - Fp16OptimizerHook, GradientCumulativeFp16OptimizerHook, - GradientCumulativeOptimizerHook, Hook, IterTimerHook, - LoggerHook, LrUpdaterHook, MlflowLoggerHook, - NeptuneLoggerHook, OptimizerHook, PaviLoggerHook, - SyncBuffersHook, TensorboardLoggerHook, TextLoggerHook, - WandbLoggerHook) -from .iter_based_runner import IterBasedRunner, IterLoader -from .log_buffer import LogBuffer -from .optimizer import (OPTIMIZER_BUILDERS, OPTIMIZERS, - DefaultOptimizerConstructor, build_optimizer, - build_optimizer_constructor) -from .priority import Priority, get_priority -from .utils import get_host_info, get_time_str, obj_from_dict, set_random_seed - -__all__ = [ - 'BaseRunner', 'Runner', 'EpochBasedRunner', 'IterBasedRunner', 'LogBuffer', - 'HOOKS', 'Hook', 'CheckpointHook', 'ClosureHook', 'LrUpdaterHook', - 'OptimizerHook', 'IterTimerHook', 'DistSamplerSeedHook', 'LoggerHook', - 'PaviLoggerHook', 'TextLoggerHook', 'TensorboardLoggerHook', - 'NeptuneLoggerHook', 'WandbLoggerHook', 'MlflowLoggerHook', - 'DvcliveLoggerHook', '_load_checkpoint', 'load_state_dict', - 'load_checkpoint', 'weights_to_cpu', 'save_checkpoint', 'Priority', - 'get_priority', 'get_host_info', 'get_time_str', 'obj_from_dict', - 'init_dist', 'get_dist_info', 'master_only', 'OPTIMIZER_BUILDERS', - 'OPTIMIZERS', 'DefaultOptimizerConstructor', 'build_optimizer', - 'build_optimizer_constructor', 'IterLoader', 'set_random_seed', - 'auto_fp16', 'force_fp32', 'wrap_fp16_model', 'Fp16OptimizerHook', - 'SyncBuffersHook', 'EMAHook', 'build_runner', 'RUNNERS', 'allreduce_grads', - 'allreduce_params', 'LossScaler', 'CheckpointLoader', 'BaseModule', - '_load_checkpoint_with_prefix', 'EvalHook', 'DistEvalHook', 'Sequential', - 'ModuleList', 'GradientCumulativeOptimizerHook', - 'GradientCumulativeFp16OptimizerHook', 'DefaultRunnerConstructor' -] diff --git a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/base_runner.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/base_runner.py deleted file mode 100644 index 4928db0a73b56fe0218a4bf66ec4ffa082d31ccc..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/base_runner.py +++ /dev/null @@ -1,542 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import copy -import logging -import os.path as osp -import warnings -from abc import ABCMeta, abstractmethod - -import torch -from torch.optim import Optimizer - -import annotator.uniformer.mmcv as mmcv -from ..parallel import is_module_wrapper -from .checkpoint import load_checkpoint -from .dist_utils import get_dist_info -from .hooks import HOOKS, Hook -from .log_buffer import LogBuffer -from .priority import Priority, get_priority -from .utils import get_time_str - - -class BaseRunner(metaclass=ABCMeta): - """The base class of Runner, a training helper for PyTorch. - - All subclasses should implement the following APIs: - - - ``run()`` - - ``train()`` - - ``val()`` - - ``save_checkpoint()`` - - Args: - model (:obj:`torch.nn.Module`): The model to be run. - batch_processor (callable): A callable method that process a data - batch. The interface of this method should be - `batch_processor(model, data, train_mode) -> dict` - optimizer (dict or :obj:`torch.optim.Optimizer`): It can be either an - optimizer (in most cases) or a dict of optimizers (in models that - requires more than one optimizer, e.g., GAN). - work_dir (str, optional): The working directory to save checkpoints - and logs. Defaults to None. - logger (:obj:`logging.Logger`): Logger used during training. - Defaults to None. (The default value is just for backward - compatibility) - meta (dict | None): A dict records some import information such as - environment info and seed, which will be logged in logger hook. - Defaults to None. - max_epochs (int, optional): Total training epochs. - max_iters (int, optional): Total training iterations. - """ - - def __init__(self, - model, - batch_processor=None, - optimizer=None, - work_dir=None, - logger=None, - meta=None, - max_iters=None, - max_epochs=None): - if batch_processor is not None: - if not callable(batch_processor): - raise TypeError('batch_processor must be callable, ' - f'but got {type(batch_processor)}') - warnings.warn('batch_processor is deprecated, please implement ' - 'train_step() and val_step() in the model instead.') - # raise an error is `batch_processor` is not None and - # `model.train_step()` exists. - if is_module_wrapper(model): - _model = model.module - else: - _model = model - if hasattr(_model, 'train_step') or hasattr(_model, 'val_step'): - raise RuntimeError( - 'batch_processor and model.train_step()/model.val_step() ' - 'cannot be both available.') - else: - assert hasattr(model, 'train_step') - - # check the type of `optimizer` - if isinstance(optimizer, dict): - for name, optim in optimizer.items(): - if not isinstance(optim, Optimizer): - raise TypeError( - f'optimizer must be a dict of torch.optim.Optimizers, ' - f'but optimizer["{name}"] is a {type(optim)}') - elif not isinstance(optimizer, Optimizer) and optimizer is not None: - raise TypeError( - f'optimizer must be a torch.optim.Optimizer object ' - f'or dict or None, but got {type(optimizer)}') - - # check the type of `logger` - if not isinstance(logger, logging.Logger): - raise TypeError(f'logger must be a logging.Logger object, ' - f'but got {type(logger)}') - - # check the type of `meta` - if meta is not None and not isinstance(meta, dict): - raise TypeError( - f'meta must be a dict or None, but got {type(meta)}') - - self.model = model - self.batch_processor = batch_processor - self.optimizer = optimizer - self.logger = logger - self.meta = meta - # create work_dir - if mmcv.is_str(work_dir): - self.work_dir = osp.abspath(work_dir) - mmcv.mkdir_or_exist(self.work_dir) - elif work_dir is None: - self.work_dir = None - else: - raise TypeError('"work_dir" must be a str or None') - - # get model name from the model class - if hasattr(self.model, 'module'): - self._model_name = self.model.module.__class__.__name__ - else: - self._model_name = self.model.__class__.__name__ - - self._rank, self._world_size = get_dist_info() - self.timestamp = get_time_str() - self.mode = None - self._hooks = [] - self._epoch = 0 - self._iter = 0 - self._inner_iter = 0 - - if max_epochs is not None and max_iters is not None: - raise ValueError( - 'Only one of `max_epochs` or `max_iters` can be set.') - - self._max_epochs = max_epochs - self._max_iters = max_iters - # TODO: Redesign LogBuffer, it is not flexible and elegant enough - self.log_buffer = LogBuffer() - - @property - def model_name(self): - """str: Name of the model, usually the module class name.""" - return self._model_name - - @property - def rank(self): - """int: Rank of current process. (distributed training)""" - return self._rank - - @property - def world_size(self): - """int: Number of processes participating in the job. - (distributed training)""" - return self._world_size - - @property - def hooks(self): - """list[:obj:`Hook`]: A list of registered hooks.""" - return self._hooks - - @property - def epoch(self): - """int: Current epoch.""" - return self._epoch - - @property - def iter(self): - """int: Current iteration.""" - return self._iter - - @property - def inner_iter(self): - """int: Iteration in an epoch.""" - return self._inner_iter - - @property - def max_epochs(self): - """int: Maximum training epochs.""" - return self._max_epochs - - @property - def max_iters(self): - """int: Maximum training iterations.""" - return self._max_iters - - @abstractmethod - def train(self): - pass - - @abstractmethod - def val(self): - pass - - @abstractmethod - def run(self, data_loaders, workflow, **kwargs): - pass - - @abstractmethod - def save_checkpoint(self, - out_dir, - filename_tmpl, - save_optimizer=True, - meta=None, - create_symlink=True): - pass - - def current_lr(self): - """Get current learning rates. - - Returns: - list[float] | dict[str, list[float]]: Current learning rates of all - param groups. If the runner has a dict of optimizers, this - method will return a dict. - """ - if isinstance(self.optimizer, torch.optim.Optimizer): - lr = [group['lr'] for group in self.optimizer.param_groups] - elif isinstance(self.optimizer, dict): - lr = dict() - for name, optim in self.optimizer.items(): - lr[name] = [group['lr'] for group in optim.param_groups] - else: - raise RuntimeError( - 'lr is not applicable because optimizer does not exist.') - return lr - - def current_momentum(self): - """Get current momentums. - - Returns: - list[float] | dict[str, list[float]]: Current momentums of all - param groups. If the runner has a dict of optimizers, this - method will return a dict. - """ - - def _get_momentum(optimizer): - momentums = [] - for group in optimizer.param_groups: - if 'momentum' in group.keys(): - momentums.append(group['momentum']) - elif 'betas' in group.keys(): - momentums.append(group['betas'][0]) - else: - momentums.append(0) - return momentums - - if self.optimizer is None: - raise RuntimeError( - 'momentum is not applicable because optimizer does not exist.') - elif isinstance(self.optimizer, torch.optim.Optimizer): - momentums = _get_momentum(self.optimizer) - elif isinstance(self.optimizer, dict): - momentums = dict() - for name, optim in self.optimizer.items(): - momentums[name] = _get_momentum(optim) - return momentums - - def register_hook(self, hook, priority='NORMAL'): - """Register a hook into the hook list. - - The hook will be inserted into a priority queue, with the specified - priority (See :class:`Priority` for details of priorities). - For hooks with the same priority, they will be triggered in the same - order as they are registered. - - Args: - hook (:obj:`Hook`): The hook to be registered. - priority (int or str or :obj:`Priority`): Hook priority. - Lower value means higher priority. - """ - assert isinstance(hook, Hook) - if hasattr(hook, 'priority'): - raise ValueError('"priority" is a reserved attribute for hooks') - priority = get_priority(priority) - hook.priority = priority - # insert the hook to a sorted list - inserted = False - for i in range(len(self._hooks) - 1, -1, -1): - if priority >= self._hooks[i].priority: - self._hooks.insert(i + 1, hook) - inserted = True - break - if not inserted: - self._hooks.insert(0, hook) - - def register_hook_from_cfg(self, hook_cfg): - """Register a hook from its cfg. - - Args: - hook_cfg (dict): Hook config. It should have at least keys 'type' - and 'priority' indicating its type and priority. - - Notes: - The specific hook class to register should not use 'type' and - 'priority' arguments during initialization. - """ - hook_cfg = hook_cfg.copy() - priority = hook_cfg.pop('priority', 'NORMAL') - hook = mmcv.build_from_cfg(hook_cfg, HOOKS) - self.register_hook(hook, priority=priority) - - def call_hook(self, fn_name): - """Call all hooks. - - Args: - fn_name (str): The function name in each hook to be called, such as - "before_train_epoch". - """ - for hook in self._hooks: - getattr(hook, fn_name)(self) - - def get_hook_info(self): - # Get hooks info in each stage - stage_hook_map = {stage: [] for stage in Hook.stages} - for hook in self.hooks: - try: - priority = Priority(hook.priority).name - except ValueError: - priority = hook.priority - classname = hook.__class__.__name__ - hook_info = f'({priority:<12}) {classname:<35}' - for trigger_stage in hook.get_triggered_stages(): - stage_hook_map[trigger_stage].append(hook_info) - - stage_hook_infos = [] - for stage in Hook.stages: - hook_infos = stage_hook_map[stage] - if len(hook_infos) > 0: - info = f'{stage}:\n' - info += '\n'.join(hook_infos) - info += '\n -------------------- ' - stage_hook_infos.append(info) - return '\n'.join(stage_hook_infos) - - def load_checkpoint(self, - filename, - map_location='cpu', - strict=False, - revise_keys=[(r'^module.', '')]): - return load_checkpoint( - self.model, - filename, - map_location, - strict, - self.logger, - revise_keys=revise_keys) - - def resume(self, - checkpoint, - resume_optimizer=True, - map_location='default'): - if map_location == 'default': - if torch.cuda.is_available(): - device_id = torch.cuda.current_device() - checkpoint = self.load_checkpoint( - checkpoint, - map_location=lambda storage, loc: storage.cuda(device_id)) - else: - checkpoint = self.load_checkpoint(checkpoint) - else: - checkpoint = self.load_checkpoint( - checkpoint, map_location=map_location) - - self._epoch = checkpoint['meta']['epoch'] - self._iter = checkpoint['meta']['iter'] - if self.meta is None: - self.meta = {} - self.meta.setdefault('hook_msgs', {}) - # load `last_ckpt`, `best_score`, `best_ckpt`, etc. for hook messages - self.meta['hook_msgs'].update(checkpoint['meta'].get('hook_msgs', {})) - - # Re-calculate the number of iterations when resuming - # models with different number of GPUs - if 'config' in checkpoint['meta']: - config = mmcv.Config.fromstring( - checkpoint['meta']['config'], file_format='.py') - previous_gpu_ids = config.get('gpu_ids', None) - if previous_gpu_ids and len(previous_gpu_ids) > 0 and len( - previous_gpu_ids) != self.world_size: - self._iter = int(self._iter * len(previous_gpu_ids) / - self.world_size) - self.logger.info('the iteration number is changed due to ' - 'change of GPU number') - - # resume meta information meta - self.meta = checkpoint['meta'] - - if 'optimizer' in checkpoint and resume_optimizer: - if isinstance(self.optimizer, Optimizer): - self.optimizer.load_state_dict(checkpoint['optimizer']) - elif isinstance(self.optimizer, dict): - for k in self.optimizer.keys(): - self.optimizer[k].load_state_dict( - checkpoint['optimizer'][k]) - else: - raise TypeError( - 'Optimizer should be dict or torch.optim.Optimizer ' - f'but got {type(self.optimizer)}') - - self.logger.info('resumed epoch %d, iter %d', self.epoch, self.iter) - - def register_lr_hook(self, lr_config): - if lr_config is None: - return - elif isinstance(lr_config, dict): - assert 'policy' in lr_config - policy_type = lr_config.pop('policy') - # If the type of policy is all in lower case, e.g., 'cyclic', - # then its first letter will be capitalized, e.g., to be 'Cyclic'. - # This is for the convenient usage of Lr updater. - # Since this is not applicable for ` - # CosineAnnealingLrUpdater`, - # the string will not be changed if it contains capital letters. - if policy_type == policy_type.lower(): - policy_type = policy_type.title() - hook_type = policy_type + 'LrUpdaterHook' - lr_config['type'] = hook_type - hook = mmcv.build_from_cfg(lr_config, HOOKS) - else: - hook = lr_config - self.register_hook(hook, priority='VERY_HIGH') - - def register_momentum_hook(self, momentum_config): - if momentum_config is None: - return - if isinstance(momentum_config, dict): - assert 'policy' in momentum_config - policy_type = momentum_config.pop('policy') - # If the type of policy is all in lower case, e.g., 'cyclic', - # then its first letter will be capitalized, e.g., to be 'Cyclic'. - # This is for the convenient usage of momentum updater. - # Since this is not applicable for - # `CosineAnnealingMomentumUpdater`, - # the string will not be changed if it contains capital letters. - if policy_type == policy_type.lower(): - policy_type = policy_type.title() - hook_type = policy_type + 'MomentumUpdaterHook' - momentum_config['type'] = hook_type - hook = mmcv.build_from_cfg(momentum_config, HOOKS) - else: - hook = momentum_config - self.register_hook(hook, priority='HIGH') - - def register_optimizer_hook(self, optimizer_config): - if optimizer_config is None: - return - if isinstance(optimizer_config, dict): - optimizer_config.setdefault('type', 'OptimizerHook') - hook = mmcv.build_from_cfg(optimizer_config, HOOKS) - else: - hook = optimizer_config - self.register_hook(hook, priority='ABOVE_NORMAL') - - def register_checkpoint_hook(self, checkpoint_config): - if checkpoint_config is None: - return - if isinstance(checkpoint_config, dict): - checkpoint_config.setdefault('type', 'CheckpointHook') - hook = mmcv.build_from_cfg(checkpoint_config, HOOKS) - else: - hook = checkpoint_config - self.register_hook(hook, priority='NORMAL') - - def register_logger_hooks(self, log_config): - if log_config is None: - return - log_interval = log_config['interval'] - for info in log_config['hooks']: - logger_hook = mmcv.build_from_cfg( - info, HOOKS, default_args=dict(interval=log_interval)) - self.register_hook(logger_hook, priority='VERY_LOW') - - def register_timer_hook(self, timer_config): - if timer_config is None: - return - if isinstance(timer_config, dict): - timer_config_ = copy.deepcopy(timer_config) - hook = mmcv.build_from_cfg(timer_config_, HOOKS) - else: - hook = timer_config - self.register_hook(hook, priority='LOW') - - def register_custom_hooks(self, custom_config): - if custom_config is None: - return - - if not isinstance(custom_config, list): - custom_config = [custom_config] - - for item in custom_config: - if isinstance(item, dict): - self.register_hook_from_cfg(item) - else: - self.register_hook(item, priority='NORMAL') - - def register_profiler_hook(self, profiler_config): - if profiler_config is None: - return - if isinstance(profiler_config, dict): - profiler_config.setdefault('type', 'ProfilerHook') - hook = mmcv.build_from_cfg(profiler_config, HOOKS) - else: - hook = profiler_config - self.register_hook(hook) - - def register_training_hooks(self, - lr_config, - optimizer_config=None, - checkpoint_config=None, - log_config=None, - momentum_config=None, - timer_config=dict(type='IterTimerHook'), - custom_hooks_config=None): - """Register default and custom hooks for training. - - Default and custom hooks include: - - +----------------------+-------------------------+ - | Hooks | Priority | - +======================+=========================+ - | LrUpdaterHook | VERY_HIGH (10) | - +----------------------+-------------------------+ - | MomentumUpdaterHook | HIGH (30) | - +----------------------+-------------------------+ - | OptimizerStepperHook | ABOVE_NORMAL (40) | - +----------------------+-------------------------+ - | CheckpointSaverHook | NORMAL (50) | - +----------------------+-------------------------+ - | IterTimerHook | LOW (70) | - +----------------------+-------------------------+ - | LoggerHook(s) | VERY_LOW (90) | - +----------------------+-------------------------+ - | CustomHook(s) | defaults to NORMAL (50) | - +----------------------+-------------------------+ - - If custom hooks have same priority with default hooks, custom hooks - will be triggered after default hooks. - """ - self.register_lr_hook(lr_config) - self.register_momentum_hook(momentum_config) - self.register_optimizer_hook(optimizer_config) - self.register_checkpoint_hook(checkpoint_config) - self.register_timer_hook(timer_config) - self.register_logger_hooks(log_config) - self.register_custom_hooks(custom_hooks_config) diff --git a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/utils.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/utils.py deleted file mode 100644 index c5befb8e56ece50b5fecfd007b26f8a29124c0bd..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/runner/utils.py +++ /dev/null @@ -1,93 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import os -import random -import sys -import time -import warnings -from getpass import getuser -from socket import gethostname - -import numpy as np -import torch - -import annotator.uniformer.mmcv as mmcv - - -def get_host_info(): - """Get hostname and username. - - Return empty string if exception raised, e.g. ``getpass.getuser()`` will - lead to error in docker container - """ - host = '' - try: - host = f'{getuser()}@{gethostname()}' - except Exception as e: - warnings.warn(f'Host or user not found: {str(e)}') - finally: - return host - - -def get_time_str(): - return time.strftime('%Y%m%d_%H%M%S', time.localtime()) - - -def obj_from_dict(info, parent=None, default_args=None): - """Initialize an object from dict. - - The dict must contain the key "type", which indicates the object type, it - can be either a string or type, such as "list" or ``list``. Remaining - fields are treated as the arguments for constructing the object. - - Args: - info (dict): Object types and arguments. - parent (:class:`module`): Module which may containing expected object - classes. - default_args (dict, optional): Default arguments for initializing the - object. - - Returns: - any type: Object built from the dict. - """ - assert isinstance(info, dict) and 'type' in info - assert isinstance(default_args, dict) or default_args is None - args = info.copy() - obj_type = args.pop('type') - if mmcv.is_str(obj_type): - if parent is not None: - obj_type = getattr(parent, obj_type) - else: - obj_type = sys.modules[obj_type] - elif not isinstance(obj_type, type): - raise TypeError('type must be a str or valid type, but ' - f'got {type(obj_type)}') - if default_args is not None: - for name, value in default_args.items(): - args.setdefault(name, value) - return obj_type(**args) - - -def set_random_seed(seed, deterministic=False, use_rank_shift=False): - """Set random seed. - - Args: - seed (int): Seed to be used. - deterministic (bool): Whether to set the deterministic option for - CUDNN backend, i.e., set `torch.backends.cudnn.deterministic` - to True and `torch.backends.cudnn.benchmark` to False. - Default: False. - rank_shift (bool): Whether to add rank number to the random seed to - have different random seed in different threads. Default: False. - """ - if use_rank_shift: - rank, _ = mmcv.runner.get_dist_info() - seed += rank - random.seed(seed) - np.random.seed(seed) - torch.manual_seed(seed) - torch.cuda.manual_seed(seed) - torch.cuda.manual_seed_all(seed) - os.environ['PYTHONHASHSEED'] = str(seed) - if deterministic: - torch.backends.cudnn.deterministic = True - torch.backends.cudnn.benchmark = False diff --git a/spaces/kirch/Text2Video-Zero/app_text_to_video.py b/spaces/kirch/Text2Video-Zero/app_text_to_video.py deleted file mode 100644 index b2527b538ce940febc699795c498ff3bcfbeb634..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/app_text_to_video.py +++ /dev/null @@ -1,72 +0,0 @@ -import gradio as gr -from model import Model -from functools import partial - -examples = [ - ["an astronaut waving the arm on the moon"], - ["a sloth surfing on a wakeboard"], - ["an astronaut walking on a street"], - ["a cute cat walking on grass"], - ["a horse is galloping on a street"], - ["an astronaut is skiing down the hill"], - ["a gorilla walking alone down the street"], - ["a gorilla dancing on times square"], - ["A panda dancing dancing like crazy on Times Square"], - ] - - -def create_demo(model: Model): - - with gr.Blocks() as demo: - with gr.Row(): - gr.Markdown('## Text2Video-Zero: Video Generation') - with gr.Row(): - gr.HTML( - """ -
    -

    - Description: Simply input any textual prompt to generate videos right away and unleash your creativity and imagination! You can also select from the examples below. For performance purposes, our current preview release generates only 8 output frames and output 4s videos. -

    -
    - """) - - with gr.Row(): - with gr.Column(): - prompt = gr.Textbox(label='Prompt') - run_button = gr.Button(label='Run') - with gr.Accordion('Advanced options', open=False): - motion_field_strength_x = gr.Slider(label='Global Translation $\delta_{x}$', - minimum=-20, - maximum=20, - value=12, - step=1) - - motion_field_strength_y = gr.Slider(label='Global Translation $\delta_{y}$', - minimum=-20, - maximum=20, - value=12, - step=1) - # a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed') - n_prompt = gr.Textbox(label="Optional Negative Prompt", - value='') - with gr.Column(): - result = gr.Video(label="Generated Video") - inputs = [ - prompt, - motion_field_strength_x, - motion_field_strength_y, - n_prompt - ] - - gr.Examples(examples=examples, - inputs=inputs, - outputs=result, - fn=model.process_text2video, - cache_examples=True, - run_on_click=False, - ) - - run_button.click(fn=model.process_text2video, - inputs=inputs, - outputs=result,) - return demo diff --git a/spaces/koajoel/PolyFormer/fairseq/examples/flores101/README.md b/spaces/koajoel/PolyFormer/fairseq/examples/flores101/README.md deleted file mode 100644 index 635c13f40bd0ccab704735bc5c26ea0192ea98cd..0000000000000000000000000000000000000000 --- a/spaces/koajoel/PolyFormer/fairseq/examples/flores101/README.md +++ /dev/null @@ -1,223 +0,0 @@ -

    - -

    - -# Flores101: Large-Scale Multilingual Machine Translation - -## Introduction - -Baseline pretrained models for small and large tracks of WMT 21 Large-Scale Multilingual Machine Translation competition. - -Flores Task at WMT 21: http://www.statmt.org/wmt21/large-scale-multilingual-translation-task.html - -Flores announement blog post: https://ai.facebook.com/blog/flores-researchers-kick-off-multilingual-translation-challenge-at-wmt-and-call-for-compute-grants/ - - - -## Pretrained models - -Model | Num layers | Embed dimension | FFN dimension| Vocab Size | #params | Download ----|---|---|---|---|---|--- -`flores101_mm100_615M` | 12 | 1024 | 4096 | 256,000 | 615M | https://dl.fbaipublicfiles.com/flores101/pretrained_models/flores101_mm100_615M.tar.gz -`flores101_mm100_175M` | 6 | 512 | 2048 | 256,000 | 175M | https://dl.fbaipublicfiles.com/flores101/pretrained_models/flores101_mm100_175M.tar.gz - - -These models are trained similar to [M2M-100](https://arxiv.org/abs/2010.11125) with additional support for the languages that are part of the WMT Large-Scale Multilingual Machine Translation track. Full list of languages can be found at the bottom. - - -## Example Generation code - -### Download model, sentencepiece vocab - -```bash -fairseq=/path/to/fairseq -cd $fairseq - -# Download 615M param model. -wget https://dl.fbaipublicfiles.com/flores101/pretrained_models/flores101_mm100_615M.tar.gz - -# Extract -tar -xvzf flores101_mm100_615M.tar.gz -``` - -### Encode using our SentencePiece Model -Note: Install SentencePiece from [here](https://github.com/google/sentencepiece) - - -```bash -fairseq=/path/to/fairseq -cd $fairseq - -# Download example dataset From German to French -sacrebleu --echo src -l de-fr -t wmt19 | head -n 20 > raw_input.de-fr.de -sacrebleu --echo ref -l de-fr -t wmt19 | head -n 20 > raw_input.de-fr.fr - -for lang in de fr ; do - python scripts/spm_encode.py \ - --model flores101_mm100_615M/sentencepiece.bpe.model \ - --output_format=piece \ - --inputs=raw_input.de-fr.${lang} \ - --outputs=spm.de-fr.${lang} -done -``` - -### Binarization - -```bash -fairseq-preprocess \ - --source-lang de --target-lang fr \ - --testpref spm.de-fr \ - --thresholdsrc 0 --thresholdtgt 0 \ - --destdir data_bin \ - --srcdict flores101_mm100_615M/dict.txt --tgtdict flores101_mm100_615M/dict.txt -``` - -### Generation - - -```bash -fairseq-generate \ - data_bin \ - --batch-size 1 \ - --path flores101_mm100_615M/model.pt \ - --fixed-dictionary flores101_mm100_615M/dict.txt \ - -s de -t fr \ - --remove-bpe 'sentencepiece' \ - --beam 5 \ - --task translation_multi_simple_epoch \ - --lang-pairs flores101_mm100_615M/language_pairs.txt \ - --decoder-langtok --encoder-langtok src \ - --gen-subset test \ - --fp16 \ - --dataset-impl mmap \ - --distributed-world-size 1 --distributed-no-spawn -``` - -### Supported Languages and lang code - -Language | lang code ----|--- -Akrikaans | af -Amharic | am -Arabic | ar -Assamese | as -Asturian | ast -Aymara | ay -Azerbaijani | az -Bashkir | ba -Belarusian | be -Bulgarian | bg -Bengali | bn -Breton | br -Bosnian | bs -Catalan | ca -Cebuano | ceb -Chokwe | cjk -Czech | cs -Welsh | cy -Danish | da -German | de -Dyula| dyu -Greek | el -English | en -Spanish | es -Estonian | et -Persian | fa -Fulah | ff -Finnish | fi -French | fr -Western Frisian | fy -Irish | ga -Scottish Gaelic | gd -Galician | gl -Gujarati | gu -Hausa | ha -Hebrew | he -Hindi | hi -Croatian | hr -Haitian Creole | ht -Hungarian | hu -Armenian | hy -Indonesian | id -Igbo | ig -Iloko | ilo -Icelandic | is -Italian | it -Japanese | ja -Javanese | jv -Georgian | ka -Kachin | kac -Kamba | kam -Kabuverdianu | kea -Kongo | kg -Kazakh | kk -Central Khmer | km -Kimbundu | kmb -Northern Kurdish | kmr -Kannada | kn -Korean | ko -Kurdish | ku -Kyrgyz | ky -Luxembourgish | lb -Ganda | lg -Lingala | ln -Lao | lo -Lithuanian | lt -Luo | luo -Latvian | lv -Malagasy | mg -Maori | mi -Macedonian | mk -Malayalam | ml -Mongolian | mn -Marathi | mr -Malay | ms -Maltese | mt -Burmese | my -Nepali | ne -Dutch | nl -Norwegian | no -Northern Sotho | ns -Nyanja | ny -Occitan | oc -Oromo | om -Oriya | or -Punjabi | pa -Polish | pl -Pashto | ps -Portuguese | pt -Quechua | qu -Romanian | ro -Russian | ru -Sindhi | sd -Shan | shn -Sinhala | si -Slovak | sk -Slovenian | sl -Shona | sn -Somali | so -Albanian | sq -Serbian | sr -Swati | ss -Sundanese | su -Swedish | sv -Swahili | sw -Tamil | ta -Telugu | te -Tajik | tg -Thai | th -Tigrinya | ti -Tagalog | tl -Tswana | tn -Turkish | tr -Ukrainian | uk -Umbundu | umb -Urdu | ur -Uzbek | uz -Vietnamese | vi -Wolof | wo -Xhosa | xh -Yiddish | yi -Yoruba | yo -Chinese| zh -Zulu | zu diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/charset_normalizer/assets/__init__.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/charset_normalizer/assets/__init__.py deleted file mode 100644 index 9075930dc8f9a382c0bd7663e546fa2a93a4d257..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/charset_normalizer/assets/__init__.py +++ /dev/null @@ -1,1440 +0,0 @@ -# -*- coding: utf-8 -*- -from typing import Dict, List - -# Language label that contain the em dash "—" -# character are to be considered alternative seq to origin -FREQUENCIES: Dict[str, List[str]] = { - "English": [ - "e", - "a", - "t", - "i", - "o", - "n", - "s", - "r", - "h", - "l", - "d", - "c", - "u", - "m", - "f", - "p", - "g", - "w", - "y", - "b", - "v", - "k", - "x", - "j", - "z", - "q", - ], - "English—": [ - "e", - "a", - "t", - "i", - "o", - "n", - "s", - "r", - "h", - "l", - "d", - "c", - "m", - "u", - "f", - "p", - "g", - "w", - "b", - "y", - "v", - "k", - "j", - "x", - "z", - "q", - ], - "German": [ - "e", - "n", - "i", - "r", - "s", - "t", - "a", - "d", - "h", - "u", - "l", - "g", - "o", - "c", - "m", - "b", - "f", - "k", - "w", - "z", - "p", - "v", - "ü", - "ä", - "ö", - "j", - ], - "French": [ - "e", - "a", - "s", - "n", - "i", - "t", - "r", - "l", - "u", - "o", - "d", - "c", - "p", - "m", - "é", - "v", - "g", - "f", - "b", - "h", - "q", - "à", - "x", - "è", - "y", - "j", - ], - "Dutch": [ - "e", - "n", - "a", - "i", - "r", - "t", - "o", - "d", - "s", - "l", - "g", - "h", - "v", - "m", - "u", - "k", - "c", - "p", - "b", - "w", - "j", - "z", - "f", - "y", - "x", - "ë", - ], - "Italian": [ - "e", - "i", - "a", - "o", - "n", - "l", - "t", - "r", - "s", - "c", - "d", - "u", - "p", - "m", - "g", - "v", - "f", - "b", - "z", - "h", - "q", - "è", - "à", - "k", - "y", - "ò", - ], - "Polish": [ - "a", - "i", - "o", - "e", - "n", - "r", - "z", - "w", - "s", - "c", - "t", - "k", - "y", - "d", - "p", - "m", - "u", - "l", - "j", - "ł", - "g", - "b", - "h", - "ą", - "ę", - "ó", - ], - "Spanish": [ - "e", - "a", - "o", - "n", - "s", - "r", - "i", - "l", - "d", - "t", - "c", - "u", - "m", - "p", - "b", - "g", - "v", - "f", - "y", - "ó", - "h", - "q", - "í", - "j", - "z", - "á", - ], - "Russian": [ - "о", - "а", - "е", - "и", - "н", - "с", - "т", - "р", - "в", - "л", - "к", - "м", - "д", - "п", - "у", - "г", - "я", - "ы", - "з", - "б", - "й", - "ь", - "ч", - "х", - "ж", - "ц", - ], - # Jap-Kanji - "Japanese": [ - "人", - "一", - "大", - "亅", - "丁", - "丨", - "竹", - "笑", - "口", - "日", - "今", - "二", - "彳", - "行", - "十", - "土", - "丶", - "寸", - "寺", - "時", - "乙", - "丿", - "乂", - "气", - "気", - "冂", - "巾", - "亠", - "市", - "目", - "儿", - "見", - "八", - "小", - "凵", - "県", - "月", - "彐", - "門", - "間", - "木", - "東", - "山", - "出", - "本", - "中", - "刀", - "分", - "耳", - "又", - "取", - "最", - "言", - "田", - "心", - "思", - "刂", - "前", - "京", - "尹", - "事", - "生", - "厶", - "云", - "会", - "未", - "来", - "白", - "冫", - "楽", - "灬", - "馬", - "尸", - "尺", - "駅", - "明", - "耂", - "者", - "了", - "阝", - "都", - "高", - "卜", - "占", - "厂", - "广", - "店", - "子", - "申", - "奄", - "亻", - "俺", - "上", - "方", - "冖", - "学", - "衣", - "艮", - "食", - "自", - ], - # Jap-Katakana - "Japanese—": [ - "ー", - "ン", - "ス", - "・", - "ル", - "ト", - "リ", - "イ", - "ア", - "ラ", - "ッ", - "ク", - "ド", - "シ", - "レ", - "ジ", - "タ", - "フ", - "ロ", - "カ", - "テ", - "マ", - "ィ", - "グ", - "バ", - "ム", - "プ", - "オ", - "コ", - "デ", - "ニ", - "ウ", - "メ", - "サ", - "ビ", - "ナ", - "ブ", - "ャ", - "エ", - "ュ", - "チ", - "キ", - "ズ", - "ダ", - "パ", - "ミ", - "ェ", - "ョ", - "ハ", - "セ", - "ベ", - "ガ", - "モ", - "ツ", - "ネ", - "ボ", - "ソ", - "ノ", - "ァ", - "ヴ", - "ワ", - "ポ", - "ペ", - "ピ", - "ケ", - "ゴ", - "ギ", - "ザ", - "ホ", - "ゲ", - "ォ", - "ヤ", - "ヒ", - "ユ", - "ヨ", - "ヘ", - "ゼ", - "ヌ", - "ゥ", - "ゾ", - "ヶ", - "ヂ", - "ヲ", - "ヅ", - "ヵ", - "ヱ", - "ヰ", - "ヮ", - "ヽ", - "゠", - "ヾ", - "ヷ", - "ヿ", - "ヸ", - "ヹ", - "ヺ", - ], - # Jap-Hiragana - "Japanese——": [ - "の", - "に", - "る", - "た", - "と", - "は", - "し", - "い", - "を", - "で", - "て", - "が", - "な", - "れ", - "か", - "ら", - "さ", - "っ", - "り", - "す", - "あ", - "も", - "こ", - "ま", - "う", - "く", - "よ", - "き", - "ん", - "め", - "お", - "け", - "そ", - "つ", - "だ", - "や", - "え", - "ど", - "わ", - "ち", - "み", - "せ", - "じ", - "ば", - "へ", - "び", - "ず", - "ろ", - "ほ", - "げ", - "む", - "べ", - "ひ", - "ょ", - "ゆ", - "ぶ", - "ご", - "ゃ", - "ね", - "ふ", - "ぐ", - "ぎ", - "ぼ", - "ゅ", - "づ", - "ざ", - "ぞ", - "ぬ", - "ぜ", - "ぱ", - "ぽ", - "ぷ", - "ぴ", - "ぃ", - "ぁ", - "ぇ", - "ぺ", - "ゞ", - "ぢ", - "ぉ", - "ぅ", - "ゐ", - "ゝ", - "ゑ", - "゛", - "゜", - "ゎ", - "ゔ", - "゚", - "ゟ", - "゙", - "ゕ", - "ゖ", - ], - "Portuguese": [ - "a", - "e", - "o", - "s", - "i", - "r", - "d", - "n", - "t", - "m", - "u", - "c", - "l", - "p", - "g", - "v", - "b", - "f", - "h", - "ã", - "q", - "é", - "ç", - "á", - "z", - "í", - ], - "Swedish": [ - "e", - "a", - "n", - "r", - "t", - "s", - "i", - "l", - "d", - "o", - "m", - "k", - "g", - "v", - "h", - "f", - "u", - "p", - "ä", - "c", - "b", - "ö", - "å", - "y", - "j", - "x", - ], - "Chinese": [ - "的", - "一", - "是", - "不", - "了", - "在", - "人", - "有", - "我", - "他", - "这", - "个", - "们", - "中", - "来", - "上", - "大", - "为", - "和", - "国", - "地", - "到", - "以", - "说", - "时", - "要", - "就", - "出", - "会", - "可", - "也", - "你", - "对", - "生", - "能", - "而", - "子", - "那", - "得", - "于", - "着", - "下", - "自", - "之", - "年", - "过", - "发", - "后", - "作", - "里", - "用", - "道", - "行", - "所", - "然", - "家", - "种", - "事", - "成", - "方", - "多", - "经", - "么", - "去", - "法", - "学", - "如", - "都", - "同", - "现", - "当", - "没", - "动", - "面", - "起", - "看", - "定", - "天", - "分", - "还", - "进", - "好", - "小", - "部", - "其", - "些", - "主", - "样", - "理", - "心", - "她", - "本", - "前", - "开", - "但", - "因", - "只", - "从", - "想", - "实", - ], - "Ukrainian": [ - "о", - "а", - "н", - "і", - "и", - "р", - "в", - "т", - "е", - "с", - "к", - "л", - "у", - "д", - "м", - "п", - "з", - "я", - "ь", - "б", - "г", - "й", - "ч", - "х", - "ц", - "ї", - ], - "Norwegian": [ - "e", - "r", - "n", - "t", - "a", - "s", - "i", - "o", - "l", - "d", - "g", - "k", - "m", - "v", - "f", - "p", - "u", - "b", - "h", - "å", - "y", - "j", - "ø", - "c", - "æ", - "w", - ], - "Finnish": [ - "a", - "i", - "n", - "t", - "e", - "s", - "l", - "o", - "u", - "k", - "ä", - "m", - "r", - "v", - "j", - "h", - "p", - "y", - "d", - "ö", - "g", - "c", - "b", - "f", - "w", - "z", - ], - "Vietnamese": [ - "n", - "h", - "t", - "i", - "c", - "g", - "a", - "o", - "u", - "m", - "l", - "r", - "à", - "đ", - "s", - "e", - "v", - "p", - "b", - "y", - "ư", - "d", - "á", - "k", - "ộ", - "ế", - ], - "Czech": [ - "o", - "e", - "a", - "n", - "t", - "s", - "i", - "l", - "v", - "r", - "k", - "d", - "u", - "m", - "p", - "í", - "c", - "h", - "z", - "á", - "y", - "j", - "b", - "ě", - "é", - "ř", - ], - "Hungarian": [ - "e", - "a", - "t", - "l", - "s", - "n", - "k", - "r", - "i", - "o", - "z", - "á", - "é", - "g", - "m", - "b", - "y", - "v", - "d", - "h", - "u", - "p", - "j", - "ö", - "f", - "c", - ], - "Korean": [ - "이", - "다", - "에", - "의", - "는", - "로", - "하", - "을", - "가", - "고", - "지", - "서", - "한", - "은", - "기", - "으", - "년", - "대", - "사", - "시", - "를", - "리", - "도", - "인", - "스", - "일", - ], - "Indonesian": [ - "a", - "n", - "e", - "i", - "r", - "t", - "u", - "s", - "d", - "k", - "m", - "l", - "g", - "p", - "b", - "o", - "h", - "y", - "j", - "c", - "w", - "f", - "v", - "z", - "x", - "q", - ], - "Turkish": [ - "a", - "e", - "i", - "n", - "r", - "l", - "ı", - "k", - "d", - "t", - "s", - "m", - "y", - "u", - "o", - "b", - "ü", - "ş", - "v", - "g", - "z", - "h", - "c", - "p", - "ç", - "ğ", - ], - "Romanian": [ - "e", - "i", - "a", - "r", - "n", - "t", - "u", - "l", - "o", - "c", - "s", - "d", - "p", - "m", - "ă", - "f", - "v", - "î", - "g", - "b", - "ș", - "ț", - "z", - "h", - "â", - "j", - ], - "Farsi": [ - "ا", - "ی", - "ر", - "د", - "ن", - "ه", - "و", - "م", - "ت", - "ب", - "س", - "ل", - "ک", - "ش", - "ز", - "ف", - "گ", - "ع", - "خ", - "ق", - "ج", - "آ", - "پ", - "ح", - "ط", - "ص", - ], - "Arabic": [ - "ا", - "ل", - "ي", - "م", - "و", - "ن", - "ر", - "ت", - "ب", - "ة", - "ع", - "د", - "س", - "ف", - "ه", - "ك", - "ق", - "أ", - "ح", - "ج", - "ش", - "ط", - "ص", - "ى", - "خ", - "إ", - ], - "Danish": [ - "e", - "r", - "n", - "t", - "a", - "i", - "s", - "d", - "l", - "o", - "g", - "m", - "k", - "f", - "v", - "u", - "b", - "h", - "p", - "å", - "y", - "ø", - "æ", - "c", - "j", - "w", - ], - "Serbian": [ - "а", - "и", - "о", - "е", - "н", - "р", - "с", - "у", - "т", - "к", - "ј", - "в", - "д", - "м", - "п", - "л", - "г", - "з", - "б", - "a", - "i", - "e", - "o", - "n", - "ц", - "ш", - ], - "Lithuanian": [ - "i", - "a", - "s", - "o", - "r", - "e", - "t", - "n", - "u", - "k", - "m", - "l", - "p", - "v", - "d", - "j", - "g", - "ė", - "b", - "y", - "ų", - "š", - "ž", - "c", - "ą", - "į", - ], - "Slovene": [ - "e", - "a", - "i", - "o", - "n", - "r", - "s", - "l", - "t", - "j", - "v", - "k", - "d", - "p", - "m", - "u", - "z", - "b", - "g", - "h", - "č", - "c", - "š", - "ž", - "f", - "y", - ], - "Slovak": [ - "o", - "a", - "e", - "n", - "i", - "r", - "v", - "t", - "s", - "l", - "k", - "d", - "m", - "p", - "u", - "c", - "h", - "j", - "b", - "z", - "á", - "y", - "ý", - "í", - "č", - "é", - ], - "Hebrew": [ - "י", - "ו", - "ה", - "ל", - "ר", - "ב", - "ת", - "מ", - "א", - "ש", - "נ", - "ע", - "ם", - "ד", - "ק", - "ח", - "פ", - "ס", - "כ", - "ג", - "ט", - "צ", - "ן", - "ז", - "ך", - ], - "Bulgarian": [ - "а", - "и", - "о", - "е", - "н", - "т", - "р", - "с", - "в", - "л", - "к", - "д", - "п", - "м", - "з", - "г", - "я", - "ъ", - "у", - "б", - "ч", - "ц", - "й", - "ж", - "щ", - "х", - ], - "Croatian": [ - "a", - "i", - "o", - "e", - "n", - "r", - "j", - "s", - "t", - "u", - "k", - "l", - "v", - "d", - "m", - "p", - "g", - "z", - "b", - "c", - "č", - "h", - "š", - "ž", - "ć", - "f", - ], - "Hindi": [ - "क", - "र", - "स", - "न", - "त", - "म", - "ह", - "प", - "य", - "ल", - "व", - "ज", - "द", - "ग", - "ब", - "श", - "ट", - "अ", - "ए", - "थ", - "भ", - "ड", - "च", - "ध", - "ष", - "इ", - ], - "Estonian": [ - "a", - "i", - "e", - "s", - "t", - "l", - "u", - "n", - "o", - "k", - "r", - "d", - "m", - "v", - "g", - "p", - "j", - "h", - "ä", - "b", - "õ", - "ü", - "f", - "c", - "ö", - "y", - ], - "Thai": [ - "า", - "น", - "ร", - "อ", - "ก", - "เ", - "ง", - "ม", - "ย", - "ล", - "ว", - "ด", - "ท", - "ส", - "ต", - "ะ", - "ป", - "บ", - "ค", - "ห", - "แ", - "จ", - "พ", - "ช", - "ข", - "ใ", - ], - "Greek": [ - "α", - "τ", - "ο", - "ι", - "ε", - "ν", - "ρ", - "σ", - "κ", - "η", - "π", - "ς", - "υ", - "μ", - "λ", - "ί", - "ό", - "ά", - "γ", - "έ", - "δ", - "ή", - "ω", - "χ", - "θ", - "ύ", - ], - "Tamil": [ - "க", - "த", - "ப", - "ட", - "ர", - "ம", - "ல", - "ன", - "வ", - "ற", - "ய", - "ள", - "ச", - "ந", - "இ", - "ண", - "அ", - "ஆ", - "ழ", - "ங", - "எ", - "உ", - "ஒ", - "ஸ", - ], - "Kazakh": [ - "а", - "ы", - "е", - "н", - "т", - "р", - "л", - "і", - "д", - "с", - "м", - "қ", - "к", - "о", - "б", - "и", - "у", - "ғ", - "ж", - "ң", - "з", - "ш", - "й", - "п", - "г", - "ө", - ], -} diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/xmlWriter.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/xmlWriter.py deleted file mode 100644 index 9a8dc3e3b7fe5eb13ea4b7ea369ced1da5555471..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/misc/xmlWriter.py +++ /dev/null @@ -1,204 +0,0 @@ -"""xmlWriter.py -- Simple XML authoring class""" - -from fontTools.misc.textTools import byteord, strjoin, tobytes, tostr -import sys -import os -import string - -INDENT = " " - - -class XMLWriter(object): - def __init__( - self, - fileOrPath, - indentwhite=INDENT, - idlefunc=None, - encoding="utf_8", - newlinestr="\n", - ): - if encoding.lower().replace("-", "").replace("_", "") != "utf8": - raise Exception("Only UTF-8 encoding is supported.") - if fileOrPath == "-": - fileOrPath = sys.stdout - if not hasattr(fileOrPath, "write"): - self.filename = fileOrPath - self.file = open(fileOrPath, "wb") - self._closeStream = True - else: - self.filename = None - # assume writable file object - self.file = fileOrPath - self._closeStream = False - - # Figure out if writer expects bytes or unicodes - try: - # The bytes check should be first. See: - # https://github.com/fonttools/fonttools/pull/233 - self.file.write(b"") - self.totype = tobytes - except TypeError: - # This better not fail. - self.file.write("") - self.totype = tostr - self.indentwhite = self.totype(indentwhite) - if newlinestr is None: - self.newlinestr = self.totype(os.linesep) - else: - self.newlinestr = self.totype(newlinestr) - self.indentlevel = 0 - self.stack = [] - self.needindent = 1 - self.idlefunc = idlefunc - self.idlecounter = 0 - self._writeraw('') - self.newline() - - def __enter__(self): - return self - - def __exit__(self, exception_type, exception_value, traceback): - self.close() - - def close(self): - if self._closeStream: - self.file.close() - - def write(self, string, indent=True): - """Writes text.""" - self._writeraw(escape(string), indent=indent) - - def writecdata(self, string): - """Writes text in a CDATA section.""" - self._writeraw("") - - def write8bit(self, data, strip=False): - """Writes a bytes() sequence into the XML, escaping - non-ASCII bytes. When this is read in xmlReader, - the original bytes can be recovered by encoding to - 'latin-1'.""" - self._writeraw(escape8bit(data), strip=strip) - - def write_noindent(self, string): - """Writes text without indentation.""" - self._writeraw(escape(string), indent=False) - - def _writeraw(self, data, indent=True, strip=False): - """Writes bytes, possibly indented.""" - if indent and self.needindent: - self.file.write(self.indentlevel * self.indentwhite) - self.needindent = 0 - s = self.totype(data, encoding="utf_8") - if strip: - s = s.strip() - self.file.write(s) - - def newline(self): - self.file.write(self.newlinestr) - self.needindent = 1 - idlecounter = self.idlecounter - if not idlecounter % 100 and self.idlefunc is not None: - self.idlefunc() - self.idlecounter = idlecounter + 1 - - def comment(self, data): - data = escape(data) - lines = data.split("\n") - self._writeraw("") - - def simpletag(self, _TAG_, *args, **kwargs): - attrdata = self.stringifyattrs(*args, **kwargs) - data = "<%s%s/>" % (_TAG_, attrdata) - self._writeraw(data) - - def begintag(self, _TAG_, *args, **kwargs): - attrdata = self.stringifyattrs(*args, **kwargs) - data = "<%s%s>" % (_TAG_, attrdata) - self._writeraw(data) - self.stack.append(_TAG_) - self.indent() - - def endtag(self, _TAG_): - assert self.stack and self.stack[-1] == _TAG_, "nonmatching endtag" - del self.stack[-1] - self.dedent() - data = "" % _TAG_ - self._writeraw(data) - - def dumphex(self, data): - linelength = 16 - hexlinelength = linelength * 2 - chunksize = 8 - for i in range(0, len(data), linelength): - hexline = hexStr(data[i : i + linelength]) - line = "" - white = "" - for j in range(0, hexlinelength, chunksize): - line = line + white + hexline[j : j + chunksize] - white = " " - self._writeraw(line) - self.newline() - - def indent(self): - self.indentlevel = self.indentlevel + 1 - - def dedent(self): - assert self.indentlevel > 0 - self.indentlevel = self.indentlevel - 1 - - def stringifyattrs(self, *args, **kwargs): - if kwargs: - assert not args - attributes = sorted(kwargs.items()) - elif args: - assert len(args) == 1 - attributes = args[0] - else: - return "" - data = "" - for attr, value in attributes: - if not isinstance(value, (bytes, str)): - value = str(value) - data = data + ' %s="%s"' % (attr, escapeattr(value)) - return data - - -def escape(data): - data = tostr(data, "utf_8") - data = data.replace("&", "&") - data = data.replace("<", "<") - data = data.replace(">", ">") - data = data.replace("\r", " ") - return data - - -def escapeattr(data): - data = escape(data) - data = data.replace('"', """) - return data - - -def escape8bit(data): - """Input is Unicode string.""" - - def escapechar(c): - n = ord(c) - if 32 <= n <= 127 and c not in "<&>": - return c - else: - return "&#" + repr(n) + ";" - - return strjoin(map(escapechar, data.decode("latin-1"))) - - -def hexStr(s): - h = string.hexdigits - r = "" - for c in s: - i = byteord(c) - r = r + h[(i >> 4) & 0xF] + h[i & 0xF] - return r diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_client.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_client.py deleted file mode 100644 index cb475e02045aafac34309e4b808e12c580e58d8f..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpx/_client.py +++ /dev/null @@ -1,2006 +0,0 @@ -import datetime -import enum -import logging -import typing -import warnings -from contextlib import asynccontextmanager, contextmanager -from types import TracebackType - -from .__version__ import __version__ -from ._auth import Auth, BasicAuth, FunctionAuth -from ._config import ( - DEFAULT_LIMITS, - DEFAULT_MAX_REDIRECTS, - DEFAULT_TIMEOUT_CONFIG, - Limits, - Proxy, - Timeout, -) -from ._decoders import SUPPORTED_DECODERS -from ._exceptions import ( - InvalidURL, - RemoteProtocolError, - TooManyRedirects, - request_context, -) -from ._models import Cookies, Headers, Request, Response -from ._status_codes import codes -from ._transports.asgi import ASGITransport -from ._transports.base import AsyncBaseTransport, BaseTransport -from ._transports.default import AsyncHTTPTransport, HTTPTransport -from ._transports.wsgi import WSGITransport -from ._types import ( - AsyncByteStream, - AuthTypes, - CertTypes, - CookieTypes, - HeaderTypes, - ProxiesTypes, - QueryParamTypes, - RequestContent, - RequestData, - RequestExtensions, - RequestFiles, - SyncByteStream, - TimeoutTypes, - URLTypes, - VerifyTypes, -) -from ._urls import URL, QueryParams -from ._utils import ( - Timer, - URLPattern, - get_environment_proxies, - is_https_redirect, - same_origin, -) - -# The type annotation for @classmethod and context managers here follows PEP 484 -# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods -T = typing.TypeVar("T", bound="Client") -U = typing.TypeVar("U", bound="AsyncClient") - - -class UseClientDefault: - """ - For some parameters such as `auth=...` and `timeout=...` we need to be able - to indicate the default "unset" state, in a way that is distinctly different - to using `None`. - - The default "unset" state indicates that whatever default is set on the - client should be used. This is different to setting `None`, which - explicitly disables the parameter, possibly overriding a client default. - - For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature. - Omitting the `timeout` parameter will send a request using whatever default - timeout has been configured on the client. Including `timeout=None` will - ensure no timeout is used. - - Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant, - but it is used internally when a parameter is not included. - """ - - -USE_CLIENT_DEFAULT = UseClientDefault() - - -logger = logging.getLogger("httpx") - -USER_AGENT = f"python-httpx/{__version__}" -ACCEPT_ENCODING = ", ".join( - [key for key in SUPPORTED_DECODERS.keys() if key != "identity"] -) - - -class ClientState(enum.Enum): - # UNOPENED: - # The client has been instantiated, but has not been used to send a request, - # or been opened by entering the context of a `with` block. - UNOPENED = 1 - # OPENED: - # The client has either sent a request, or is within a `with` block. - OPENED = 2 - # CLOSED: - # The client has either exited the `with` block, or `close()` has - # been called explicitly. - CLOSED = 3 - - -class BoundSyncStream(SyncByteStream): - """ - A byte stream that is bound to a given response instance, and that - ensures the `response.elapsed` is set once the response is closed. - """ - - def __init__( - self, stream: SyncByteStream, response: Response, timer: Timer - ) -> None: - self._stream = stream - self._response = response - self._timer = timer - - def __iter__(self) -> typing.Iterator[bytes]: - for chunk in self._stream: - yield chunk - - def close(self) -> None: - seconds = self._timer.sync_elapsed() - self._response.elapsed = datetime.timedelta(seconds=seconds) - self._stream.close() - - -class BoundAsyncStream(AsyncByteStream): - """ - An async byte stream that is bound to a given response instance, and that - ensures the `response.elapsed` is set once the response is closed. - """ - - def __init__( - self, stream: AsyncByteStream, response: Response, timer: Timer - ) -> None: - self._stream = stream - self._response = response - self._timer = timer - - async def __aiter__(self) -> typing.AsyncIterator[bytes]: - async for chunk in self._stream: - yield chunk - - async def aclose(self) -> None: - seconds = await self._timer.async_elapsed() - self._response.elapsed = datetime.timedelta(seconds=seconds) - await self._stream.aclose() - - -EventHook = typing.Callable[..., typing.Any] - - -class BaseClient: - def __init__( - self, - *, - auth: typing.Optional[AuthTypes] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - follow_redirects: bool = False, - max_redirects: int = DEFAULT_MAX_REDIRECTS, - event_hooks: typing.Optional[ - typing.Mapping[str, typing.List[EventHook]] - ] = None, - base_url: URLTypes = "", - trust_env: bool = True, - default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = "utf-8", - ): - event_hooks = {} if event_hooks is None else event_hooks - - self._base_url = self._enforce_trailing_slash(URL(base_url)) - - self._auth = self._build_auth(auth) - self._params = QueryParams(params) - self.headers = Headers(headers) - self._cookies = Cookies(cookies) - self._timeout = Timeout(timeout) - self.follow_redirects = follow_redirects - self.max_redirects = max_redirects - self._event_hooks = { - "request": list(event_hooks.get("request", [])), - "response": list(event_hooks.get("response", [])), - } - self._trust_env = trust_env - self._default_encoding = default_encoding - self._state = ClientState.UNOPENED - - @property - def is_closed(self) -> bool: - """ - Check if the client being closed - """ - return self._state == ClientState.CLOSED - - @property - def trust_env(self) -> bool: - return self._trust_env - - def _enforce_trailing_slash(self, url: URL) -> URL: - if url.raw_path.endswith(b"/"): - return url - return url.copy_with(raw_path=url.raw_path + b"/") - - def _get_proxy_map( - self, proxies: typing.Optional[ProxiesTypes], allow_env_proxies: bool - ) -> typing.Dict[str, typing.Optional[Proxy]]: - if proxies is None: - if allow_env_proxies: - return { - key: None if url is None else Proxy(url=url) - for key, url in get_environment_proxies().items() - } - return {} - if isinstance(proxies, dict): - new_proxies = {} - for key, value in proxies.items(): - proxy = Proxy(url=value) if isinstance(value, (str, URL)) else value - new_proxies[str(key)] = proxy - return new_proxies - else: - proxy = Proxy(url=proxies) if isinstance(proxies, (str, URL)) else proxies - return {"all://": proxy} - - @property - def timeout(self) -> Timeout: - return self._timeout - - @timeout.setter - def timeout(self, timeout: TimeoutTypes) -> None: - self._timeout = Timeout(timeout) - - @property - def event_hooks(self) -> typing.Dict[str, typing.List[EventHook]]: - return self._event_hooks - - @event_hooks.setter - def event_hooks( - self, event_hooks: typing.Dict[str, typing.List[EventHook]] - ) -> None: - self._event_hooks = { - "request": list(event_hooks.get("request", [])), - "response": list(event_hooks.get("response", [])), - } - - @property - def auth(self) -> typing.Optional[Auth]: - """ - Authentication class used when none is passed at the request-level. - - See also [Authentication][0]. - - [0]: /quickstart/#authentication - """ - return self._auth - - @auth.setter - def auth(self, auth: AuthTypes) -> None: - self._auth = self._build_auth(auth) - - @property - def base_url(self) -> URL: - """ - Base URL to use when sending requests with relative URLs. - """ - return self._base_url - - @base_url.setter - def base_url(self, url: URLTypes) -> None: - self._base_url = self._enforce_trailing_slash(URL(url)) - - @property - def headers(self) -> Headers: - """ - HTTP headers to include when sending requests. - """ - return self._headers - - @headers.setter - def headers(self, headers: HeaderTypes) -> None: - client_headers = Headers( - { - b"Accept": b"*/*", - b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"), - b"Connection": b"keep-alive", - b"User-Agent": USER_AGENT.encode("ascii"), - } - ) - client_headers.update(headers) - self._headers = client_headers - - @property - def cookies(self) -> Cookies: - """ - Cookie values to include when sending requests. - """ - return self._cookies - - @cookies.setter - def cookies(self, cookies: CookieTypes) -> None: - self._cookies = Cookies(cookies) - - @property - def params(self) -> QueryParams: - """ - Query parameters to include in the URL when sending requests. - """ - return self._params - - @params.setter - def params(self, params: QueryParamTypes) -> None: - self._params = QueryParams(params) - - def build_request( - self, - method: str, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Request: - """ - Build and return a request instance. - - * The `params`, `headers` and `cookies` arguments - are merged with any values set on the client. - * The `url` argument is merged with any `base_url` set on the client. - - See also: [Request instances][0] - - [0]: /advanced/#request-instances - """ - url = self._merge_url(url) - headers = self._merge_headers(headers) - cookies = self._merge_cookies(cookies) - params = self._merge_queryparams(params) - extensions = {} if extensions is None else extensions - if "timeout" not in extensions: - timeout = ( - self.timeout - if isinstance(timeout, UseClientDefault) - else Timeout(timeout) - ) - extensions = dict(**extensions, timeout=timeout.as_dict()) - return Request( - method, - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - extensions=extensions, - ) - - def _merge_url(self, url: URLTypes) -> URL: - """ - Merge a URL argument together with any 'base_url' on the client, - to create the URL used for the outgoing request. - """ - merge_url = URL(url) - if merge_url.is_relative_url: - # To merge URLs we always append to the base URL. To get this - # behaviour correct we always ensure the base URL ends in a '/' - # separator, and strip any leading '/' from the merge URL. - # - # So, eg... - # - # >>> client = Client(base_url="https://www.example.com/subpath") - # >>> client.base_url - # URL('https://www.example.com/subpath/') - # >>> client.build_request("GET", "/path").url - # URL('https://www.example.com/subpath/path') - merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") - return self.base_url.copy_with(raw_path=merge_raw_path) - return merge_url - - def _merge_cookies( - self, cookies: typing.Optional[CookieTypes] = None - ) -> typing.Optional[CookieTypes]: - """ - Merge a cookies argument together with any cookies on the client, - to create the cookies used for the outgoing request. - """ - if cookies or self.cookies: - merged_cookies = Cookies(self.cookies) - merged_cookies.update(cookies) - return merged_cookies - return cookies - - def _merge_headers( - self, headers: typing.Optional[HeaderTypes] = None - ) -> typing.Optional[HeaderTypes]: - """ - Merge a headers argument together with any headers on the client, - to create the headers used for the outgoing request. - """ - merged_headers = Headers(self.headers) - merged_headers.update(headers) - return merged_headers - - def _merge_queryparams( - self, params: typing.Optional[QueryParamTypes] = None - ) -> typing.Optional[QueryParamTypes]: - """ - Merge a queryparams argument together with any queryparams on the client, - to create the queryparams used for the outgoing request. - """ - if params or self.params: - merged_queryparams = QueryParams(self.params) - return merged_queryparams.merge(params) - return params - - def _build_auth(self, auth: typing.Optional[AuthTypes]) -> typing.Optional[Auth]: - if auth is None: - return None - elif isinstance(auth, tuple): - return BasicAuth(username=auth[0], password=auth[1]) - elif isinstance(auth, Auth): - return auth - elif callable(auth): - return FunctionAuth(func=auth) - else: - raise TypeError(f'Invalid "auth" argument: {auth!r}') - - def _build_request_auth( - self, - request: Request, - auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT, - ) -> Auth: - auth = ( - self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth) - ) - - if auth is not None: - return auth - - username, password = request.url.username, request.url.password - if username or password: - return BasicAuth(username=username, password=password) - - return Auth() - - def _build_redirect_request(self, request: Request, response: Response) -> Request: - """ - Given a request and a redirect response, return a new request that - should be used to effect the redirect. - """ - method = self._redirect_method(request, response) - url = self._redirect_url(request, response) - headers = self._redirect_headers(request, url, method) - stream = self._redirect_stream(request, method) - cookies = Cookies(self.cookies) - return Request( - method=method, - url=url, - headers=headers, - cookies=cookies, - stream=stream, - extensions=request.extensions, - ) - - def _redirect_method(self, request: Request, response: Response) -> str: - """ - When being redirected we may want to change the method of the request - based on certain specs or browser behavior. - """ - method = request.method - - # https://tools.ietf.org/html/rfc7231#section-6.4.4 - if response.status_code == codes.SEE_OTHER and method != "HEAD": - method = "GET" - - # Do what the browsers do, despite standards... - # Turn 302s into GETs. - if response.status_code == codes.FOUND and method != "HEAD": - method = "GET" - - # If a POST is responded to with a 301, turn it into a GET. - # This bizarre behaviour is explained in 'requests' issue 1704. - if response.status_code == codes.MOVED_PERMANENTLY and method == "POST": - method = "GET" - - return method - - def _redirect_url(self, request: Request, response: Response) -> URL: - """ - Return the URL for the redirect to follow. - """ - location = response.headers["Location"] - - try: - url = URL(location) - except InvalidURL as exc: - raise RemoteProtocolError( - f"Invalid URL in location header: {exc}.", request=request - ) from None - - # Handle malformed 'Location' headers that are "absolute" form, have no host. - # See: https://github.com/encode/httpx/issues/771 - if url.scheme and not url.host: - url = url.copy_with(host=request.url.host) - - # Facilitate relative 'Location' headers, as allowed by RFC 7231. - # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') - if url.is_relative_url: - url = request.url.join(url) - - # Attach previous fragment if needed (RFC 7231 7.1.2) - if request.url.fragment and not url.fragment: - url = url.copy_with(fragment=request.url.fragment) - - return url - - def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers: - """ - Return the headers that should be used for the redirect request. - """ - headers = Headers(request.headers) - - if not same_origin(url, request.url): - if not is_https_redirect(request.url, url): - # Strip Authorization headers when responses are redirected - # away from the origin. (Except for direct HTTP to HTTPS redirects.) - headers.pop("Authorization", None) - - # Update the Host header. - headers["Host"] = url.netloc.decode("ascii") - - if method != request.method and method == "GET": - # If we've switch to a 'GET' request, then strip any headers which - # are only relevant to the request body. - headers.pop("Content-Length", None) - headers.pop("Transfer-Encoding", None) - - # We should use the client cookie store to determine any cookie header, - # rather than whatever was on the original outgoing request. - headers.pop("Cookie", None) - - return headers - - def _redirect_stream( - self, request: Request, method: str - ) -> typing.Optional[typing.Union[SyncByteStream, AsyncByteStream]]: - """ - Return the body that should be used for the redirect request. - """ - if method != request.method and method == "GET": - return None - - return request.stream - - -class Client(BaseClient): - """ - An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc. - - It can be shared between threads. - - Usage: - - ```python - >>> client = httpx.Client() - >>> response = client.get('https://example.org') - ``` - - **Parameters:** - - * **auth** - *(optional)* An authentication class to use when sending - requests. - * **params** - *(optional)* Query parameters to include in request URLs, as - a string, dictionary, or sequence of two-tuples. - * **headers** - *(optional)* Dictionary of HTTP headers to include when - sending requests. - * **cookies** - *(optional)* Dictionary of Cookie items to include when - sending requests. - * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to - verify the identity of requested hosts. Either `True` (default CA bundle), - a path to an SSL certificate file, an `ssl.SSLContext`, or `False` - (which will disable verification). - * **cert** - *(optional)* An SSL certificate used by the requested host - to authenticate the client. Either a path to an SSL certificate file, or - two-tuple of (certificate file, key file), or a three-tuple of (certificate - file, key file, password). - * **proxies** - *(optional)* A dictionary mapping proxy keys to proxy - URLs. - * **timeout** - *(optional)* The timeout configuration to use when sending - requests. - * **limits** - *(optional)* The limits configuration to use. - * **max_redirects** - *(optional)* The maximum number of redirect responses - that should be followed. - * **base_url** - *(optional)* A URL to use as the base when building - request URLs. - * **transport** - *(optional)* A transport class to use for sending requests - over the network. - * **app** - *(optional)* An WSGI application to send requests to, - rather than sending actual network requests. - * **trust_env** - *(optional)* Enables or disables usage of environment - variables for configuration. - * **default_encoding** - *(optional)* The default encoding to use for decoding - response text, if no charset information is included in a response Content-Type - header. Set to a callable for automatic character set detection. Default: "utf-8". - """ - - def __init__( - self, - *, - auth: typing.Optional[AuthTypes] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - verify: VerifyTypes = True, - cert: typing.Optional[CertTypes] = None, - http1: bool = True, - http2: bool = False, - proxies: typing.Optional[ProxiesTypes] = None, - mounts: typing.Optional[typing.Mapping[str, BaseTransport]] = None, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - follow_redirects: bool = False, - limits: Limits = DEFAULT_LIMITS, - max_redirects: int = DEFAULT_MAX_REDIRECTS, - event_hooks: typing.Optional[ - typing.Mapping[str, typing.List[EventHook]] - ] = None, - base_url: URLTypes = "", - transport: typing.Optional[BaseTransport] = None, - app: typing.Optional[typing.Callable[..., typing.Any]] = None, - trust_env: bool = True, - default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = "utf-8", - ): - super().__init__( - auth=auth, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - follow_redirects=follow_redirects, - max_redirects=max_redirects, - event_hooks=event_hooks, - base_url=base_url, - trust_env=trust_env, - default_encoding=default_encoding, - ) - - if http2: - try: - import h2 # noqa - except ImportError: # pragma: no cover - raise ImportError( - "Using http2=True, but the 'h2' package is not installed. " - "Make sure to install httpx using `pip install httpx[http2]`." - ) from None - - allow_env_proxies = trust_env and app is None and transport is None - proxy_map = self._get_proxy_map(proxies, allow_env_proxies) - - self._transport = self._init_transport( - verify=verify, - cert=cert, - http1=http1, - http2=http2, - limits=limits, - transport=transport, - app=app, - trust_env=trust_env, - ) - self._mounts: typing.Dict[URLPattern, typing.Optional[BaseTransport]] = { - URLPattern(key): None - if proxy is None - else self._init_proxy_transport( - proxy, - verify=verify, - cert=cert, - http1=http1, - http2=http2, - limits=limits, - trust_env=trust_env, - ) - for key, proxy in proxy_map.items() - } - if mounts is not None: - self._mounts.update( - {URLPattern(key): transport for key, transport in mounts.items()} - ) - - self._mounts = dict(sorted(self._mounts.items())) - - def _init_transport( - self, - verify: VerifyTypes = True, - cert: typing.Optional[CertTypes] = None, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - transport: typing.Optional[BaseTransport] = None, - app: typing.Optional[typing.Callable[..., typing.Any]] = None, - trust_env: bool = True, - ) -> BaseTransport: - if transport is not None: - return transport - - if app is not None: - return WSGITransport(app=app) - - return HTTPTransport( - verify=verify, - cert=cert, - http1=http1, - http2=http2, - limits=limits, - trust_env=trust_env, - ) - - def _init_proxy_transport( - self, - proxy: Proxy, - verify: VerifyTypes = True, - cert: typing.Optional[CertTypes] = None, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - trust_env: bool = True, - ) -> BaseTransport: - return HTTPTransport( - verify=verify, - cert=cert, - http1=http1, - http2=http2, - limits=limits, - trust_env=trust_env, - proxy=proxy, - ) - - def _transport_for_url(self, url: URL) -> BaseTransport: - """ - Returns the transport instance that should be used for a given URL. - This will either be the standard connection pool, or a proxy. - """ - for pattern, transport in self._mounts.items(): - if pattern.matches(url): - return self._transport if transport is None else transport - - return self._transport - - def request( - self, - method: str, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Build and send a request. - - Equivalent to: - - ```python - request = client.build_request(...) - response = client.send(request, ...) - ``` - - See `Client.build_request()`, `Client.send()` and - [Merging of configuration][0] for how the various parameters - are merged with client-level configuration. - - [0]: /advanced/#merging-of-configuration - """ - if cookies is not None: - message = ( - "Setting per-request cookies=<...> is being deprecated, because " - "the expected behaviour on cookie persistence is ambiguous. Set " - "cookies directly on the client instance instead." - ) - warnings.warn(message, DeprecationWarning) - - request = self.build_request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - extensions=extensions, - ) - return self.send(request, auth=auth, follow_redirects=follow_redirects) - - @contextmanager - def stream( - self, - method: str, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> typing.Iterator[Response]: - """ - Alternative to `httpx.request()` that streams the response body - instead of loading it into memory at once. - - **Parameters**: See `httpx.request`. - - See also: [Streaming Responses][0] - - [0]: /quickstart#streaming-responses - """ - request = self.build_request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - extensions=extensions, - ) - response = self.send( - request=request, - auth=auth, - follow_redirects=follow_redirects, - stream=True, - ) - try: - yield response - finally: - response.close() - - def send( - self, - request: Request, - *, - stream: bool = False, - auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - ) -> Response: - """ - Send a request. - - The request is sent as-is, unmodified. - - Typically you'll want to build one with `Client.build_request()` - so that any client-level configuration is merged into the request, - but passing an explicit `httpx.Request()` is supported as well. - - See also: [Request instances][0] - - [0]: /advanced/#request-instances - """ - if self._state == ClientState.CLOSED: - raise RuntimeError("Cannot send a request, as the client has been closed.") - - self._state = ClientState.OPENED - follow_redirects = ( - self.follow_redirects - if isinstance(follow_redirects, UseClientDefault) - else follow_redirects - ) - - auth = self._build_request_auth(request, auth) - - response = self._send_handling_auth( - request, - auth=auth, - follow_redirects=follow_redirects, - history=[], - ) - try: - if not stream: - response.read() - - return response - - except BaseException as exc: - response.close() - raise exc - - def _send_handling_auth( - self, - request: Request, - auth: Auth, - follow_redirects: bool, - history: typing.List[Response], - ) -> Response: - auth_flow = auth.sync_auth_flow(request) - try: - request = next(auth_flow) - - while True: - response = self._send_handling_redirects( - request, - follow_redirects=follow_redirects, - history=history, - ) - try: - try: - next_request = auth_flow.send(response) - except StopIteration: - return response - - response.history = list(history) - response.read() - request = next_request - history.append(response) - - except BaseException as exc: - response.close() - raise exc - finally: - auth_flow.close() - - def _send_handling_redirects( - self, - request: Request, - follow_redirects: bool, - history: typing.List[Response], - ) -> Response: - while True: - if len(history) > self.max_redirects: - raise TooManyRedirects( - "Exceeded maximum allowed redirects.", request=request - ) - - for hook in self._event_hooks["request"]: - hook(request) - - response = self._send_single_request(request) - try: - for hook in self._event_hooks["response"]: - hook(response) - response.history = list(history) - - if not response.has_redirect_location: - return response - - request = self._build_redirect_request(request, response) - history = history + [response] - - if follow_redirects: - response.read() - else: - response.next_request = request - return response - - except BaseException as exc: - response.close() - raise exc - - def _send_single_request(self, request: Request) -> Response: - """ - Sends a single request, without handling any redirections. - """ - transport = self._transport_for_url(request.url) - timer = Timer() - timer.sync_start() - - if not isinstance(request.stream, SyncByteStream): - raise RuntimeError( - "Attempted to send an async request with a sync Client instance." - ) - - with request_context(request=request): - response = transport.handle_request(request) - - assert isinstance(response.stream, SyncByteStream) - - response.request = request - response.stream = BoundSyncStream( - response.stream, response=response, timer=timer - ) - self.cookies.extract_cookies(response) - response.default_encoding = self._default_encoding - - logger.info( - 'HTTP Request: %s %s "%s %d %s"', - request.method, - request.url, - response.http_version, - response.status_code, - response.reason_phrase, - ) - - return response - - def get( - self, - url: URLTypes, - *, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `GET` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "GET", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def options( - self, - url: URLTypes, - *, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send an `OPTIONS` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "OPTIONS", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def head( - self, - url: URLTypes, - *, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `HEAD` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "HEAD", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def post( - self, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `POST` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "POST", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def put( - self, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `PUT` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "PUT", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def patch( - self, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `PATCH` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "PATCH", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def delete( - self, - url: URLTypes, - *, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `DELETE` request. - - **Parameters**: See `httpx.request`. - """ - return self.request( - "DELETE", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - def close(self) -> None: - """ - Close transport and proxies. - """ - if self._state != ClientState.CLOSED: - self._state = ClientState.CLOSED - - self._transport.close() - for transport in self._mounts.values(): - if transport is not None: - transport.close() - - def __enter__(self: T) -> T: - if self._state != ClientState.UNOPENED: - msg = { - ClientState.OPENED: "Cannot open a client instance more than once.", - ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.", - }[self._state] - raise RuntimeError(msg) - - self._state = ClientState.OPENED - - self._transport.__enter__() - for transport in self._mounts.values(): - if transport is not None: - transport.__enter__() - return self - - def __exit__( - self, - exc_type: typing.Optional[typing.Type[BaseException]] = None, - exc_value: typing.Optional[BaseException] = None, - traceback: typing.Optional[TracebackType] = None, - ) -> None: - self._state = ClientState.CLOSED - - self._transport.__exit__(exc_type, exc_value, traceback) - for transport in self._mounts.values(): - if transport is not None: - transport.__exit__(exc_type, exc_value, traceback) - - -class AsyncClient(BaseClient): - """ - An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, - cookie persistence, etc. - - Usage: - - ```python - >>> async with httpx.AsyncClient() as client: - >>> response = await client.get('https://example.org') - ``` - - **Parameters:** - - * **auth** - *(optional)* An authentication class to use when sending - requests. - * **params** - *(optional)* Query parameters to include in request URLs, as - a string, dictionary, or sequence of two-tuples. - * **headers** - *(optional)* Dictionary of HTTP headers to include when - sending requests. - * **cookies** - *(optional)* Dictionary of Cookie items to include when - sending requests. - * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to - verify the identity of requested hosts. Either `True` (default CA bundle), - a path to an SSL certificate file, an `ssl.SSLContext`, or `False` - (which will disable verification). - * **cert** - *(optional)* An SSL certificate used by the requested host - to authenticate the client. Either a path to an SSL certificate file, or - two-tuple of (certificate file, key file), or a three-tuple of (certificate - file, key file, password). - * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be - enabled. Defaults to `False`. - * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy - URLs. - * **timeout** - *(optional)* The timeout configuration to use when sending - requests. - * **limits** - *(optional)* The limits configuration to use. - * **max_redirects** - *(optional)* The maximum number of redirect responses - that should be followed. - * **base_url** - *(optional)* A URL to use as the base when building - request URLs. - * **transport** - *(optional)* A transport class to use for sending requests - over the network. - * **app** - *(optional)* An ASGI application to send requests to, - rather than sending actual network requests. - * **trust_env** - *(optional)* Enables or disables usage of environment - variables for configuration. - * **default_encoding** - *(optional)* The default encoding to use for decoding - response text, if no charset information is included in a response Content-Type - header. Set to a callable for automatic character set detection. Default: "utf-8". - """ - - def __init__( - self, - *, - auth: typing.Optional[AuthTypes] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - verify: VerifyTypes = True, - cert: typing.Optional[CertTypes] = None, - http1: bool = True, - http2: bool = False, - proxies: typing.Optional[ProxiesTypes] = None, - mounts: typing.Optional[typing.Mapping[str, AsyncBaseTransport]] = None, - timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, - follow_redirects: bool = False, - limits: Limits = DEFAULT_LIMITS, - max_redirects: int = DEFAULT_MAX_REDIRECTS, - event_hooks: typing.Optional[ - typing.Mapping[str, typing.List[typing.Callable[..., typing.Any]]] - ] = None, - base_url: URLTypes = "", - transport: typing.Optional[AsyncBaseTransport] = None, - app: typing.Optional[typing.Callable[..., typing.Any]] = None, - trust_env: bool = True, - default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = "utf-8", - ): - super().__init__( - auth=auth, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - follow_redirects=follow_redirects, - max_redirects=max_redirects, - event_hooks=event_hooks, - base_url=base_url, - trust_env=trust_env, - default_encoding=default_encoding, - ) - - if http2: - try: - import h2 # noqa - except ImportError: # pragma: no cover - raise ImportError( - "Using http2=True, but the 'h2' package is not installed. " - "Make sure to install httpx using `pip install httpx[http2]`." - ) from None - - allow_env_proxies = trust_env and app is None and transport is None - proxy_map = self._get_proxy_map(proxies, allow_env_proxies) - - self._transport = self._init_transport( - verify=verify, - cert=cert, - http1=http1, - http2=http2, - limits=limits, - transport=transport, - app=app, - trust_env=trust_env, - ) - - self._mounts: typing.Dict[URLPattern, typing.Optional[AsyncBaseTransport]] = { - URLPattern(key): None - if proxy is None - else self._init_proxy_transport( - proxy, - verify=verify, - cert=cert, - http1=http1, - http2=http2, - limits=limits, - trust_env=trust_env, - ) - for key, proxy in proxy_map.items() - } - if mounts is not None: - self._mounts.update( - {URLPattern(key): transport for key, transport in mounts.items()} - ) - self._mounts = dict(sorted(self._mounts.items())) - - def _init_transport( - self, - verify: VerifyTypes = True, - cert: typing.Optional[CertTypes] = None, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - transport: typing.Optional[AsyncBaseTransport] = None, - app: typing.Optional[typing.Callable[..., typing.Any]] = None, - trust_env: bool = True, - ) -> AsyncBaseTransport: - if transport is not None: - return transport - - if app is not None: - return ASGITransport(app=app) - - return AsyncHTTPTransport( - verify=verify, - cert=cert, - http1=http1, - http2=http2, - limits=limits, - trust_env=trust_env, - ) - - def _init_proxy_transport( - self, - proxy: Proxy, - verify: VerifyTypes = True, - cert: typing.Optional[CertTypes] = None, - http1: bool = True, - http2: bool = False, - limits: Limits = DEFAULT_LIMITS, - trust_env: bool = True, - ) -> AsyncBaseTransport: - return AsyncHTTPTransport( - verify=verify, - cert=cert, - http2=http2, - limits=limits, - trust_env=trust_env, - proxy=proxy, - ) - - def _transport_for_url(self, url: URL) -> AsyncBaseTransport: - """ - Returns the transport instance that should be used for a given URL. - This will either be the standard connection pool, or a proxy. - """ - for pattern, transport in self._mounts.items(): - if pattern.matches(url): - return self._transport if transport is None else transport - - return self._transport - - async def request( - self, - method: str, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Build and send a request. - - Equivalent to: - - ```python - request = client.build_request(...) - response = await client.send(request, ...) - ``` - - See `AsyncClient.build_request()`, `AsyncClient.send()` - and [Merging of configuration][0] for how the various parameters - are merged with client-level configuration. - - [0]: /advanced/#merging-of-configuration - """ - request = self.build_request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - extensions=extensions, - ) - return await self.send(request, auth=auth, follow_redirects=follow_redirects) - - @asynccontextmanager - async def stream( - self, - method: str, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> typing.AsyncIterator[Response]: - """ - Alternative to `httpx.request()` that streams the response body - instead of loading it into memory at once. - - **Parameters**: See `httpx.request`. - - See also: [Streaming Responses][0] - - [0]: /quickstart#streaming-responses - """ - request = self.build_request( - method=method, - url=url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - timeout=timeout, - extensions=extensions, - ) - response = await self.send( - request=request, - auth=auth, - follow_redirects=follow_redirects, - stream=True, - ) - try: - yield response - finally: - await response.aclose() - - async def send( - self, - request: Request, - *, - stream: bool = False, - auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - ) -> Response: - """ - Send a request. - - The request is sent as-is, unmodified. - - Typically you'll want to build one with `AsyncClient.build_request()` - so that any client-level configuration is merged into the request, - but passing an explicit `httpx.Request()` is supported as well. - - See also: [Request instances][0] - - [0]: /advanced/#request-instances - """ - if self._state == ClientState.CLOSED: - raise RuntimeError("Cannot send a request, as the client has been closed.") - - self._state = ClientState.OPENED - follow_redirects = ( - self.follow_redirects - if isinstance(follow_redirects, UseClientDefault) - else follow_redirects - ) - - auth = self._build_request_auth(request, auth) - - response = await self._send_handling_auth( - request, - auth=auth, - follow_redirects=follow_redirects, - history=[], - ) - try: - if not stream: - await response.aread() - - return response - - except BaseException as exc: # pragma: no cover - await response.aclose() - raise exc - - async def _send_handling_auth( - self, - request: Request, - auth: Auth, - follow_redirects: bool, - history: typing.List[Response], - ) -> Response: - auth_flow = auth.async_auth_flow(request) - try: - request = await auth_flow.__anext__() - - while True: - response = await self._send_handling_redirects( - request, - follow_redirects=follow_redirects, - history=history, - ) - try: - try: - next_request = await auth_flow.asend(response) - except StopAsyncIteration: - return response - - response.history = list(history) - await response.aread() - request = next_request - history.append(response) - - except BaseException as exc: - await response.aclose() - raise exc - finally: - await auth_flow.aclose() - - async def _send_handling_redirects( - self, - request: Request, - follow_redirects: bool, - history: typing.List[Response], - ) -> Response: - while True: - if len(history) > self.max_redirects: - raise TooManyRedirects( - "Exceeded maximum allowed redirects.", request=request - ) - - for hook in self._event_hooks["request"]: - await hook(request) - - response = await self._send_single_request(request) - try: - for hook in self._event_hooks["response"]: - await hook(response) - - response.history = list(history) - - if not response.has_redirect_location: - return response - - request = self._build_redirect_request(request, response) - history = history + [response] - - if follow_redirects: - await response.aread() - else: - response.next_request = request - return response - - except BaseException as exc: - await response.aclose() - raise exc - - async def _send_single_request(self, request: Request) -> Response: - """ - Sends a single request, without handling any redirections. - """ - transport = self._transport_for_url(request.url) - timer = Timer() - await timer.async_start() - - if not isinstance(request.stream, AsyncByteStream): - raise RuntimeError( - "Attempted to send an sync request with an AsyncClient instance." - ) - - with request_context(request=request): - response = await transport.handle_async_request(request) - - assert isinstance(response.stream, AsyncByteStream) - response.request = request - response.stream = BoundAsyncStream( - response.stream, response=response, timer=timer - ) - self.cookies.extract_cookies(response) - response.default_encoding = self._default_encoding - - logger.info( - 'HTTP Request: %s %s "%s %d %s"', - request.method, - request.url, - response.http_version, - response.status_code, - response.reason_phrase, - ) - - return response - - async def get( - self, - url: URLTypes, - *, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault, None] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `GET` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "GET", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def options( - self, - url: URLTypes, - *, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send an `OPTIONS` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "OPTIONS", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def head( - self, - url: URLTypes, - *, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `HEAD` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "HEAD", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def post( - self, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `POST` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "POST", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def put( - self, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `PUT` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "PUT", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def patch( - self, - url: URLTypes, - *, - content: typing.Optional[RequestContent] = None, - data: typing.Optional[RequestData] = None, - files: typing.Optional[RequestFiles] = None, - json: typing.Optional[typing.Any] = None, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `PATCH` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "PATCH", - url, - content=content, - data=data, - files=files, - json=json, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def delete( - self, - url: URLTypes, - *, - params: typing.Optional[QueryParamTypes] = None, - headers: typing.Optional[HeaderTypes] = None, - cookies: typing.Optional[CookieTypes] = None, - auth: typing.Union[AuthTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - follow_redirects: typing.Union[bool, UseClientDefault] = USE_CLIENT_DEFAULT, - timeout: typing.Union[TimeoutTypes, UseClientDefault] = USE_CLIENT_DEFAULT, - extensions: typing.Optional[RequestExtensions] = None, - ) -> Response: - """ - Send a `DELETE` request. - - **Parameters**: See `httpx.request`. - """ - return await self.request( - "DELETE", - url, - params=params, - headers=headers, - cookies=cookies, - auth=auth, - follow_redirects=follow_redirects, - timeout=timeout, - extensions=extensions, - ) - - async def aclose(self) -> None: - """ - Close transport and proxies. - """ - if self._state != ClientState.CLOSED: - self._state = ClientState.CLOSED - - await self._transport.aclose() - for proxy in self._mounts.values(): - if proxy is not None: - await proxy.aclose() - - async def __aenter__(self: U) -> U: - if self._state != ClientState.UNOPENED: - msg = { - ClientState.OPENED: "Cannot open a client instance more than once.", - ClientState.CLOSED: "Cannot reopen a client instance, once it has been closed.", - }[self._state] - raise RuntimeError(msg) - - self._state = ClientState.OPENED - - await self._transport.__aenter__() - for proxy in self._mounts.values(): - if proxy is not None: - await proxy.__aenter__() - return self - - async def __aexit__( - self, - exc_type: typing.Optional[typing.Type[BaseException]] = None, - exc_value: typing.Optional[BaseException] = None, - traceback: typing.Optional[TracebackType] = None, - ) -> None: - self._state = ClientState.CLOSED - - await self._transport.__aexit__(exc_type, exc_value, traceback) - for proxy in self._mounts.values(): - if proxy is not None: - await proxy.__aexit__(exc_type, exc_value, traceback) diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/matplotlib/animation.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/matplotlib/animation.py deleted file mode 100644 index 2d8156a51599bdf766541365b0da38657dd95bd4..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/matplotlib/animation.py +++ /dev/null @@ -1,1790 +0,0 @@ -# TODO: -# * Documentation -- this will need a new section of the User's Guide. -# Both for Animations and just timers. -# - Also need to update -# https://scipy-cookbook.readthedocs.io/items/Matplotlib_Animations.html -# * Blit -# * Currently broken with Qt4 for widgets that don't start on screen -# * Still a few edge cases that aren't working correctly -# * Can this integrate better with existing matplotlib animation artist flag? -# - If animated removes from default draw(), perhaps we could use this to -# simplify initial draw. -# * Example -# * Frameless animation - pure procedural with no loop -# * Need example that uses something like inotify or subprocess -# * Complex syncing examples -# * Movies -# * Can blit be enabled for movies? -# * Need to consider event sources to allow clicking through multiple figures - - -import abc -import base64 -import contextlib -from io import BytesIO, TextIOWrapper -import itertools -import logging -from pathlib import Path -import shutil -import subprocess -import sys -from tempfile import TemporaryDirectory -import uuid -import warnings - -import numpy as np -from PIL import Image - -import matplotlib as mpl -from matplotlib._animation_data import ( - DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE) -from matplotlib import _api, cbook -import matplotlib.colors as mcolors - -_log = logging.getLogger(__name__) - -# Process creation flag for subprocess to prevent it raising a terminal -# window. See for example https://stackoverflow.com/q/24130623/ -subprocess_creation_flags = ( - subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0) - -# Other potential writing methods: -# * http://pymedia.org/ -# * libming (produces swf) python wrappers: https://github.com/libming/libming -# * Wrap x264 API: - -# (https://stackoverflow.com/q/2940671/) - - -def adjusted_figsize(w, h, dpi, n): - """ - Compute figure size so that pixels are a multiple of n. - - Parameters - ---------- - w, h : float - Size in inches. - - dpi : float - The dpi. - - n : int - The target multiple. - - Returns - ------- - wnew, hnew : float - The new figure size in inches. - """ - - # this maybe simplified if / when we adopt consistent rounding for - # pixel size across the whole library - def correct_roundoff(x, dpi, n): - if int(x*dpi) % n != 0: - if int(np.nextafter(x, np.inf)*dpi) % n == 0: - x = np.nextafter(x, np.inf) - elif int(np.nextafter(x, -np.inf)*dpi) % n == 0: - x = np.nextafter(x, -np.inf) - return x - - wnew = int(w * dpi / n) * n / dpi - hnew = int(h * dpi / n) * n / dpi - return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n) - - -class MovieWriterRegistry: - """Registry of available writer classes by human readable name.""" - - def __init__(self): - self._registered = dict() - - def register(self, name): - """ - Decorator for registering a class under a name. - - Example use:: - - @registry.register(name) - class Foo: - pass - """ - def wrapper(writer_cls): - self._registered[name] = writer_cls - return writer_cls - return wrapper - - def is_available(self, name): - """ - Check if given writer is available by name. - - Parameters - ---------- - name : str - - Returns - ------- - bool - """ - try: - cls = self._registered[name] - except KeyError: - return False - return cls.isAvailable() - - def __iter__(self): - """Iterate over names of available writer class.""" - for name in self._registered: - if self.is_available(name): - yield name - - def list(self): - """Get a list of available MovieWriters.""" - return [*self] - - def __getitem__(self, name): - """Get an available writer class from its name.""" - if self.is_available(name): - return self._registered[name] - raise RuntimeError(f"Requested MovieWriter ({name}) not available") - - -writers = MovieWriterRegistry() - - -class AbstractMovieWriter(abc.ABC): - """ - Abstract base class for writing movies, providing a way to grab frames by - calling `~AbstractMovieWriter.grab_frame`. - - `setup` is called to start the process and `finish` is called afterwards. - `saving` is provided as a context manager to facilitate this process as :: - - with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100): - # Iterate over frames - moviewriter.grab_frame(**savefig_kwargs) - - The use of the context manager ensures that `setup` and `finish` are - performed as necessary. - - An instance of a concrete subclass of this class can be given as the - ``writer`` argument of `Animation.save()`. - """ - - def __init__(self, fps=5, metadata=None, codec=None, bitrate=None): - self.fps = fps - self.metadata = metadata if metadata is not None else {} - self.codec = ( - mpl.rcParams['animation.codec'] if codec is None else codec) - self.bitrate = ( - mpl.rcParams['animation.bitrate'] if bitrate is None else bitrate) - - @abc.abstractmethod - def setup(self, fig, outfile, dpi=None): - """ - Setup for writing the movie file. - - Parameters - ---------- - fig : `~matplotlib.figure.Figure` - The figure object that contains the information for frames. - outfile : str - The filename of the resulting movie file. - dpi : float, default: ``fig.dpi`` - The DPI (or resolution) for the file. This controls the size - in pixels of the resulting movie file. - """ - # Check that path is valid - Path(outfile).parent.resolve(strict=True) - self.outfile = outfile - self.fig = fig - if dpi is None: - dpi = self.fig.dpi - self.dpi = dpi - - @property - def frame_size(self): - """A tuple ``(width, height)`` in pixels of a movie frame.""" - w, h = self.fig.get_size_inches() - return int(w * self.dpi), int(h * self.dpi) - - @abc.abstractmethod - def grab_frame(self, **savefig_kwargs): - """ - Grab the image information from the figure and save as a movie frame. - - All keyword arguments in *savefig_kwargs* are passed on to the - `~.Figure.savefig` call that saves the figure. - """ - - @abc.abstractmethod - def finish(self): - """Finish any processing for writing the movie.""" - - @contextlib.contextmanager - def saving(self, fig, outfile, dpi, *args, **kwargs): - """ - Context manager to facilitate writing the movie file. - - ``*args, **kw`` are any parameters that should be passed to `setup`. - """ - # This particular sequence is what contextlib.contextmanager wants - self.setup(fig, outfile, dpi, *args, **kwargs) - try: - yield self - finally: - self.finish() - - -class MovieWriter(AbstractMovieWriter): - """ - Base class for writing movies. - - This is a base class for MovieWriter subclasses that write a movie frame - data to a pipe. You cannot instantiate this class directly. - See examples for how to use its subclasses. - - Attributes - ---------- - frame_format : str - The format used in writing frame data, defaults to 'rgba'. - fig : `~matplotlib.figure.Figure` - The figure to capture data from. - This must be provided by the subclasses. - """ - - # Builtin writer subclasses additionally define the _exec_key and _args_key - # attributes, which indicate the rcParams entries where the path to the - # executable and additional command-line arguments to the executable are - # stored. Third-party writers cannot meaningfully set these as they cannot - # extend rcParams with new keys. - - # Pipe-based writers only support RGBA, but file-based ones support more - # formats. - supported_formats = ["rgba"] - - def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None, - metadata=None): - """ - Parameters - ---------- - fps : int, default: 5 - Movie frame rate (per second). - codec : str or None, default: :rc:`animation.codec` - The codec to use. - bitrate : int, default: :rc:`animation.bitrate` - The bitrate of the movie, in kilobits per second. Higher values - means higher quality movies, but increase the file size. A value - of -1 lets the underlying movie encoder select the bitrate. - extra_args : list of str or None, optional - Extra command-line arguments passed to the underlying movie - encoder. The default, None, means to use - :rc:`animation.[name-of-encoder]_args` for the builtin writers. - metadata : dict[str, str], default: {} - A dictionary of keys and values for metadata to include in the - output file. Some keys that may be of use include: - title, artist, genre, subject, copyright, srcform, comment. - """ - if type(self) is MovieWriter: - # TODO MovieWriter is still an abstract class and needs to be - # extended with a mixin. This should be clearer in naming - # and description. For now, just give a reasonable error - # message to users. - raise TypeError( - 'MovieWriter cannot be instantiated directly. Please use one ' - 'of its subclasses.') - - super().__init__(fps=fps, metadata=metadata, codec=codec, - bitrate=bitrate) - self.frame_format = self.supported_formats[0] - self.extra_args = extra_args - - def _adjust_frame_size(self): - if self.codec == 'h264': - wo, ho = self.fig.get_size_inches() - w, h = adjusted_figsize(wo, ho, self.dpi, 2) - if (wo, ho) != (w, h): - self.fig.set_size_inches(w, h, forward=True) - _log.info('figure size in inches has been adjusted ' - 'from %s x %s to %s x %s', wo, ho, w, h) - else: - w, h = self.fig.get_size_inches() - _log.debug('frame size in pixels is %s x %s', *self.frame_size) - return w, h - - def setup(self, fig, outfile, dpi=None): - # docstring inherited - super().setup(fig, outfile, dpi=dpi) - self._w, self._h = self._adjust_frame_size() - # Run here so that grab_frame() can write the data to a pipe. This - # eliminates the need for temp files. - self._run() - - def _run(self): - # Uses subprocess to call the program for assembling frames into a - # movie file. *args* returns the sequence of command line arguments - # from a few configuration options. - command = self._args() - _log.info('MovieWriter._run: running command: %s', - cbook._pformat_subprocess(command)) - PIPE = subprocess.PIPE - self._proc = subprocess.Popen( - command, stdin=PIPE, stdout=PIPE, stderr=PIPE, - creationflags=subprocess_creation_flags) - - def finish(self): - """Finish any processing for writing the movie.""" - out, err = self._proc.communicate() - # Use the encoding/errors that universal_newlines would use. - out = TextIOWrapper(BytesIO(out)).read() - err = TextIOWrapper(BytesIO(err)).read() - if out: - _log.log( - logging.WARNING if self._proc.returncode else logging.DEBUG, - "MovieWriter stdout:\n%s", out) - if err: - _log.log( - logging.WARNING if self._proc.returncode else logging.DEBUG, - "MovieWriter stderr:\n%s", err) - if self._proc.returncode: - raise subprocess.CalledProcessError( - self._proc.returncode, self._proc.args, out, err) - - def grab_frame(self, **savefig_kwargs): - # docstring inherited - _log.debug('MovieWriter.grab_frame: Grabbing frame.') - # Readjust the figure size in case it has been changed by the user. - # All frames must have the same size to save the movie correctly. - self.fig.set_size_inches(self._w, self._h) - # Save the figure data to the sink, using the frame format and dpi. - self.fig.savefig(self._proc.stdin, format=self.frame_format, - dpi=self.dpi, **savefig_kwargs) - - def _args(self): - """Assemble list of encoder-specific command-line arguments.""" - return NotImplementedError("args needs to be implemented by subclass.") - - @classmethod - def bin_path(cls): - """ - Return the binary path to the commandline tool used by a specific - subclass. This is a class method so that the tool can be looked for - before making a particular MovieWriter subclass available. - """ - return str(mpl.rcParams[cls._exec_key]) - - @classmethod - def isAvailable(cls): - """Return whether a MovieWriter subclass is actually available.""" - return shutil.which(cls.bin_path()) is not None - - -class FileMovieWriter(MovieWriter): - """ - `MovieWriter` for writing to individual files and stitching at the end. - - This must be sub-classed to be useful. - """ - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.frame_format = mpl.rcParams['animation.frame_format'] - - def setup(self, fig, outfile, dpi=None, frame_prefix=None): - """ - Setup for writing the movie file. - - Parameters - ---------- - fig : `~matplotlib.figure.Figure` - The figure to grab the rendered frames from. - outfile : str - The filename of the resulting movie file. - dpi : float, default: ``fig.dpi`` - The dpi of the output file. This, with the figure size, - controls the size in pixels of the resulting movie file. - frame_prefix : str, optional - The filename prefix to use for temporary files. If *None* (the - default), files are written to a temporary directory which is - deleted by `finish`; if not *None*, no temporary files are - deleted. - """ - # Check that path is valid - Path(outfile).parent.resolve(strict=True) - self.fig = fig - self.outfile = outfile - if dpi is None: - dpi = self.fig.dpi - self.dpi = dpi - self._adjust_frame_size() - - if frame_prefix is None: - self._tmpdir = TemporaryDirectory() - self.temp_prefix = str(Path(self._tmpdir.name, 'tmp')) - else: - self._tmpdir = None - self.temp_prefix = frame_prefix - self._frame_counter = 0 # used for generating sequential file names - self._temp_paths = list() - self.fname_format_str = '%s%%07d.%s' - - def __del__(self): - if hasattr(self, '_tmpdir') and self._tmpdir: - self._tmpdir.cleanup() - - @property - def frame_format(self): - """ - Format (png, jpeg, etc.) to use for saving the frames, which can be - decided by the individual subclasses. - """ - return self._frame_format - - @frame_format.setter - def frame_format(self, frame_format): - if frame_format in self.supported_formats: - self._frame_format = frame_format - else: - _api.warn_external( - f"Ignoring file format {frame_format!r} which is not " - f"supported by {type(self).__name__}; using " - f"{self.supported_formats[0]} instead.") - self._frame_format = self.supported_formats[0] - - def _base_temp_name(self): - # Generates a template name (without number) given the frame format - # for extension and the prefix. - return self.fname_format_str % (self.temp_prefix, self.frame_format) - - def grab_frame(self, **savefig_kwargs): - # docstring inherited - # Creates a filename for saving using basename and counter. - path = Path(self._base_temp_name() % self._frame_counter) - self._temp_paths.append(path) # Record the filename for later use. - self._frame_counter += 1 # Ensures each created name is unique. - _log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s', - self._frame_counter, path) - with open(path, 'wb') as sink: # Save figure to the sink. - self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi, - **savefig_kwargs) - - def finish(self): - # Call run here now that all frame grabbing is done. All temp files - # are available to be assembled. - try: - self._run() - super().finish() - finally: - if self._tmpdir: - _log.debug( - 'MovieWriter: clearing temporary path=%s', self._tmpdir - ) - self._tmpdir.cleanup() - - -@writers.register('pillow') -class PillowWriter(AbstractMovieWriter): - @classmethod - def isAvailable(cls): - return True - - def setup(self, fig, outfile, dpi=None): - super().setup(fig, outfile, dpi=dpi) - self._frames = [] - - def grab_frame(self, **savefig_kwargs): - buf = BytesIO() - self.fig.savefig( - buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi}) - self._frames.append(Image.frombuffer( - "RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)) - - def finish(self): - self._frames[0].save( - self.outfile, save_all=True, append_images=self._frames[1:], - duration=int(1000 / self.fps), loop=0) - - -# Base class of ffmpeg information. Has the config keys and the common set -# of arguments that controls the *output* side of things. -class FFMpegBase: - """ - Mixin class for FFMpeg output. - - This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter` - classes. - """ - - _exec_key = 'animation.ffmpeg_path' - _args_key = 'animation.ffmpeg_args' - - @property - def output_args(self): - args = [] - if Path(self.outfile).suffix == '.gif': - self.codec = 'gif' - else: - args.extend(['-vcodec', self.codec]) - extra_args = (self.extra_args if self.extra_args is not None - else mpl.rcParams[self._args_key]) - # For h264, the default format is yuv444p, which is not compatible - # with quicktime (and others). Specifying yuv420p fixes playback on - # iOS, as well as HTML5 video in firefox and safari (on both Win and - # OSX). Also fixes internet explorer. This is as of 2015/10/29. - if self.codec == 'h264' and '-pix_fmt' not in extra_args: - args.extend(['-pix_fmt', 'yuv420p']) - # For GIF, we're telling FFMPEG to split the video stream, to generate - # a palette, and then use it for encoding. - elif self.codec == 'gif' and '-filter_complex' not in extra_args: - args.extend(['-filter_complex', - 'split [a][b];[a] palettegen [p];[b][p] paletteuse']) - if self.bitrate > 0: - args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps. - args.extend(extra_args) - for k, v in self.metadata.items(): - args.extend(['-metadata', '%s=%s' % (k, v)]) - - return args + ['-y', self.outfile] - - -# Combine FFMpeg options with pipe-based writing -@writers.register('ffmpeg') -class FFMpegWriter(FFMpegBase, MovieWriter): - """ - Pipe-based ffmpeg writer. - - Frames are streamed directly to ffmpeg via a pipe and written in a single - pass. - """ - def _args(self): - # Returns the command line parameters for subprocess to use - # ffmpeg to create a movie using a pipe. - args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo', - '-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format, - '-r', str(self.fps)] - # Logging is quieted because subprocess.PIPE has limited buffer size. - # If you have a lot of frames in your animation and set logging to - # DEBUG, you will have a buffer overrun. - if _log.getEffectiveLevel() > logging.DEBUG: - args += ['-loglevel', 'error'] - args += ['-i', 'pipe:'] + self.output_args - return args - - -# Combine FFMpeg options with temp file-based writing -@writers.register('ffmpeg_file') -class FFMpegFileWriter(FFMpegBase, FileMovieWriter): - """ - File-based ffmpeg writer. - - Frames are written to temporary files on disk and then stitched - together at the end. - """ - supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba'] - - def _args(self): - # Returns the command line parameters for subprocess to use - # ffmpeg to create a movie using a collection of temp images - args = [] - # For raw frames, we need to explicitly tell ffmpeg the metadata. - if self.frame_format in {'raw', 'rgba'}: - args += [ - '-f', 'image2', '-vcodec', 'rawvideo', - '-video_size', '%dx%d' % self.frame_size, - '-pixel_format', 'rgba', - '-framerate', str(self.fps), - ] - args += ['-r', str(self.fps), '-i', self._base_temp_name(), - '-vframes', str(self._frame_counter)] - # Logging is quieted because subprocess.PIPE has limited buffer size. - # If you have a lot of frames in your animation and set logging to - # DEBUG, you will have a buffer overrun. - if _log.getEffectiveLevel() > logging.DEBUG: - args += ['-loglevel', 'error'] - return [self.bin_path(), *args, *self.output_args] - - -# Base class for animated GIFs with ImageMagick -class ImageMagickBase: - """ - Mixin class for ImageMagick output. - - This is a base class for the concrete `ImageMagickWriter` and - `ImageMagickFileWriter` classes, which define an ``input_names`` attribute - (or property) specifying the input names passed to ImageMagick. - """ - - _exec_key = 'animation.convert_path' - _args_key = 'animation.convert_args' - - @_api.deprecated("3.6") - @property - def delay(self): - return 100. / self.fps - - @_api.deprecated("3.6") - @property - def output_args(self): - extra_args = (self.extra_args if self.extra_args is not None - else mpl.rcParams[self._args_key]) - return [*extra_args, self.outfile] - - def _args(self): - # ImageMagick does not recognize "raw". - fmt = "rgba" if self.frame_format == "raw" else self.frame_format - extra_args = (self.extra_args if self.extra_args is not None - else mpl.rcParams[self._args_key]) - return [ - self.bin_path(), - "-size", "%ix%i" % self.frame_size, - "-depth", "8", - "-delay", str(100 / self.fps), - "-loop", "0", - f"{fmt}:{self.input_names}", - *extra_args, - self.outfile, - ] - - @classmethod - def bin_path(cls): - binpath = super().bin_path() - if binpath == 'convert': - binpath = mpl._get_executable_info('magick').executable - return binpath - - @classmethod - def isAvailable(cls): - try: - return super().isAvailable() - except mpl.ExecutableNotFoundError as _enf: - # May be raised by get_executable_info. - _log.debug('ImageMagick unavailable due to: %s', _enf) - return False - - -# Combine ImageMagick options with pipe-based writing -@writers.register('imagemagick') -class ImageMagickWriter(ImageMagickBase, MovieWriter): - """ - Pipe-based animated gif writer. - - Frames are streamed directly to ImageMagick via a pipe and written - in a single pass. - """ - - input_names = "-" # stdin - - -# Combine ImageMagick options with temp file-based writing -@writers.register('imagemagick_file') -class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter): - """ - File-based animated gif writer. - - Frames are written to temporary files on disk and then stitched - together at the end. - """ - - supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba'] - input_names = property( - lambda self: f'{self.temp_prefix}*.{self.frame_format}') - - -# Taken directly from jakevdp's JSAnimation package at -# http://github.com/jakevdp/JSAnimation -def _included_frames(frame_count, frame_format, frame_dir): - return INCLUDED_FRAMES.format(Nframes=frame_count, - frame_dir=frame_dir, - frame_format=frame_format) - - -def _embedded_frames(frame_list, frame_format): - """frame_list should be a list of base64-encoded png files""" - if frame_format == 'svg': - # Fix MIME type for svg - frame_format = 'svg+xml' - template = ' frames[{0}] = "data:image/{1};base64,{2}"\n' - return "\n" + "".join( - template.format(i, frame_format, frame_data.replace('\n', '\\\n')) - for i, frame_data in enumerate(frame_list)) - - -@writers.register('html') -class HTMLWriter(FileMovieWriter): - """Writer for JavaScript-based HTML movies.""" - - supported_formats = ['png', 'jpeg', 'tiff', 'svg'] - - @classmethod - def isAvailable(cls): - return True - - def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None, - metadata=None, embed_frames=False, default_mode='loop', - embed_limit=None): - - if extra_args: - _log.warning("HTMLWriter ignores 'extra_args'") - extra_args = () # Don't lookup nonexistent rcParam[args_key]. - self.embed_frames = embed_frames - self.default_mode = default_mode.lower() - _api.check_in_list(['loop', 'once', 'reflect'], - default_mode=self.default_mode) - - # Save embed limit, which is given in MB - if embed_limit is None: - self._bytes_limit = mpl.rcParams['animation.embed_limit'] - else: - self._bytes_limit = embed_limit - # Convert from MB to bytes - self._bytes_limit *= 1024 * 1024 - - super().__init__(fps, codec, bitrate, extra_args, metadata) - - def setup(self, fig, outfile, dpi=None, frame_dir=None): - outfile = Path(outfile) - _api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix) - - self._saved_frames = [] - self._total_bytes = 0 - self._hit_limit = False - - if not self.embed_frames: - if frame_dir is None: - frame_dir = outfile.with_name(outfile.stem + '_frames') - frame_dir.mkdir(parents=True, exist_ok=True) - frame_prefix = frame_dir / 'frame' - else: - frame_prefix = None - - super().setup(fig, outfile, dpi, frame_prefix) - self._clear_temp = False - - def grab_frame(self, **savefig_kwargs): - if self.embed_frames: - # Just stop processing if we hit the limit - if self._hit_limit: - return - f = BytesIO() - self.fig.savefig(f, format=self.frame_format, - dpi=self.dpi, **savefig_kwargs) - imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii') - self._total_bytes += len(imgdata64) - if self._total_bytes >= self._bytes_limit: - _log.warning( - "Animation size has reached %s bytes, exceeding the limit " - "of %s. If you're sure you want a larger animation " - "embedded, set the animation.embed_limit rc parameter to " - "a larger value (in MB). This and further frames will be " - "dropped.", self._total_bytes, self._bytes_limit) - self._hit_limit = True - else: - self._saved_frames.append(imgdata64) - else: - return super().grab_frame(**savefig_kwargs) - - def finish(self): - # save the frames to an html file - if self.embed_frames: - fill_frames = _embedded_frames(self._saved_frames, - self.frame_format) - frame_count = len(self._saved_frames) - else: - # temp names is filled by FileMovieWriter - frame_count = len(self._temp_paths) - fill_frames = _included_frames( - frame_count, self.frame_format, - self._temp_paths[0].parent.relative_to(self.outfile.parent)) - mode_dict = dict(once_checked='', - loop_checked='', - reflect_checked='') - mode_dict[self.default_mode + '_checked'] = 'checked' - - interval = 1000 // self.fps - - with open(self.outfile, 'w') as of: - of.write(JS_INCLUDE + STYLE_INCLUDE) - of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex, - Nframes=frame_count, - fill_frames=fill_frames, - interval=interval, - **mode_dict)) - - # Duplicate the temporary file clean up logic from - # FileMovieWriter.finish. We can not call the inherited version of - # finish because it assumes that there is a subprocess that we either - # need to call to merge many frames together or that there is a - # subprocess call that we need to clean up. - if self._tmpdir: - _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir) - self._tmpdir.cleanup() - - -class Animation: - """ - A base class for Animations. - - This class is not usable as is, and should be subclassed to provide needed - behavior. - - .. note:: - - You must store the created Animation in a variable that lives as long - as the animation should run. Otherwise, the Animation object will be - garbage-collected and the animation stops. - - Parameters - ---------- - fig : `~matplotlib.figure.Figure` - The figure object used to get needed events, such as draw or resize. - - event_source : object, optional - A class that can run a callback when desired events - are generated, as well as be stopped and started. - - Examples include timers (see `TimedAnimation`) and file - system notifications. - - blit : bool, default: False - Whether blitting is used to optimize drawing. If the backend does not - support blitting, then this parameter has no effect. - - See Also - -------- - FuncAnimation, ArtistAnimation - """ - - def __init__(self, fig, event_source=None, blit=False): - self._draw_was_started = False - - self._fig = fig - # Disables blitting for backends that don't support it. This - # allows users to request it if available, but still have a - # fallback that works if it is not. - self._blit = blit and fig.canvas.supports_blit - - # These are the basics of the animation. The frame sequence represents - # information for each frame of the animation and depends on how the - # drawing is handled by the subclasses. The event source fires events - # that cause the frame sequence to be iterated. - self.frame_seq = self.new_frame_seq() - self.event_source = event_source - - # Instead of starting the event source now, we connect to the figure's - # draw_event, so that we only start once the figure has been drawn. - self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start) - - # Connect to the figure's close_event so that we don't continue to - # fire events and try to draw to a deleted figure. - self._close_id = self._fig.canvas.mpl_connect('close_event', - self._stop) - if self._blit: - self._setup_blit() - - def __del__(self): - if not getattr(self, '_draw_was_started', True): - warnings.warn( - 'Animation was deleted without rendering anything. This is ' - 'most likely not intended. To prevent deletion, assign the ' - 'Animation to a variable, e.g. `anim`, that exists until you ' - 'output the Animation using `plt.show()` or ' - '`anim.save()`.' - ) - - def _start(self, *args): - """ - Starts interactive animation. Adds the draw frame command to the GUI - handler, calls show to start the event loop. - """ - # Do not start the event source if saving() it. - if self._fig.canvas.is_saving(): - return - # First disconnect our draw event handler - self._fig.canvas.mpl_disconnect(self._first_draw_id) - - # Now do any initial draw - self._init_draw() - - # Add our callback for stepping the animation and - # actually start the event_source. - self.event_source.add_callback(self._step) - self.event_source.start() - - def _stop(self, *args): - # On stop we disconnect all of our events. - if self._blit: - self._fig.canvas.mpl_disconnect(self._resize_id) - self._fig.canvas.mpl_disconnect(self._close_id) - self.event_source.remove_callback(self._step) - self.event_source = None - - def save(self, filename, writer=None, fps=None, dpi=None, codec=None, - bitrate=None, extra_args=None, metadata=None, extra_anim=None, - savefig_kwargs=None, *, progress_callback=None): - """ - Save the animation as a movie file by drawing every frame. - - Parameters - ---------- - filename : str - The output filename, e.g., :file:`mymovie.mp4`. - - writer : `MovieWriter` or str, default: :rc:`animation.writer` - A `MovieWriter` instance to use or a key that identifies a - class to use, such as 'ffmpeg'. - - fps : int, optional - Movie frame rate (per second). If not set, the frame rate from the - animation's frame interval. - - dpi : float, default: :rc:`savefig.dpi` - Controls the dots per inch for the movie frames. Together with - the figure's size in inches, this controls the size of the movie. - - codec : str, default: :rc:`animation.codec`. - The video codec to use. Not all codecs are supported by a given - `MovieWriter`. - - bitrate : int, default: :rc:`animation.bitrate` - The bitrate of the movie, in kilobits per second. Higher values - means higher quality movies, but increase the file size. A value - of -1 lets the underlying movie encoder select the bitrate. - - extra_args : list of str or None, optional - Extra command-line arguments passed to the underlying movie - encoder. The default, None, means to use - :rc:`animation.[name-of-encoder]_args` for the builtin writers. - - metadata : dict[str, str], default: {} - Dictionary of keys and values for metadata to include in - the output file. Some keys that may be of use include: - title, artist, genre, subject, copyright, srcform, comment. - - extra_anim : list, default: [] - Additional `Animation` objects that should be included - in the saved movie file. These need to be from the same - `.Figure` instance. Also, animation frames will - just be simply combined, so there should be a 1:1 correspondence - between the frames from the different animations. - - savefig_kwargs : dict, default: {} - Keyword arguments passed to each `~.Figure.savefig` call used to - save the individual frames. - - progress_callback : function, optional - A callback function that will be called for every frame to notify - the saving progress. It must have the signature :: - - def func(current_frame: int, total_frames: int) -> Any - - where *current_frame* is the current frame number and - *total_frames* is the total number of frames to be saved. - *total_frames* is set to None, if the total number of frames can - not be determined. Return values may exist but are ignored. - - Example code to write the progress to stdout:: - - progress_callback = lambda i, n: print(f'Saving frame {i}/{n}') - - Notes - ----- - *fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to - construct a `.MovieWriter` instance and can only be passed if - *writer* is a string. If they are passed as non-*None* and *writer* - is a `.MovieWriter`, a `RuntimeError` will be raised. - """ - - all_anim = [self] - if extra_anim is not None: - all_anim.extend(anim for anim in extra_anim - if anim._fig is self._fig) - - # Disable "Animation was deleted without rendering" warning. - for anim in all_anim: - anim._draw_was_started = True - - if writer is None: - writer = mpl.rcParams['animation.writer'] - elif (not isinstance(writer, str) and - any(arg is not None - for arg in (fps, codec, bitrate, extra_args, metadata))): - raise RuntimeError('Passing in values for arguments ' - 'fps, codec, bitrate, extra_args, or metadata ' - 'is not supported when writer is an existing ' - 'MovieWriter instance. These should instead be ' - 'passed as arguments when creating the ' - 'MovieWriter instance.') - - if savefig_kwargs is None: - savefig_kwargs = {} - else: - # we are going to mutate this below - savefig_kwargs = dict(savefig_kwargs) - - if fps is None and hasattr(self, '_interval'): - # Convert interval in ms to frames per second - fps = 1000. / self._interval - - # Re-use the savefig DPI for ours if none is given - if dpi is None: - dpi = mpl.rcParams['savefig.dpi'] - if dpi == 'figure': - dpi = self._fig.dpi - - writer_kwargs = {} - if codec is not None: - writer_kwargs['codec'] = codec - if bitrate is not None: - writer_kwargs['bitrate'] = bitrate - if extra_args is not None: - writer_kwargs['extra_args'] = extra_args - if metadata is not None: - writer_kwargs['metadata'] = metadata - - # If we have the name of a writer, instantiate an instance of the - # registered class. - if isinstance(writer, str): - try: - writer_cls = writers[writer] - except RuntimeError: # Raised if not available. - writer_cls = PillowWriter # Always available. - _log.warning("MovieWriter %s unavailable; using Pillow " - "instead.", writer) - writer = writer_cls(fps, **writer_kwargs) - _log.info('Animation.save using %s', type(writer)) - - if 'bbox_inches' in savefig_kwargs: - _log.warning("Warning: discarding the 'bbox_inches' argument in " - "'savefig_kwargs' as it may cause frame size " - "to vary, which is inappropriate for animation.") - savefig_kwargs.pop('bbox_inches') - - # Create a new sequence of frames for saved data. This is different - # from new_frame_seq() to give the ability to save 'live' generated - # frame information to be saved later. - # TODO: Right now, after closing the figure, saving a movie won't work - # since GUI widgets are gone. Either need to remove extra code to - # allow for this non-existent use case or find a way to make it work. - if mpl.rcParams['savefig.bbox'] == 'tight': - _log.info("Disabling savefig.bbox = 'tight', as it may cause " - "frame size to vary, which is inappropriate for " - "animation.") - - facecolor = savefig_kwargs.get('facecolor', - mpl.rcParams['savefig.facecolor']) - if facecolor == 'auto': - facecolor = self._fig.get_facecolor() - - def _pre_composite_to_white(color): - r, g, b, a = mcolors.to_rgba(color) - return a * np.array([r, g, b]) + 1 - a - - savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor) - savefig_kwargs['transparent'] = False # just to be safe! - # canvas._is_saving = True makes the draw_event animation-starting - # callback a no-op; canvas.manager = None prevents resizing the GUI - # widget (both are likewise done in savefig()). - with mpl.rc_context({'savefig.bbox': None}), \ - writer.saving(self._fig, filename, dpi), \ - cbook._setattr_cm(self._fig.canvas, - _is_saving=True, manager=None): - for anim in all_anim: - anim._init_draw() # Clear the initial frame - frame_number = 0 - # TODO: Currently only FuncAnimation has a save_count - # attribute. Can we generalize this to all Animations? - save_count_list = [getattr(a, '_save_count', None) - for a in all_anim] - if None in save_count_list: - total_frames = None - else: - total_frames = sum(save_count_list) - for data in zip(*[a.new_saved_frame_seq() for a in all_anim]): - for anim, d in zip(all_anim, data): - # TODO: See if turning off blit is really necessary - anim._draw_next_frame(d, blit=False) - if progress_callback is not None: - progress_callback(frame_number, total_frames) - frame_number += 1 - writer.grab_frame(**savefig_kwargs) - - def _step(self, *args): - """ - Handler for getting events. By default, gets the next frame in the - sequence and hands the data off to be drawn. - """ - # Returns True to indicate that the event source should continue to - # call _step, until the frame sequence reaches the end of iteration, - # at which point False will be returned. - try: - framedata = next(self.frame_seq) - self._draw_next_frame(framedata, self._blit) - return True - except StopIteration: - return False - - def new_frame_seq(self): - """Return a new sequence of frame information.""" - # Default implementation is just an iterator over self._framedata - return iter(self._framedata) - - def new_saved_frame_seq(self): - """Return a new sequence of saved/cached frame information.""" - # Default is the same as the regular frame sequence - return self.new_frame_seq() - - def _draw_next_frame(self, framedata, blit): - # Breaks down the drawing of the next frame into steps of pre- and - # post- draw, as well as the drawing of the frame itself. - self._pre_draw(framedata, blit) - self._draw_frame(framedata) - self._post_draw(framedata, blit) - - def _init_draw(self): - # Initial draw to clear the frame. Also used by the blitting code - # when a clean base is required. - self._draw_was_started = True - - def _pre_draw(self, framedata, blit): - # Perform any cleaning or whatnot before the drawing of the frame. - # This default implementation allows blit to clear the frame. - if blit: - self._blit_clear(self._drawn_artists) - - def _draw_frame(self, framedata): - # Performs actual drawing of the frame. - raise NotImplementedError('Needs to be implemented by subclasses to' - ' actually make an animation.') - - def _post_draw(self, framedata, blit): - # After the frame is rendered, this handles the actual flushing of - # the draw, which can be a direct draw_idle() or make use of the - # blitting. - if blit and self._drawn_artists: - self._blit_draw(self._drawn_artists) - else: - self._fig.canvas.draw_idle() - - # The rest of the code in this class is to facilitate easy blitting - def _blit_draw(self, artists): - # Handles blitted drawing, which renders only the artists given instead - # of the entire figure. - updated_ax = {a.axes for a in artists} - # Enumerate artists to cache Axes backgrounds. We do not draw - # artists yet to not cache foreground from plots with shared axes - for ax in updated_ax: - # If we haven't cached the background for the current view of this - # Axes object, do so now. This might not always be reliable, but - # it's an attempt to automate the process. - cur_view = ax._get_view() - view, bg = self._blit_cache.get(ax, (object(), None)) - if cur_view != view: - self._blit_cache[ax] = ( - cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox)) - # Make a separate pass to draw foreground. - for a in artists: - a.axes.draw_artist(a) - # After rendering all the needed artists, blit each Axes individually. - for ax in updated_ax: - ax.figure.canvas.blit(ax.bbox) - - def _blit_clear(self, artists): - # Get a list of the Axes that need clearing from the artists that - # have been drawn. Grab the appropriate saved background from the - # cache and restore. - axes = {a.axes for a in artists} - for ax in axes: - try: - view, bg = self._blit_cache[ax] - except KeyError: - continue - if ax._get_view() == view: - ax.figure.canvas.restore_region(bg) - else: - self._blit_cache.pop(ax) - - def _setup_blit(self): - # Setting up the blit requires: a cache of the background for the Axes - self._blit_cache = dict() - self._drawn_artists = [] - # _post_draw needs to be called first to initialize the renderer - self._post_draw(None, self._blit) - # Then we need to clear the Frame for the initial draw - # This is typically handled in _on_resize because QT and Tk - # emit a resize event on launch, but the macosx backend does not, - # thus we force it here for everyone for consistency - self._init_draw() - # Connect to future resize events - self._resize_id = self._fig.canvas.mpl_connect('resize_event', - self._on_resize) - - def _on_resize(self, event): - # On resize, we need to disable the resize event handling so we don't - # get too many events. Also stop the animation events, so that - # we're paused. Reset the cache and re-init. Set up an event handler - # to catch once the draw has actually taken place. - self._fig.canvas.mpl_disconnect(self._resize_id) - self.event_source.stop() - self._blit_cache.clear() - self._init_draw() - self._resize_id = self._fig.canvas.mpl_connect('draw_event', - self._end_redraw) - - def _end_redraw(self, event): - # Now that the redraw has happened, do the post draw flushing and - # blit handling. Then re-enable all of the original events. - self._post_draw(None, False) - self.event_source.start() - self._fig.canvas.mpl_disconnect(self._resize_id) - self._resize_id = self._fig.canvas.mpl_connect('resize_event', - self._on_resize) - - def to_html5_video(self, embed_limit=None): - """ - Convert the animation to an HTML5 ``